diff --git a/Cargo.lock b/Cargo.lock index eb691b7..df5642d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,12 +18,6 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - [[package]] name = "aead" version = "0.6.1" @@ -45,17 +39,6 @@ dependencies = [ "cpufeatures 0.3.1", ] -[[package]] -name = "ahash" -version = "0.7.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae442e79f0396cdfccee3e4380cc8d4a9fabbd23dc4a25e1bcc7f960693104ed" -dependencies = [ - "getrandom 0.2.17", - "once_cell", - "version_check", -] - [[package]] name = "ahash" version = "0.8.13" @@ -79,12 +62,6 @@ 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-activity" version = "0.6.1" @@ -99,11 +76,20 @@ dependencies = [ "log", "ndk", "ndk-context", - "ndk-sys 0.6.0+11769913", + "ndk-sys", "num_enum", "thiserror 2.0.21", ] +[[package]] +name = "android-build" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9fc9904ad2ad097c3c1cfe2eacaaf0fc24710936fa9ed941cb310b7c6ed2ab7" +dependencies = [ + "windows-sys 0.52.0", +] + [[package]] name = "android-properties" version = "0.2.2" @@ -130,15 +116,6 @@ dependencies = [ "security-framework", ] -[[package]] -name = "approx" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" -dependencies = [ - "num-traits", -] - [[package]] name = "argon2" version = "0.6.0" @@ -171,11 +148,11 @@ checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" [[package]] name = "ash" -version = "0.37.3+1.3.251" +version = "0.38.0+1.3.281" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e9c3835d686b0a6084ab4234fcd1b07dbf6e4767dce60874b12356a25ecd4a" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" dependencies = [ - "libloading 0.7.4", + "libloading", ] [[package]] @@ -216,17 +193,6 @@ dependencies = [ "slab", ] -[[package]] -name = "async-fs" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5" -dependencies = [ - "async-lock", - "blocking", - "futures-lite", -] - [[package]] name = "async-io" version = "2.6.0" @@ -375,18 +341,18 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" [[package]] name = "bit-set" -version = "0.5.3" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" dependencies = [ "bit-vec", ] [[package]] name = "bit-vec" -version = "0.6.3" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" [[package]] name = "bitflags" @@ -479,12 +445,6 @@ version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" -[[package]] -name = "by_address" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" - [[package]] name = "bytemuck" version = "1.25.2" @@ -594,12 +554,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" -[[package]] -name = "cfg_aliases" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" - [[package]] name = "cfg_aliases" version = "0.2.2" @@ -711,43 +665,25 @@ checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" [[package]] name = "codespan-reporting" -version = "0.11.1" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81" dependencies = [ + "serde", "termcolor", "unicode-width", ] [[package]] -name = "com" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e17887fd17353b65b1b2ef1c526c83e26cd72e74f598a8dc1bee13a48f3d9f6" -dependencies = [ - "com_macros", -] - -[[package]] -name = "com_macros" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d375883580a668c7481ea6631fc1a8863e33cc335bf56bfad8d7e6d4b04b13a5" -dependencies = [ - "com_macros_support", - "proc-macro2", - "syn 1.0.109", -] - -[[package]] -name = "com_macros_support" -version = "0.6.0" +name = "colony-ui" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad899a1087a9296d5644792d7cb72b8e34c1bec8e7d4fbc002230169a6e8710c" +checksum = "31984ffb00f64c0fd0b998103ef11e1f4255e8f26c784a3776caf4b9ea28d60b" dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", + "dirs 6.0.0", + "iced", + "serde", + "serde_json", ] [[package]] @@ -809,7 +745,7 @@ checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" dependencies = [ "bitflags 1.3.2", "core-foundation 0.9.4", - "core-graphics-types", + "core-graphics-types 0.1.3", "foreign-types", "libc", ] @@ -825,29 +761,50 @@ dependencies = [ "libc", ] +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "libc", +] + [[package]] name = "core_detect" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + [[package]] name = "cosmic-text" -version = "0.12.1" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59fd57d82eb4bfe7ffa9b1cec0c05e2fd378155b47f255a67983cb4afe0e80c2" +checksum = "173852283a9a57a3cbe365d86e74dc428a09c50421477d5ad6fe9d9509e37737" dependencies = [ "bitflags 2.13.2", "fontdb", + "harfrust", + "linebender_resource_handle", "log", "rangemap", - "rayon", "rustc-hash 1.1.0", - "rustybuzz", "self_cell", + "skrifa 0.37.0", + "smol_str", "swash", "sys-locale", - "ttf-parser 0.21.1", "unicode-bidi", "unicode-linebreak", "unicode-script", @@ -878,15 +835,6 @@ dependencies = [ "libc", ] -[[package]] -name = "crc32fast" -version = "1.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" -dependencies = [ - "cfg-if", -] - [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -896,25 +844,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "crossbeam-deque" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" -dependencies = [ - "crossbeam-utils", -] - [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -927,6 +856,19 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "cryoglyph" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08bc795bdbccdbd461736fb163930a009da6597b226d6f6fce33e7a8eb6ec519" +dependencies = [ + "cosmic-text", + "etagere", + "lru", + "rustc-hash 2.1.3", + "wgpu", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -972,51 +914,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" -[[package]] -name = "d3d12" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e3d747f100290a1ca24b752186f61f6637e1deffe3bf6320de6fcb29510a307" -dependencies = [ - "bitflags 2.13.2", - "libloading 0.8.9", - "winapi", -] - -[[package]] -name = "dark-light" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a76fa97167fa740dcdbfe18e8895601e1bc36525f09b044e00916e717c03a3c" -dependencies = [ - "dconf_rs", - "detect-desktop-environment", - "dirs 4.0.0", - "objc", - "rust-ini", - "web-sys", - "winreg", - "zbus 4.4.0", -] - -[[package]] -name = "dconf_rs" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7046468a81e6a002061c01e6a7c83139daf91b11c30e66795b13217c2d885c8b" - [[package]] name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" -[[package]] -name = "detect-desktop-environment" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21d8ad60dd5b13a4ee6bd8fa2d5d88965c597c67bce32b5fc49c94f55cb50810" - [[package]] name = "digest" version = "0.10.7" @@ -1041,11 +944,11 @@ dependencies = [ [[package]] name = "dirs" -version = "4.0.0" +version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ - "dirs-sys 0.3.7", + "dirs-sys", ] [[package]] @@ -1054,18 +957,7 @@ version = "7.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f" dependencies = [ - "dirs-sys 0.5.0", -] - -[[package]] -name = "dirs-sys" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" -dependencies = [ - "libc", - "redox_users 0.4.6", - "winapi", + "dirs-sys", ] [[package]] @@ -1076,7 +968,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users 0.5.3", + "redox_users", "windows-sys 0.61.2", ] @@ -1115,14 +1007,17 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" dependencies = [ - "libloading 0.8.9", + "libloading", ] [[package]] -name = "dlv-list" -version = "0.3.0" +name = "document-features" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] [[package]] name = "downcast-rs" @@ -1136,46 +1031,6 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" -[[package]] -name = "drm" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" -dependencies = [ - "bitflags 2.13.2", - "bytemuck", - "drm-ffi", - "drm-fourcc", - "libc", - "rustix 0.38.44", -] - -[[package]] -name = "drm-ffi" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" -dependencies = [ - "drm-sys", - "rustix 1.1.6", -] - -[[package]] -name = "drm-fourcc" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" - -[[package]] -name = "drm-sys" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" -dependencies = [ - "libc", - "linux-raw-sys 0.9.4", -] - [[package]] name = "dtor" version = "0.8.1" @@ -1188,12 +1043,6 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" -[[package]] -name = "either" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" - [[package]] name = "encoding_rs" version = "0.8.44" @@ -1302,43 +1151,44 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" -[[package]] -name = "fdeflate" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" -dependencies = [ - "simd-adler32", -] - [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" -[[package]] -name = "flate2" -version = "1.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" -dependencies = [ - "crc32fast", - "miniz_oxide 0.9.1", - "zlib-rs", -] - [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "font-types" -version = "0.7.3" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39a654f404bbcbd48ea58c617c2993ee91d1cb63727a37bf2323a4edeed1b8c5" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "font-types" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3971f9a5ca983419cdc386941ba3b9e1feba01a0ab888adf78739feb2798492" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ "bytemuck", ] @@ -1354,16 +1204,16 @@ dependencies = [ [[package]] name = "fontdb" -version = "0.16.2" +version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3" +checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905" dependencies = [ "fontconfig-parser", "log", "memmap2", "slotmap", "tinyvec", - "ttf-parser 0.20.0", + "ttf-parser", ] [[package]] @@ -1579,6 +1429,7 @@ dependencies = [ "base64 0.23.1", "chacha20poly1305", "chrono", + "colony-ui", "dirs 7.0.0", "git2", "iced", @@ -1620,9 +1471,9 @@ checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" [[package]] name = "glow" -version = "0.13.1" +version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd348e04c43b32574f2de31c8bb397d96c9fcfa1371bd4ca6d8bdc464ab121b1" +checksum = "c5e5ea60d70410161c8bf5da3fdfeaa1c72ed2c15f8bbb9d19fe3a4fad085f08" dependencies = [ "js-sys", "slotmap", @@ -1632,9 +1483,9 @@ dependencies = [ [[package]] name = "glutin_wgl_sys" -version = "0.5.0" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8098adac955faa2d31079b65dc48841251f69efd3ac25477903fc424362ead" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" dependencies = [ "gl_generator", ] @@ -1660,33 +1511,32 @@ dependencies = [ [[package]] name = "gpu-allocator" -version = "0.25.0" +version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f56f6318968d03c18e1bcf4857ff88c61157e9da8e47c5f29055d60e1228884" +checksum = "c151a2a5ef800297b4e79efa4f4bec035c5f51d5ae587287c9b952bdf734cacd" dependencies = [ "log", "presser", "thiserror 1.0.69", - "winapi", - "windows", + "windows 0.58.0", ] [[package]] name = "gpu-descriptor" -version = "0.2.4" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc11df1ace8e7e564511f53af41f3e42ddc95b56fd07b3f4445d2a6048bc682c" +checksum = "b89c83349105e3732062a895becfc71a8f921bb71ecbbdd8ff99263e3b53a0ca" dependencies = [ "bitflags 2.13.2", "gpu-descriptor-types", - "hashbrown 0.14.5", + "hashbrown 0.15.5", ] [[package]] name = "gpu-descriptor-types" -version = "0.1.2" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bf0b36e6f090b7e1d8a4b49c0cb81c1f8376f72198c65dd3ad9ff3556b8b78c" +checksum = "fdf242682df893b86f33a73828fb09ca4b2d3bb6cc95249707fc684d27484b91" dependencies = [ "bitflags 2.13.2", ] @@ -1728,48 +1578,46 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", + "num-traits", "zerocopy", ] [[package]] -name = "hashbrown" -version = "0.12.3" +name = "harfrust" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +checksum = "92c020db12c71d8a12a3fe7607873cade3a01a6287e29d540c8723276221b9d8" dependencies = [ - "ahash 0.7.9", + "bitflags 2.13.2", + "bytemuck", + "core_maths", + "read-fonts 0.35.0", + "smallvec", ] [[package]] name = "hashbrown" -version = "0.14.5" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ - "ahash 0.8.13", - "allocator-api2", + "foldhash 0.1.5", ] [[package]] name = "hashbrown" -version = "0.17.2" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "foldhash 0.2.0", +] [[package]] -name = "hassle-rs" -version = "0.11.0" +name = "hashbrown" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af2a7e73e1f34c48da31fb668a907f250794837e08faa144fd24f0b8b741e890" -dependencies = [ - "bitflags 2.13.2", - "com", - "libc", - "libloading 0.8.9", - "thiserror 1.0.69", - "widestring", - "winapi", -] +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" [[package]] name = "hermit-abi" @@ -1943,71 +1791,69 @@ dependencies = [ [[package]] name = "iced" -version = "0.13.1" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88acfabc84ec077eaf9ede3457ffa3a104626d79022a9bf7f296093b1d60c73f" +checksum = "000e01026c93ba643f8357a3db3ada0e6555265a377f6f9291c472f6dd701fb3" dependencies = [ "iced_core", + "iced_debug", "iced_futures", "iced_renderer", + "iced_runtime", "iced_widget", "iced_winit", - "thiserror 1.0.69", + "thiserror 2.0.21", ] [[package]] name = "iced_core" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0013a238275494641bf8f1732a23a808196540dc67b22ff97099c044ae4c8a1c" +checksum = "91ab1937d699403e7e69252ae743a902bcee9f4ab2052cc4c9a46fcf34729d85" dependencies = [ "bitflags 2.13.2", "bytes", - "dark-light", "glam", + "lilt", "log", "num-traits", - "once_cell", - "palette", "rustc-hash 2.1.3", "smol_str", - "thiserror 1.0.69", + "thiserror 2.0.21", "web-time", ] [[package]] -name = "iced_futures" -version = "0.13.2" +name = "iced_debug" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c04a6745ba2e80f32cf01e034fd00d853aa4f4cd8b91888099cb7aaee0d5d7c" +checksum = "25035ab0215a620e53f4103e36fc4e59a1fb2817e4bfc38a30ad27b4202ea0be" dependencies = [ - "futures", "iced_core", + "iced_futures", "log", - "rustc-hash 2.1.3", - "tokio", - "wasm-bindgen-futures", - "wasm-timer", ] [[package]] -name = "iced_glyphon" -version = "0.6.0" +name = "iced_futures" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41c3bb56f1820ca252bc1d0994ece33d233a55657c0c263ea7cb16895adbde82" +checksum = "8c0c85ccad42dfbec7293c36c018af0ea0dbcc52d137a4a9a0b0f6822a3fdf0a" dependencies = [ - "cosmic-text", - "etagere", - "lru", + "futures", + "iced_core", + "log", "rustc-hash 2.1.3", - "wgpu", + "tokio", + "wasm-bindgen-futures", + "wasmtimer", ] [[package]] name = "iced_graphics" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba25a18cfa6d5cc160aca7e1b34f73ccdff21680fa8702168c09739767b6c66f" +checksum = "234ca1c2cec4155055f68fa5fad1b5242c496ac8238d80a259bca382fb44a102" dependencies = [ "bitflags 2.13.2", "bytemuck", @@ -2016,47 +1862,57 @@ dependencies = [ "iced_core", "iced_futures", "log", - "once_cell", "raw-window-handle", "rustc-hash 2.1.3", - "thiserror 1.0.69", + "thiserror 2.0.21", "unicode-segmentation", ] +[[package]] +name = "iced_program" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dfafec2947cda688d8eb00dac337ba11aa60f9ef6335aed343e189d26e4a673" +dependencies = [ + "iced_graphics", + "iced_runtime", +] + [[package]] name = "iced_renderer" -version = "0.13.0" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73558208059f9e622df2bf434e044ee2f838ce75201a023cf0ca3e1244f46c2a" +checksum = "250cc0802408e8c077986ec56c7d07c65f423ee658a4b9fd795a1f2aae5dac05" dependencies = [ "iced_graphics", "iced_tiny_skia", "iced_wgpu", "log", - "thiserror 1.0.69", + "thiserror 2.0.21", ] [[package]] name = "iced_runtime" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "348b5b2c61c934d88ca3b0ed1ed913291e923d086a66fa288ce9669da9ef62b5" +checksum = "d1889b819ce4c06674183242e336c8d49465665441396914dc07cc86f44fa8d4" dependencies = [ "bytes", "iced_core", "iced_futures", "raw-window-handle", - "thiserror 1.0.69", + "thiserror 2.0.21", ] [[package]] name = "iced_tiny_skia" -version = "0.13.0" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c625d368284fcc43b0b36b176f76eff1abebe7959dd58bd8ce6897d641962a50" +checksum = "c267596d742714b1853cc10c3983a367762816fc4836bd3b79f76ce76787d6f8" dependencies = [ "bytemuck", "cosmic-text", + "iced_debug", "iced_graphics", "kurbo", "log", @@ -2067,55 +1923,53 @@ dependencies = [ [[package]] name = "iced_wgpu" -version = "0.13.5" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15708887133671d2bcc6c1d01d1f176f43a64d6cdc3b2bf893396c3ee498295f" +checksum = "ff144a999b0ca0f8a10257934500060240825c42e950ec0ebee9c8ae30561c13" dependencies = [ "bitflags 2.13.2", "bytemuck", + "cryoglyph", "futures", "glam", "guillotiere", - "iced_glyphon", + "iced_debug", "iced_graphics", "log", - "once_cell", "rustc-hash 2.1.3", - "thiserror 1.0.69", + "thiserror 2.0.21", "wgpu", ] [[package]] name = "iced_widget" -version = "0.13.4" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81429e1b950b0e4bca65be4c4278fea6678ea782030a411778f26fa9f8983e1d" +checksum = "b1596afa0d3109c2618e8bc12bae6c11d3064df8f95c42dfce570397dbe957ab" dependencies = [ "iced_renderer", - "iced_runtime", + "log", "num-traits", - "once_cell", "rustc-hash 2.1.3", - "thiserror 1.0.69", + "thiserror 2.0.21", "unicode-segmentation", ] [[package]] name = "iced_winit" -version = "0.13.0" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f44cd4e1c594b6334f409282937bf972ba14d31fedf03c23aa595d982a2fda28" +checksum = "7589888c8e951899cc688247a69933bb7a0511f0b4b2e122ac3fcd5dacb37f72" dependencies = [ - "iced_futures", - "iced_graphics", - "iced_runtime", + "iced_debug", + "iced_program", "log", + "mundy", "rustc-hash 2.1.3", - "thiserror 1.0.69", + "thiserror 2.0.21", "tracing", "wasm-bindgen-futures", "web-sys", - "winapi", "window_clipboard", "winit", ] @@ -2244,15 +2098,6 @@ dependencies = [ "hybrid-array", ] -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if", -] - [[package]] name = "ipnet" version = "2.12.2" @@ -2391,7 +2236,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" dependencies = [ "libc", - "libloading 0.8.9", + "libloading", "pkg-config", ] @@ -2437,16 +2282,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "libloading" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" -dependencies = [ - "cfg-if", - "winapi", -] - [[package]] name = "libloading" version = "0.8.9" @@ -2503,16 +2338,25 @@ dependencies = [ ] [[package]] -name = "linux-raw-sys" -version = "0.4.15" +name = "lilt" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +checksum = "337d4c256f7d9f2dbd633891d48ace853efa5b1554122d9220b172ad9c03c3a9" +dependencies = [ + "web-time", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linux-raw-sys" -version = "0.9.4" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "linux-raw-sys" @@ -2526,6 +2370,12 @@ version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" +[[package]] +name = "litrs" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" + [[package]] name = "lock_api" version = "0.4.14" @@ -2543,9 +2393,9 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lru" -version = "0.12.5" +version = "0.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +checksum = "7f66e8d5d03f609abc3a39e6f08e4164ebf1447a732906d39eb9b99b7919ef39" [[package]] name = "lru-slab" @@ -2597,13 +2447,13 @@ dependencies = [ [[package]] name = "metal" -version = "0.27.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43f73953f8cbe511f021b58f18c3ce1c3d1ae13fe953293e13345bf83217f25" +checksum = "00c15a6f673ff72ddcc22394663290f870fb224c1bfce55734a75c414150e605" dependencies = [ "bitflags 2.13.2", "block", - "core-graphics-types", + "core-graphics-types 0.2.0", "foreign-types", "log", "objc", @@ -2616,26 +2466,6 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "miniz_oxide" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" -dependencies = [ - "adler2", - "simd-adler32", -] - [[package]] name = "mio" version = "1.2.5" @@ -2653,24 +2483,55 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" +[[package]] +name = "mundy" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f32eb0db40f2df2bcfb05c93b8f73938d4c26ce9ac8881f1df0c8d3296921a73" +dependencies = [ + "android-build", + "async-io", + "cfg-if", + "dispatch", + "futures-channel", + "futures-lite", + "jni", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "pin-project-lite", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows 0.62.2", + "zbus", +] + [[package]] name = "naga" -version = "0.19.2" +version = "27.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e3524642f53d9af419ab5e8dd29d3ba155708267667c2f3f06c88c9e130843" +checksum = "066cf25f0e8b11ee0df221219010f213ad429855f57c494f995590c861a9a7d8" dependencies = [ + "arrayvec", "bit-set", "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", "codespan-reporting", + "half", + "hashbrown 0.16.1", "hexf-parse", "indexmap", + "libm", "log", "num-traits", + "once_cell", "rustc-hash 1.1.0", "spirv", - "termcolor", - "thiserror 1.0.69", - "unicode-xid", + "thiserror 2.0.21", + "unicode-ident", ] [[package]] @@ -2682,7 +2543,7 @@ dependencies = [ "bitflags 2.13.2", "jni-sys 0.3.1", "log", - "ndk-sys 0.6.0+11769913", + "ndk-sys", "num_enum", "raw-window-handle", "thiserror 1.0.69", @@ -2694,15 +2555,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" -[[package]] -name = "ndk-sys" -version = "0.5.0+25.2.9519653" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691" -dependencies = [ - "jni-sys 0.3.1", -] - [[package]] name = "ndk-sys" version = "0.6.0+11769913" @@ -2712,19 +2564,6 @@ dependencies = [ "jni-sys 0.3.1", ] -[[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 0.2.2", - "libc", - "memoffset", -] - [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -2810,6 +2649,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] [[package]] @@ -2860,7 +2700,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" dependencies = [ "malloc_buf", - "objc_exception", ] [[package]] @@ -2898,8 +2737,8 @@ dependencies = [ "block2 0.5.1", "libc", "objc2 0.5.3", - "objc2-core-data", - "objc2-core-image", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-foundation 0.2.2", "objc2-quartz-core 0.2.2", ] @@ -2912,8 +2751,17 @@ checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ "bitflags 2.13.2", "block2 0.6.2", + "libc", "objc2 0.6.5", + "objc2-cloud-kit 0.3.2", + "objc2-core-data 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image 0.3.2", + "objc2-core-text", + "objc2-core-video", "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", "objc2-uniform-type-identifiers 0.3.2", ] @@ -2930,6 +2778,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-contacts" version = "0.2.2" @@ -2953,6 +2812,17 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-foundation" version = "0.3.2" @@ -2989,6 +2859,16 @@ dependencies = [ "objc2-metal", ] +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-core-location" version = "0.2.2" @@ -3001,6 +2881,31 @@ dependencies = [ "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + [[package]] name = "objc2-encode" version = "4.1.0" @@ -3027,6 +2932,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.2", + "block2 0.6.2", + "libc", "objc2 0.6.5", "objc2-core-foundation", ] @@ -3110,9 +3017,9 @@ dependencies = [ "bitflags 2.13.2", "block2 0.5.1", "objc2 0.5.3", - "objc2-cloud-kit", - "objc2-core-data", - "objc2-core-image", + "objc2-cloud-kit 0.2.2", + "objc2-core-data 0.2.2", + "objc2-core-image 0.2.2", "objc2-core-location", "objc2-foundation 0.2.2", "objc2-link-presentation", @@ -3156,15 +3063,6 @@ dependencies = [ "objc2-foundation 0.2.2", ] -[[package]] -name = "objc_exception" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4" -dependencies = [ - "cc", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -3232,13 +3130,12 @@ dependencies = [ ] [[package]] -name = "ordered-multimap" -version = "0.4.3" +name = "ordered-float" +version = "5.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccd746e37177e1711c20dd619a1620f34f5c8b569c53590a72dedd5344d8924a" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" dependencies = [ - "dlv-list", - "hashbrown 0.12.3", + "num-traits", ] [[package]] @@ -3257,56 +3154,15 @@ version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" dependencies = [ - "ttf-parser 0.25.1", -] - -[[package]] -name = "palette" -version = "0.7.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64" -dependencies = [ - "approx", - "palette_derive", - "palette_math", - "phf", -] - -[[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", + "ttf-parser", ] -[[package]] -name = "palette_math" -version = "0.7.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12" - [[package]] name = "parking" version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" -[[package]] -name = "parking_lot" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core 0.8.6", -] - [[package]] name = "parking_lot" version = "0.12.5" @@ -3314,21 +3170,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ "lock_api", - "parking_lot_core 0.9.12", -] - -[[package]] -name = "parking_lot_core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" -dependencies = [ - "cfg-if", - "instant", - "libc", - "redox_syscall 0.2.16", - "smallvec", - "winapi", + "parking_lot_core", ] [[package]] @@ -3375,24 +3217,6 @@ dependencies = [ "ctutils", ] -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_shared", -] - -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", -] - [[package]] name = "pin-project" version = "1.2.0" @@ -3419,12 +3243,6 @@ version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" -[[package]] -name = "pin-utils" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" - [[package]] name = "piper" version = "0.2.5" @@ -3449,23 +3267,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] -name = "png" -version = "0.17.16" +name = "polling" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" -dependencies = [ - "bitflags 1.3.2", - "crc32fast", - "fdeflate", - "flate2", - "miniz_oxide 0.8.9", -] - -[[package]] -name = "polling" -version = "3.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" dependencies = [ "cfg-if", "concurrent-queue", @@ -3491,6 +3296,21 @@ dependencies = [ "universal-hash", ] +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + [[package]] name = "potential_utf" version = "0.1.6" @@ -3561,7 +3381,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" dependencies = [ "bytes", - "cfg_aliases 0.2.2", + "cfg_aliases", "pin-project-lite", "quinn-proto", "quinn-udp", @@ -3603,7 +3423,7 @@ version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ - "cfg_aliases 0.2.2", + "cfg_aliases", "libc", "once_cell", "socket2", @@ -3700,43 +3520,26 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" -[[package]] -name = "rayon" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - [[package]] name = "read-fonts" -version = "0.22.7" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69aacb76b5c29acfb7f90155d39759a29496aebb49395830e928a9703d2eec2f" +checksum = "6717cf23b488adf64b9d711329542ba34de147df262370221940dfabc2c91358" dependencies = [ "bytemuck", - "font-types", + "core_maths", + "font-types 0.10.1", ] [[package]] -name = "redox_syscall" -version = "0.2.16" +name = "read-fonts" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" dependencies = [ - "bitflags 1.3.2", + "bytemuck", + "font-types 0.12.7", + "once_cell", ] [[package]] @@ -3766,17 +3569,6 @@ dependencies = [ "bitflags 2.13.2", ] -[[package]] -name = "redox_users" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" -dependencies = [ - "getrandom 0.2.17", - "libredox", - "thiserror 1.0.69", -] - [[package]] name = "redox_users" version = "0.5.3" @@ -3913,16 +3705,6 @@ version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" -[[package]] -name = "rust-ini" -version = "0.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d5f2436026b4f6e79dc829837d467cc7e9a55ee40e750d716713540715a2df" -dependencies = [ - "cfg-if", - "ordered-multimap", -] - [[package]] name = "rustc-hash" version = "1.1.0" @@ -4051,23 +3833,6 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" -[[package]] -name = "rustybuzz" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c" -dependencies = [ - "bitflags 2.13.2", - "bytemuck", - "libm", - "smallvec", - "ttf-parser 0.21.1", - "unicode-bidi-mirroring", - "unicode-ccc", - "unicode-properties", - "unicode-script", -] - [[package]] name = "ryu" version = "1.0.23" @@ -4133,7 +3898,7 @@ dependencies = [ "once_cell", "serde", "sha2 0.11.1", - "zbus 5.19.0", + "zbus", ] [[package]] @@ -4207,6 +3972,8 @@ version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ + "foldhash 0.2.0", + "indexmap", "itoa", "memchr", "serde", @@ -4248,17 +4015,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha1" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - [[package]] name = "sha2" version = "0.10.9" @@ -4306,12 +4062,6 @@ dependencies = [ "libc", ] -[[package]] -name = "simd-adler32" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" - [[package]] name = "simd_cesu8" version = "1.2.0" @@ -4329,19 +4079,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" [[package]] -name = "siphasher" -version = "1.0.4" +name = "skrifa" +version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" +checksum = "8c31071dedf532758ecf3fed987cdb4bd9509f900e026ab684b4ecb81ea49841" +dependencies = [ + "bytemuck", + "read-fonts 0.35.0", +] [[package]] name = "skrifa" -version = "0.22.3" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e1c44ad1f6c5bdd4eefed8326711b7dbda9ea45dfd36068c427d332aa382cbe" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", - "read-fonts", + "read-fonts 0.41.0", ] [[package]] @@ -4455,7 +4209,6 @@ checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" dependencies = [ "as-raw-xcb-connection", "bytemuck", - "drm", "fastrand", "js-sys", "memmap2", @@ -4520,11 +4273,11 @@ checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" [[package]] name = "swash" -version = "0.1.19" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbd59f3f359ddd2c95af4758c18270eddd9c730dde98598023cdabff472c2ca2" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" dependencies = [ - "skrifa", + "skrifa 0.44.0", "yazi", "zeno", ] @@ -4535,17 +4288,6 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" -[[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" @@ -4730,7 +4472,6 @@ dependencies = [ "bytemuck", "cfg-if", "log", - "png", "tiny-skia-path", ] @@ -4753,7 +4494,7 @@ checksum = "a90a0ca3ee6a69f2ad28fd11621a4c3f03b371f366be500b64df260c4ffbafb4" dependencies = [ "as-raw-xcb-connection", "ctor", - "libloading 0.8.9", + "libloading", "pkg-config", "tracing", ] @@ -4993,23 +4734,14 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" -[[package]] -name = "ttf-parser" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4" - -[[package]] -name = "ttf-parser" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8" - [[package]] name = "ttf-parser" version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +dependencies = [ + "core_maths", +] [[package]] name = "typenum" @@ -5034,18 +4766,6 @@ version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" -[[package]] -name = "unicode-bidi-mirroring" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86" - -[[package]] -name = "unicode-ccc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656" - [[package]] name = "unicode-ident" version = "1.0.27" @@ -5058,12 +4778,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" -[[package]] -name = "unicode-properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" - [[package]] name = "unicode-script" version = "0.5.9" @@ -5082,12 +4796,6 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "universal-hash" version = "0.6.1" @@ -5242,18 +4950,17 @@ dependencies = [ ] [[package]] -name = "wasm-timer" -version = "0.2.5" +name = "wasmtimer" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be0ecb0db480561e9a7642b5d3e4187c128914e58aa84330b9493e3eb68c5e7f" +checksum = "c62b7f338e4397a45d054c15a2b36a93d57cccdda7be11a7d7b045d47b5e70ce" dependencies = [ "futures", "js-sys", - "parking_lot 0.11.2", - "pin-utils", + "parking_lot", + "pin-project-lite", + "slab", "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", ] [[package]] @@ -5438,17 +5145,21 @@ dependencies = [ [[package]] name = "wgpu" -version = "0.19.4" +version = "27.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbd7311dbd2abcfebaabf1841a2824ed7c8be443a0f29166e5d3c6a53a762c01" +checksum = "bfe68bac7cde125de7a731c3400723cadaaf1703795ad3f4805f187459cd7a77" dependencies = [ "arrayvec", + "bitflags 2.13.2", "cfg-if", - "cfg_aliases 0.1.1", + "cfg_aliases", + "document-features", + "hashbrown 0.16.1", "js-sys", "log", "naga", - "parking_lot 0.12.5", + "parking_lot", + "portable-atomic", "profiling", "raw-window-handle", "smallvec", @@ -5463,35 +5174,68 @@ dependencies = [ [[package]] name = "wgpu-core" -version = "0.19.4" +version = "27.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b94525fc99ba9e5c9a9e24764f2bc29bad0911a7446c12f446a8277369bf3a" +checksum = "27a75de515543b1897b26119f93731b385a19aea165a1ec5f0e3acecc229cae7" dependencies = [ "arrayvec", + "bit-set", "bit-vec", "bitflags 2.13.2", - "cfg_aliases 0.1.1", - "codespan-reporting", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.16.1", "indexmap", "log", "naga", "once_cell", - "parking_lot 0.12.5", + "parking_lot", + "portable-atomic", "profiling", "raw-window-handle", "rustc-hash 1.1.0", "smallvec", - "thiserror 1.0.69", - "web-sys", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-emscripten", + "wgpu-core-deps-windows-linux-android", "wgpu-hal", "wgpu-types", ] +[[package]] +name = "wgpu-core-deps-apple" +version = "27.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0772ae958e9be0c729561d5e3fd9a19679bcdfb945b8b1a1969d9bfe8056d233" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-emscripten" +version = "27.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06ac3444a95b0813ecfd81ddb2774b66220b264b3e2031152a4a29fda4da6b5" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "27.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71197027d61a71748e4120f05a9242b2ad142e3c01f8c1b47707945a879a03c3" +dependencies = [ + "wgpu-hal", +] + [[package]] name = "wgpu-hal" -version = "0.19.5" +version = "27.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfabcfc55fd86611a855816326b2d54c3b2fd7972c27ce414291562650552703" +checksum = "5b21cb61c57ee198bc4aff71aeadff4cbb80b927beb912506af9c780d64313ce" dependencies = [ "android_system_properties", "arrayvec", @@ -5499,72 +5243,57 @@ dependencies = [ "bit-set", "bitflags 2.13.2", "block", - "cfg_aliases 0.1.1", - "core-graphics-types", - "d3d12", + "bytemuck", + "cfg-if", + "cfg_aliases", + "core-graphics-types 0.2.0", "glow", "glutin_wgl_sys", "gpu-alloc", "gpu-allocator", "gpu-descriptor", - "hassle-rs", + "hashbrown 0.16.1", "js-sys", "khronos-egl", "libc", - "libloading 0.8.9", + "libloading", "log", "metal", "naga", - "ndk-sys 0.5.0+25.2.9519653", + "ndk-sys", "objc", "once_cell", - "parking_lot 0.12.5", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", "profiling", "range-alloc", "raw-window-handle", "renderdoc-sys", - "rustc-hash 1.1.0", "smallvec", - "thiserror 1.0.69", + "thiserror 2.0.21", "wasm-bindgen", "web-sys", "wgpu-types", - "winapi", + "windows 0.58.0", + "windows-core 0.58.0", ] [[package]] name = "wgpu-types" -version = "0.19.2" +version = "27.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b671ff9fb03f78b46ff176494ee1ebe7d603393f42664be55b64dc8d53969805" +checksum = "afdcf84c395990db737f2dd91628706cb31e86d72e53482320d368e52b5da5eb" dependencies = [ "bitflags 2.13.2", + "bytemuck", "js-sys", + "log", + "thiserror 2.0.21", "web-sys", ] -[[package]] -name = "widestring" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - [[package]] name = "winapi-util" version = "0.1.11" @@ -5574,42 +5303,61 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - [[package]] name = "window_clipboard" -version = "0.4.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d692d46038c433f9daee7ad8757e002a4248c20b0a3fbc991d99521d3bcb6d" +checksum = "d5654226305eaf2dde8853fb482861d28e5dcecbbd40cb88e8393d94bb80d733" dependencies = [ "clipboard-win", "clipboard_macos", "clipboard_wayland", "clipboard_x11", "raw-window-handle", - "thiserror 1.0.69", + "thiserror 2.0.21", ] [[package]] name = "windows" -version = "0.52.0" +version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" dependencies = [ - "windows-core 0.52.0", + "windows-core 0.58.0", "windows-targets", ] +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core 0.62.2", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core 0.62.2", +] + [[package]] name = "windows-core" -version = "0.52.0" +version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99" dependencies = [ + "windows-implement 0.58.0", + "windows-interface 0.58.0", + "windows-result 0.2.0", + "windows-strings 0.1.0", "windows-targets", ] @@ -5619,11 +5367,33 @@ version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-implement", - "windows-interface", + "windows-implement 0.60.2", + "windows-interface 0.59.3", + "windows-link", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core 0.62.2", "windows-link", - "windows-result", - "windows-strings", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -5637,6 +5407,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-interface" +version = "0.58.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-interface" version = "0.59.3" @@ -5667,6 +5448,16 @@ dependencies = [ "zeroize", ] +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core 0.62.2", + "windows-link", +] + [[package]] name = "windows-registry" version = "0.6.1" @@ -5674,8 +5465,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ "windows-link", - "windows-result", - "windows-strings", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-result" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" +dependencies = [ + "windows-targets", ] [[package]] @@ -5687,6 +5487,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-strings" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" +dependencies = [ + "windows-result 0.2.0", + "windows-targets", +] + [[package]] name = "windows-strings" version = "0.5.1" @@ -5739,6 +5549,15 @@ dependencies = [ "windows_x86_64_msvc", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" @@ -5793,14 +5612,14 @@ version = "0.30.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" dependencies = [ - "ahash 0.8.13", + "ahash", "android-activity", "atomic-waker", "bitflags 2.13.2", "block2 0.5.1", "bytemuck", "calloop 0.13.0", - "cfg_aliases 0.2.2", + "cfg_aliases", "concurrent-queue", "core-foundation 0.9.4", "core-graphics", @@ -5848,15 +5667,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "winreg" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" -dependencies = [ - "winapi", -] - [[package]] name = "writeable" version = "0.6.4" @@ -5883,7 +5693,7 @@ dependencies = [ "as-raw-xcb-connection", "gethostname", "libc", - "libloading 0.8.9", + "libloading", "once_cell", "rustix 1.1.6", "x11rb-protocol", @@ -5901,16 +5711,6 @@ version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" -[[package]] -name = "xdg-home" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - [[package]] name = "xkbcommon-dl" version = "0.4.2" @@ -5938,9 +5738,9 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "yazi" -version = "0.1.6" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c94451ac9513335b5e23d7a8a2b61a7102398b8cca5160829d313e84c9d98be1" +checksum = "ac366ea532fa8ee6a992cec9dea525b1dc284e69702f36c2ab5fbebadc81ec86" [[package]] name = "yoke" @@ -5965,44 +5765,6 @@ dependencies = [ "synstructure", ] -[[package]] -name = "zbus" -version = "4.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" -dependencies = [ - "async-broadcast", - "async-executor", - "async-fs", - "async-io", - "async-lock", - "async-process", - "async-recursion", - "async-task", - "async-trait", - "blocking", - "enumflags2", - "event-listener", - "futures-core", - "futures-sink", - "futures-util", - "hex", - "nix", - "ordered-stream", - "rand 0.8.8", - "serde", - "serde_repr", - "sha1", - "static_assertions", - "tracing", - "uds_windows", - "windows-sys 0.52.0", - "xdg-home", - "zbus_macros 4.4.0", - "zbus_names 3.0.0", - "zvariant 4.2.0", -] - [[package]] name = "zbus" version = "5.19.0" @@ -6033,9 +5795,9 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow", - "zbus_macros 5.19.0", - "zbus_names 4.3.5", - "zvariant 5.15.1", + "zbus_macros", + "zbus_names", + "zvariant", ] [[package]] @@ -6046,20 +5808,7 @@ checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" dependencies = [ "keyring-core", "secret-service", - "zbus 5.19.0", -] - -[[package]] -name = "zbus_macros" -version = "4.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 2.0.119", - "zvariant_utils 2.1.0", + "zbus", ] [[package]] @@ -6072,20 +5821,9 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.10", - "zbus_names 4.3.5", - "zvariant 5.15.1", - "zvariant_utils 4.2.0", -] - -[[package]] -name = "zbus_names" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" -dependencies = [ - "serde", - "static_assertions", - "zvariant 4.2.0", + "zbus_names", + "zvariant", + "zvariant_utils", ] [[package]] @@ -6096,7 +5834,7 @@ checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" dependencies = [ "serde", "winnow", - "zvariant 5.15.1", + "zvariant", ] [[package]] @@ -6110,9 +5848,9 @@ dependencies = [ [[package]] name = "zeno" -version = "0.2.3" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd15f8e0dbb966fd9245e7498c7e9e5055d9e5c8b676b95bd67091cd11a1e697" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" [[package]] name = "zerocopy" @@ -6208,31 +5946,12 @@ dependencies = [ "syn 3.0.10", ] -[[package]] -name = "zlib-rs" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" - [[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zvariant" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" -dependencies = [ - "endi", - "enumflags2", - "serde", - "static_assertions", - "zvariant_derive 4.2.0", -] - [[package]] name = "zvariant" version = "5.15.1" @@ -6244,21 +5963,8 @@ dependencies = [ "serde", "winnow", "zcheapstr", - "zvariant_derive 5.15.1", - "zvariant_utils 4.2.0", -] - -[[package]] -name = "zvariant_derive" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 2.0.119", - "zvariant_utils 2.1.0", + "zvariant_derive", + "zvariant_utils", ] [[package]] @@ -6271,18 +5977,7 @@ dependencies = [ "proc-macro2", "quote", "syn 3.0.10", - "zvariant_utils 4.2.0", -] - -[[package]] -name = "zvariant_utils" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "zvariant_utils", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index fd62a10..2298f85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,7 +16,8 @@ fake-repos = [] mock-providers = [] [dependencies] -iced = { version = "0.13.1", features = ["tokio", "advanced"] } +iced = { version = "0.14.0", features = ["tokio", "advanced"] } +colony-ui = "0.1.6" tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time"] } git2 = { version = "0.21.0", features = ["https", "ssh", "vendored-openssl"] } reqwest = { version = "0.13.5", features = ["blocking", "form", "json", "query"] } diff --git a/README.md b/README.md index 9da15a2..e67f39f 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,8 @@ Graphical Git clients either serve one hosting site, like GitHub Desktop, or are closed source and tied to an account of their own, like GitKraken. GitSpace is an open source, native Rust client that signs in to GitHub, GitLab and their self-hosted instances side by -side, finds and clones your repositories from both, and then works on them in one -panel-based window inspired by GitKraken. +side, finds and clones your repositories from both, and keeps all of them one click away +in a sidebar. > **Status:** early development, no release yet. CI builds GitSpace and runs its tests on > Linux, macOS and Windows, and checks that it still builds on Rust 1.100. The first signed @@ -22,15 +22,14 @@ panel-based window inspired by GitKraken. > work out of the box. OAuth sign-in needs the client ID of an OAuth app you register > yourself, because no build embeds one yet. The git operations are covered by tests on > local repositories; SSH sign-in, proxies and OAuth are covered by unit tests of their -> logic, not by tests against live servers. The interface is built on iced and has no -> language setting yet: most of it is in French, with some labels still in English. It is -> meant to move to the shared Colony UI kit, which brings English and French locales. +> logic, not by tests against live servers. The interface is built on iced 0.14 and the +> shared [colony-ui](https://crates.io/crates/colony-ui) kit, in English and French. ## Why GitSpace - **Both sites in one place.** Tokens for GitHub, GitLab and self-hosted instances sit side - by side, and the Clone dialog searches your repositories on either site without leaving - GitSpace. + by side, and the Add repository screen searches your repositories on either site without + leaving GitSpace. - **Tokens stay with you.** They go to the operating system's keyring, are only ever sent over HTTPS, and only to the host they belong to. GitSpace has no account of its own and no server: it talks to the hosts you use and nothing else. @@ -39,23 +38,53 @@ panel-based window inspired by GitKraken. ## What it does -- Clone from GitHub, GitLab or any Git URL over HTTPS or SSH, and reopen recent repositories. -- Repository overview with fetch, pull (fast-forward), push, open in the file manager and - open a terminal, plus optional auto-fetch on an interval. -- Stage and unstage files with their diffs, commit, restore a file from another branch, and - create, apply and drop stashes. -- History with commit diffs, filtered by branch. -- Branches: create, rename, delete, check out and track, merge a branch into the current one - or rebase the current one onto it, compare with it, pin favourites, and archive a branch as - a tag. Delete, merge and rebase ask for confirmation, and checkout refuses to overwrite +The window has two parts. The sidebar on the left lists your repositories: pinned ones +first, then the others by the time you last opened them. Each row shows the number of +changed files and how far the branch is ahead of or behind its upstream, and a repository +whose folder is gone is marked as missing. Ctrl+K (Cmd+K on macOS) filters the list by name, +Alt+Up and Alt+Down move to the previous or next repository, and a right-click on a row pins +it, removes it from the list or opens its folder or a terminal there. Repositories found one +level down in the default clone folder join the list on their own. + +The right part shows the open repository: a header with the branch, the ahead and behind +counts, Fetch, Pull and Push, and four tabs below it (Ctrl+1 to Ctrl+4): + +- Changes: staged and unstaged files with their added and removed line counts, the diff of + the selected file, and the commit box. A file can be staged, unstaged, restored from + another branch or have its changes discarded after a confirmation. +- History: the commits of a branch with branch and tag badges and merge markers, a filter + on message, author and hash, and the files and diff of the selected commit. A commit can + be checked out or used as the start of a new branch. +- Branches: local branches and one group per remote, each with its distance from the + current branch and whether it is merged. Check out, merge into the current branch, rebase + the current branch onto it, rename (F2), pin, change the upstream, archive as a tag or + delete. Delete, merge and rebase ask for confirmation, and checkout refuses to overwrite uncommitted changes. -- Sign in to GitHub with a one-time code entered on github.com (OAuth device flow), to - GitLab through OAuth in the browser (PKCE), or to GitHub, GitLab and self-hosted hosts with - a personal access token. -- Network preferences: HTTP and HTTPS proxies, transfer timeout, preferring HTTPS and - allowing SSH. -- Four Catppuccin themes. -- Structured logs with daily rotation (`GITSPACE_LOG` sets the filter). +- Stashes: stash the working tree, with or without untracked files, then apply, apply and + drop, or drop a stash, and look at its files and diff. + +"+ Clone or open" at the bottom of the sidebar opens the Add repository screen: search your +GitHub or GitLab repositories, paste an HTTPS or SSH URL, or pick a local folder. A clone +shows its progress and opens on Changes when it finishes. At startup GitSpace reopens the +repository you used last, unless that is turned off or its folder is gone. + +The GitSpace button at the top of the sidebar (or Ctrl+,) opens Preferences in place of the +repository view. Every change applies and is saved at once; there is no Save button. + +- General: interface language (English, French, or the system's), reopening the last + repository at startup, and import, export or reset of the preferences file. +- Appearance and Accessibility: the 26 theme families and accents of colony-ui, text size, + animations, high contrast, reduced motion and a dyslexia-friendly font. A change redraws + every screen at once. +- Accounts: sign in to GitHub with a one-time code entered on github.com (OAuth device + flow), to GitLab through OAuth in the browser (PKCE), or to GitHub, GitLab and self-hosted + hosts with a personal access token. +- Git: the default clone folder, auto-fetch every 1, 5, 15, 30 or 60 minutes, pinned + branches and log retention. +- Network: HTTP and HTTPS proxies, the transfer timeout, preferring HTTPS and allowing SSH. +- About: the version, the licence and where GitSpace keeps its files. + +Logs are structured, one file per day (`GITSPACE_LOG` sets the filter). ## Installation @@ -97,8 +126,8 @@ command on your `PATH`: merge, rebase and restoring a file from another branch r OAuth sign-in needs the client ID of an OAuth app: a GitHub OAuth app with "Enable Device Flow" ticked, and a GitLab application with "Confidential" unticked and the redirect URI `http://127.0.0.1:9876/callback`. Set `GITSPACE_GITHUB_CLIENT_ID` and -`GITSPACE_GITLAB_CLIENT_ID` when building to build them in, or enter them under Configure -OAuth Apps on the Auth tab. A personal access token works without one. +`GITSPACE_GITLAB_CLIENT_ID` when building to build them in, or enter them under +Preferences → Accounts → OAuth app client IDs. A personal access token works without one. ## Documentation @@ -144,14 +173,14 @@ GitSpace sends no telemetry, no analytics and no crash reports. | Data | Stored or sent | Where, and why | |---|---|---| -| Settings | stored | `config.json` in the `gitspace` folder of the system configuration directory (`~/.config/gitspace/` on Linux, see [configuration](docs/guide/configuration.md)): preferences, network options, the paths of recent repositories and the log retention | -| Logs | stored | `gitspace/logs/` in the system data directory (`~/.local/share/gitspace/logs/` on Linux), one file per day, the oldest deleted past the retention set in Preferences. They record operations and errors, never a token | -| Access tokens | stored | the operating system's keyring (service `gitspace`, one entry per host, plus `oauth:` with the refresh token and expiry after an OAuth sign-in). With "Allow encrypted file storage if the native keyring is unavailable" on, they are also written to `tokens.enc` in the settings folder, encrypted with a key kept in the keyring. When the keyring cannot be used, that key is the file `token-local-key.bin` in the same folder instead, readable by your user account, so `tokens.enc` is then only as safe as that account. Setting `GITSPACE_TOKEN_MASTER_PASSWORD` mixes a password into that key (Argon2id, salt in `token-salt.bin`). `token-hosts.json` lists the hosts that have a token | +| Settings | stored | `config.json` in the `Colony/GitSpace` folder of the system configuration directory (`~/.config/Colony/GitSpace/` on Linux, see [configuration](docs/guide/configuration.md)): preferences, network options, the paths of recent repositories and the log retention | +| Logs | stored | `Colony/GitSpace/logs/` in the system data directory (`~/.local/share/Colony/GitSpace/logs/` on Linux), one file per day, the oldest deleted past the retention set in Preferences. They record operations and errors, never a token | +| Access tokens | stored | the operating system's keyring (service `gitspace`, one entry per host, plus `oauth:` with the refresh token and expiry after an OAuth sign-in). With "Allow an encrypted file" on (Preferences → Accounts → Token storage), they are also written to `tokens.enc` in the settings folder, encrypted with a key kept in the keyring. When the keyring cannot be used, that key is the file `token-local-key.bin` in the same folder instead, readable by your user account, so `tokens.enc` is then only as safe as that account. Setting `GITSPACE_TOKEN_MASTER_PASSWORD` mixes a password into that key (Argon2id, salt in `token-salt.bin`). `token-hosts.json` lists the hosts that have a token | | Token check | sent | when you save a personal access token: the token to `https://api.github.com/user`, `https://gitlab.com/api/v4/user`, or the matching API of a self-hosted GitHub or GitLab host you entered. A self-hosted host must use `https://`; an `http://` host is refused, so a token never travels in clear text | | GitHub sign-in | sent | when you choose to sign in with GitHub: GitSpace asks `https://github.com/login/device/code` for a one-time code, you enter it at `https://github.com/login/device` in your browser, and GitSpace asks `https://github.com/login/oauth/access_token` every few seconds whether you approved it, until you approve or deny it, cancel, or the code expires. Only the OAuth app's client ID is sent, never a client secret | | GitLab sign-in | sent | when you choose to sign in with GitLab: your browser opens `gitlab.com`, which sends the authorization code back to GitSpace on `127.0.0.1` (port 9876), and GitSpace exchanges it for a token at `gitlab.com`, with PKCE | -| Repository search | sent | when you search in the Clone dialog: the search to `https://api.github.com` (`/user`, `/user/repos`, `/users//repos`, `/orgs//repos`) or `https://gitlab.com/api/v4/projects`, with your token for that site when one is saved | -| Git traffic | sent | clone, fetch, pull and push talk to the remote of the repository when you start them, and fetch also runs on its own while a repository is open if you turn on auto-fetch in Preferences (off by default, every 1, 5 or 15 minutes or an interval you choose). Over HTTPS the token saved for that host is sent as the password; a plain-HTTP remote never receives a token. Over SSH, GitSpace signs in with the keys in ssh-agent or `~/.ssh/id_ed25519`, `id_ecdsa` and `id_rsa`, and never sends a token | +| Repository search | sent | when you search on the Add repository screen: on GitHub, the search to `https://api.github.com/search/repositories`, plus, with a saved token, the list of your repositories from `https://api.github.com/user/repos`, filtered on your machine; on GitLab, the search to `https://gitlab.com/api/v4/projects`. Your token for that site goes with the request when one is saved | +| Git traffic | sent | clone, fetch, pull and push talk to the remote of the repository when you start them, and fetch also runs on its own while a repository is open if you turn on auto-fetch in Preferences (off by default, every 1, 5, 15, 30 or 60 minutes). Over HTTPS the token saved for that host is sent as the password; a plain-HTTP remote never receives a token. Over SSH, GitSpace signs in with the keys in ssh-agent or `~/.ssh/id_ed25519`, `id_ecdsa` and `id_rsa`, and never sends a token | | Local git commands | neither | merge, rebase and restoring a file from another branch run your own `git` command in the repository folder. These commands work on the local repository only and do not contact a remote | When a proxy is set in Preferences, the repository search and HTTP(S) git traffic @@ -165,5 +194,5 @@ action named there. Their privacy policies: GitSpace is licensed under the [GNU General Public License v3.0 or later](LICENSE). -The bundled JetBrains Mono Nerd Font files in `assets/JetBrainsMonoNerdFont/` are licensed -under the SIL Open Font License 1.1 (see [OFL.txt](assets/JetBrainsMonoNerdFont/OFL.txt)). +The interface fonts come from the [colony-ui](https://crates.io/crates/colony-ui) crate, +which ships each font with its licence. diff --git a/assets/JetBrainsMonoNerdFont/JetBrainsMonoNerdFont-Regular.ttf b/assets/JetBrainsMonoNerdFont/JetBrainsMonoNerdFont-Regular.ttf deleted file mode 100644 index 235a07a..0000000 Binary files a/assets/JetBrainsMonoNerdFont/JetBrainsMonoNerdFont-Regular.ttf and /dev/null differ diff --git a/assets/JetBrainsMonoNerdFont/OFL.txt b/assets/JetBrainsMonoNerdFont/OFL.txt deleted file mode 100644 index 8bee414..0000000 --- a/assets/JetBrainsMonoNerdFont/OFL.txt +++ /dev/null @@ -1,93 +0,0 @@ -Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -https://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/docs/README.md b/docs/README.md index f26036f..af8e607 100644 --- a/docs/README.md +++ b/docs/README.md @@ -21,7 +21,7 @@ Sorted by who is reading, not by subject. | | | |---|---| -| [project/gitkraken-layout.md](project/gitkraken-layout.md) | the window layout, tabs and shortcuts, and what GitKraken has that GitSpace leaves out | -| [project/ui-stack.md](project/ui-stack.md) | why the interface moved from egui to iced, and where it goes next | +| [project/gitkraken-layout.md](project/gitkraken-layout.md) | the sidebar, the repository tabs, the shortcuts, and what GitKraken has that GitSpace leaves out | +| [project/ui-stack.md](project/ui-stack.md) | why the interface moved from egui to iced and colony-ui, and what comes from the kit | Security policy: [../SECURITY.md](../SECURITY.md). diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index d6faf9a..b109369 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -1,30 +1,48 @@ # Settings, tokens and logs -GitSpace keeps its files in a `gitspace` folder inside the system configuration directory: +GitSpace keeps its files in a `Colony/GitSpace` folder inside the system configuration directory, +the layout shared by every Colony program: | Platform | Folder | |---|---| -| Linux | `~/.config/gitspace/` (`$XDG_CONFIG_HOME/gitspace/` when that variable is set) | -| macOS | `~/Library/Application Support/gitspace/` | -| Windows | `%APPDATA%\gitspace\` | +| Linux | `~/.config/Colony/GitSpace/` (`$XDG_CONFIG_HOME/Colony/GitSpace/` when that variable is set) | +| macOS | `~/Library/Application Support/Colony/GitSpace/` | +| Windows | `%LOCALAPPDATA%\Colony\GitSpace\` | | File | What it holds | |---|---| -| `config.json` | preferences, recent repositories and log retention | +| `config.json` | preferences, the repository list and log retention. Each repository entry has its path, whether it is pinned, when it was last opened, whether the clone-folder scan found it, and whether you removed it from the list (so the next scan does not add it back) | | `config.json.bak` | a copy of a `config.json` that could not be parsed (see below) | -| `tokens.enc` | saved tokens, encrypted, only when "Allow encrypted file storage if the native keyring is unavailable" is on; otherwise tokens live in the system keyring only | +| `tokens.enc` | saved tokens, encrypted, only when "Allow an encrypted file" (Preferences → Accounts → Token storage) is on; otherwise tokens live in the system keyring only | | `token-hosts.json` | the hosts that have a saved token | | `token-local-key.bin`, `token-salt.bin` | the encryption key used when the system keyring is unavailable, and the salt that mixes `GITSPACE_TOKEN_MASTER_PASSWORD` into it | Settings and token files are written to a temporary file that is then renamed into place, so a crash or a full disk never leaves a half-written file. +## Moving from an older version + +Older versions used a `gitspace` folder instead: `~/.config/gitspace/` and +`~/.local/share/gitspace/logs/` on Linux, `~/Library/Application Support/gitspace/` on macOS, +`%APPDATA%\gitspace\` on Windows. On the first start without a `config.json` in the new +folder, GitSpace moves the files listed above and the logs there, `config.json` last, and keeps +the owner-only permissions of the token files. If GitSpace stops during the move, the next start +finishes it. When a file exists in both folders with different content, GitSpace moves nothing, +uses the old folder for that run and shows an error; move or delete one of the two copies, then +restart. If another error stops the move, for example a full disk, GitSpace puts the files it already +moved back in the old folder, uses that folder for the run and tries again on the next start. + ## When a file cannot be read GitSpace never saves over a file it could not read: -- **Unknown theme or motion value in `config.json`**, for example one written by another - version: that value falls back to its default and every other setting is kept. +- **A value this version does not know**, for example one written by a newer version: an + unknown theme family is kept in the file and the default theme is shown until a version + that knows it starts; an unknown language falls back to System. Every other setting is + kept. +- **Settings from a version before the colony-ui interface**: the Catppuccin theme (Latte, + Frappé, Macchiato or Mocha) becomes the same variant of colony-ui's Catppuccin family, and + the recent repositories keep their order as last-opened times. - **`config.json` cannot be parsed**: GitSpace copies it to `config.json.bak`, logs the error and starts with default settings. To get your settings back, close GitSpace, fix the JSON in the backup and move it back to `config.json`. @@ -45,7 +63,7 @@ GitSpace never saves over a file it could not read: The network preferences apply to clone, fetch, pull and push: - **Proxy**: `https://` remotes go through the HTTPS proxy and `http://` remotes through the - HTTP proxy, and so does the repository search in the Clone dialog. When the matching field is + HTTP proxy, and so does the repository search on the Add repository screen. When the matching field is empty, git's `http.proxy` setting and the `https_proxy` and `http_proxy` environment variables apply. SSH remotes never go through a proxy. Token checks and OAuth sign-in do not use this proxy: they connect directly, or through the system proxy (the `https_proxy` and @@ -62,14 +80,14 @@ The network preferences apply to clone, fetch, pull and push: - **HTTPS remotes** use the saved token for the host. A remote reached over plain `http://` never receives the token. - **Auto-fetch**: off by default. When on, GitSpace fetches the remote of the open repository - every 1, 5 or 15 minutes, or at an interval you enter, with the same proxy, timeout and - token rules as a fetch you start yourself. + every 1, 5, 15, 30 or 60 minutes (Preferences → Git → Background fetch), with the same + proxy, timeout and token rules as a fetch you start yourself. ## Logs -GitSpace writes JSON logs to a `gitspace/logs` folder inside the system data directory -(`~/.local/share/gitspace/logs/` on Linux, `~/Library/Application Support/gitspace/logs/` on -macOS, `%APPDATA%\gitspace\logs\` on Windows), one file per day. Files past the retention +GitSpace writes JSON logs to a `Colony/GitSpace/logs` folder inside the system data directory +(`~/.local/share/Colony/GitSpace/logs/` on Linux, `~/Library/Application Support/Colony/GitSpace/logs/` +on macOS, `%LOCALAPPDATA%\Colony\GitSpace\logs\` on Windows), one file per day. Files past the retention count set in Preferences are deleted at startup. Logs never contain a token. ## Environment variables @@ -78,4 +96,4 @@ count set in Preferences are deleted at startup. Logs never contain a token. |---|---| | `GITSPACE_LOG` | the log filter, in [`tracing` `EnvFilter`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html) syntax. The default is `gitspace=info,info`; `GITSPACE_LOG=gitspace=debug` shows GitSpace's own debug messages | | `GITSPACE_TOKEN_MASTER_PASSWORD` | only used when the system keyring is unavailable: a password mixed (Argon2id, salt in `token-salt.bin`) into `token-local-key.bin`, the key that then encrypts `tokens.enc`. In that case it must be set to the same value every time GitSpace starts, or saved tokens cannot be decrypted. It is ignored while the keyring holds the key | -| `GITSPACE_GITHUB_CLIENT_ID`, `GITSPACE_GITLAB_CLIENT_ID` | read when GitSpace is **built**, not when it runs: the OAuth client IDs compiled into the binary, used instead of any ID entered in **Configure OAuth Apps** on the Auth tab. Without them, OAuth sign-in needs a client ID entered there: a GitHub OAuth app with "Enable Device Flow" ticked, or a GitLab application with "Confidential" unticked and the redirect URI `http://127.0.0.1:9876/callback` | +| `GITSPACE_GITHUB_CLIENT_ID`, `GITSPACE_GITLAB_CLIENT_ID` | read when GitSpace is **built**, not when it runs: the OAuth client IDs compiled into the binary, used instead of any ID entered under Preferences → Accounts → OAuth app client IDs. Without them, OAuth sign-in needs a client ID entered there: a GitHub OAuth app with "Enable Device Flow" ticked, or a GitLab application with "Confidential" unticked and the redirect URI `http://127.0.0.1:9876/callback` | diff --git a/docs/guide/install.md b/docs/guide/install.md index 6077dd7..5d626e9 100644 --- a/docs/guide/install.md +++ b/docs/guide/install.md @@ -59,6 +59,6 @@ prints the version without opening a window. everything else keeps working. - **A keyring** to keep tokens in: Keychain on macOS, Credential Manager on Windows, and a Secret Service provider such as GNOME Keyring or KWallet on Linux. Without one, turn on - "Allow encrypted file storage if the native keyring is unavailable"; see + "Allow an encrypted file" in Preferences → Accounts → Token storage; see [configuration](configuration.md) for what that stores and how well it is protected. - **OpenGL** for drawing the window. diff --git a/docs/internals/architecture.md b/docs/internals/architecture.md index 40a2b52..d65dd86 100644 --- a/docs/internals/architecture.md +++ b/docs/internals/architecture.md @@ -1,16 +1,18 @@ # Architecture GitSpace is one binary crate, `gitspace`, with no workspace and no build script. `src/main.rs` -answers `--version`, starts logging and hands the window to iced; everything else lives in -five modules. +answers `--version`, moves old files, starts logging and hands the window to iced; everything +else lives in the modules below. ``` src/ -├── main.rs entry point: --version, logging, iced::application -├── ui/ the iced application: shell, tabs, panels, theme +├── main.rs entry point: --version, the file move, logging, iced::application +├── ui/ the iced application: sidebar, repository tabs, Preferences, widgets ├── git/ repository operations on top of git2, plus the git CLI for three of them ├── auth/ tokens: validation, OAuth, keyring and encrypted-file storage -├── config.rs config.json: preferences, network and logging options, atomic writes +├── config.rs config.json: preferences, the repository list, logging options, atomic writes +├── i18n.rs GitSpace's labels, with i18n/en.json and i18n/fr.json +├── paths.rs the Colony/GitSpace folders and the one-time move from the old ones ├── logging.rs tracing setup: JSON to stderr and to a daily rotating file └── error.rs AppError and the logs directory ``` @@ -22,30 +24,53 @@ token as a plain argument from the UI. ## `ui`: the application `ui/app.rs` holds `GitSpaceApp`, the iced application state. Its `update` routes each -message to the panel it belongs to, applies changes the panels report through `take_*` -methods, and reloads the other panels when one of them changes the repository (commit, -checkout, merge, rebase). Its `view` draws the shell from `ui/layout.rs` (header, left rail, -tab strip, see [gitkraken-layout.md](../project/gitkraken-layout.md)) and the active tab. Its -subscriptions are the Ctrl+1 to Ctrl+7 tab shortcuts, the auto-fetch timer and the toast -timer. - -One file per tab: `clone.rs` (search and clone), `recent.rs` (the Open tab), `repo_overview.rs`, -`stage.rs`, `history.rs`, `branches.rs`, `auth.rs`, and `preferences.rs` for the full-window -Preferences. Shared pieces: `theme.rs` (the Catppuccin palettes), `menu.rs` (menu items), -`fonts.rs` (the bundled JetBrains Mono Nerd Font, Regular only), `context.rs` (the open -repository) and `notifications.rs` (toasts). - -Every git, keyring and network call runs in an iced `Task`, on tokio's blocking pool, and -returns its result as a message. Results carry the repository path they were computed for, -and a panel drops a result for a repository that is no longer open. `view` functions only -read state. +message to the screen it belongs to, saves the preferences after each change, and reloads +the other tabs when one of them changes the repository (commit, checkout, merge, rebase, +pull, a stash job). A fetch or a push leaves HEAD and the working tree as they were, so it +reloads only the header and Branches. When the window gains focus it reads the header, +Changes, Branches and Stashes again, because another program may have changed the +repository. In both cases History is left as it is so that its selection stays. Its `view` +puts the sidebar next to the content area: the repository header and the active tab, the +Add repository screen when no repository is open, or Preferences while they are open (see +[gitkraken-layout.md](../project/gitkraken-layout.md)). +Its subscriptions are the keyboard shortcuts, window focus, the auto-fetch timer and the +toast timer. At startup it opens the last repository on Changes when "Reopen the last +repository at startup" is on and the folder still exists. + +The screens: + +| File | What it draws | +|---|---| +| `sidebar.rs`, `repo_list.rs` | the repository list, its search and its groups; `repo_list.rs` decides which rows show and in which order | +| `repo_header.rs` | the header of the open repository with Fetch, Pull and Push, and the tab strip | +| `changes.rs`, `history.rs`, `branches.rs`, `stashes.rs` | the four tabs; `diff_view.rs` draws the diffs that Changes, History and Stashes show | +| `add_repo.rs` | the Add repository screen: GitHub and GitLab search, URL, local folder, clone progress | +| `preferences/` | the Preferences page: `mod.rs` with the kit's General, Appearance and Accessibility, then `accounts.rs`, `git.rs`, `network.rs` and `about.rs` | +| `widgets/` | what the kit does not have yet: buttons, chips, tabs, the segmented control, menus, toasts, and one line of text that ends in "…" when it is cut | +| `context.rs` | `RepoContext`, the open repository, and `git_task`, which runs a git call off the UI thread | + +Colours come from `colony_ui::theme::Palette`, sizes from `Typography::current()` and fonts +from colony-ui, read each time a widget is drawn; `main.rs` registers the font files. Every +visible string goes through `crate::i18n::t` or the kit's `colony_ui::i18n::t`. Two tests +keep this true: `ui_has_no_hex_colours` in `ui/widgets/mod.rs` and +`ui_has_no_literal_strings` in `i18n.rs`. Another test checks that English and French have +the same keys. + +Every git, keyring, network and folder-scan call runs in an iced `Task`, on tokio's blocking +pool, and returns its result as a message. Results carry the repository path they were +computed for, and a screen drops a result for a repository that is no longer open. `view` +functions only read state. The sidebar status of every repository comes from +`git::status::quick_status`, at most four at a time, and the clone folder is scanned by +`git::discover::discover_repositories`. ## `git`: repository operations Thin functions over [git2](https://docs.rs/git2) (libgit2, vendored OpenSSL), one file per area: `clone.rs`, `remote.rs` (fetch, pull as a fast-forward of the checked-out branch only, push of the checked-out branch to its upstream), `branch.rs`, `commit.rs`, `log.rs`, -`diff.rs`, `status.rs`, `stash.rs`, `compare.rs` and `merge.rs`. Checkout, pull and stash +`diff.rs`, `status.rs`, `stash.rs`, `merge.rs` and `discover.rs` (the repositories one level +down in a folder). `status.rs` reads changed files with their line counts from diff stats, +without building patches, and `quick_status` reads only what the sidebar shows. Checkout, pull and stash apply use libgit2's safe checkout, which fails instead of overwriting a modified file. `transport.rs` is shared by every network operation: it checks the URL against the network @@ -80,11 +105,12 @@ host is refused before any request. Signing out removes the token from the keyri redirects turned off: - **GitHub** uses the device flow (RFC 8628). `DeviceFlow::start` asks `github.com` for a - one-time code and refuses a verification page that is not `https://`; the Auth tab shows - the code, and `DeviceFlow::wait` polls the token endpoint at the interval GitHub sets. It - adds 5 seconds on `slow_down`, doubles the interval up to a minute while the endpoint cannot - be reached or answers with a rate limit or a server error, and stops when the code is approved, denied or expired, or the user cancels. Only - the client ID is sent, never a client secret. + one-time code and refuses a verification page that is not `https://`; Preferences → + Accounts shows the code, and `DeviceFlow::wait` polls the token endpoint at the interval + GitHub sets. It adds 5 seconds on `slow_down`, doubles the interval up to a minute while + the endpoint cannot be reached or answers with a rate limit or a server error, and stops + when the code is approved, denied or expired, or the user cancels. Only the client ID is + sent, never a client secret. - **GitLab** uses the authorization code flow with PKCE: `OAuthFlow` opens the browser and listens for the callback on `127.0.0.1` port 9876, the redirect URI registered with the GitLab application. If that port is in use, sign-in stops with an error before the browser @@ -92,7 +118,8 @@ redirects turned off: An expired GitLab token is refreshed with its refresh token when it is next needed. The client IDs come from `GITSPACE_GITHUB_CLIENT_ID` and `GITSPACE_GITLAB_CLIENT_ID` at build -time (`ui/auth.rs`), and otherwise from the IDs entered under Configure OAuth Apps. +time (`ui/preferences/accounts.rs`), and otherwise from the IDs entered under Preferences → +Accounts → OAuth app client IDs. ## `config`, `logging`, `error` @@ -107,9 +134,11 @@ files past the configured retention at startup. ## Files and paths -All locations come from the `dirs` crate: settings and token files in -`/gitspace/`, logs in `/gitspace/logs/`. Each module builds its own path -from those two roots; there is no central paths module yet. +`paths.rs` owns every location: settings and token files in `colony_ui::paths::config_dir("GitSpace")`, +logs in `logs/` under `colony_ui::paths::data_dir("GitSpace")`. `main` calls +`paths::init_at_startup` before logging starts; it moves the files of the old +`/gitspace/` and `/gitspace/` folders once and fixes the folders that +`paths::effective_dirs` returns for the run (the old ones when the move failed). ## Features diff --git a/docs/project/gitkraken-layout.md b/docs/project/gitkraken-layout.md index e6bc4b9..77cef6b 100644 --- a/docs/project/gitkraken-layout.md +++ b/docs/project/gitkraken-layout.md @@ -1,52 +1,89 @@ -# The GitKraken-style layout +# The window layout -GitSpace borrows its overall shape from GitKraken: a navigation rail on the left, one -working area in the middle, and the repository you are working on always one click away. -This page describes the shell as it is built today, in `src/ui/layout.rs` and -`src/ui/app.rs`, and what it deliberately leaves out. +GitSpace started from GitKraken's shape: a rail on the left and one working area. The +colony-ui redesign kept the idea of a rail and changed what it holds. The sidebar is now the +list of repositories, and a repository's sections are tabs in the content area, so switching +repository or section takes one click. This page describes the window as `src/ui/app.rs`, +`src/ui/sidebar.rs` and `src/ui/repo_header.rs` build it. ## The window ``` -+----------------------------------------------------------------+ -| GitSpace Workspace shell (header, 48 px)| -+---------------+------------------------------------------------+ -| Navigation | Clone | Open | Repo Overview | Stage | ... | -| Workspaces +------------------------------------------------+ -| Actions | | -| Context | active tab (scrolls) | -| (resizable, | | -| 220 px) | | -+---------------+------------------------------------------------+ ++---------------+--------------------------------------------------+ +| GitSpace | colony-ui [main] [↑2 ↓0] ▤ >_ Fetch Pull Push| +| Repos · 34 ⌕ | Changes·4 History Branches Stashes·2 | +| PINNED +--------------------------------------------------+ +| colony-ui 4 | | +| GitSpace ↑2| active tab | +| RECENT | | +| Eidos ↓3| | +| ... | | +| + Clone or open | +| Ctrl+K search | | ++---------------+--------------------------------------------------+ ``` -- **Header.** Pinned to the top. Clicking the GitSpace name opens Preferences, which - replaces the whole window until it is closed (General, Appearance and GitSpace - categories). -- **Left rail.** A side panel, 220 px wide, in three groups: - - *Workspaces*: Recent opens the Open tab; Remote Repos opens Clone. - - *Actions*: Clone, Open, New Branch (the Branches tab) and Sync (the Stage tab). - - *Context*: the active repository with its path, and buttons to open it in the file - manager or copy its path. "No repository selected" until one is open. -- **Centre.** A tab strip above the content of the active tab. Only the content scrolls; the - header, rail and tab strip stay where they are. +The window has no other chrome: no header bar, no menu bar. -## Tabs +## Sidebar -In their default order: Clone, Open, Repo Overview, Stage, History, Branches and Auth. +The sidebar is 240 px wide. -- **Click** a tab to show it. The active tab is underlined in the theme's accent colour. -- **Ctrl+1 to Ctrl+7** (Cmd on macOS) jump to the tab in that position. +- The GitSpace button at the top opens Preferences, and the same button closes it. +- A label row shows "Repositories" and how many there are, with a magnifier at its right + end. The magnifier or Ctrl+K replaces the row with a search field of the same height, so + the list below does not move. The search matches names, ignoring case, and highlights the + matched letters. Up and Down move the selection, Enter opens the repository, and Escape + closes the search and clears it. +- The list has two groups. PINNED comes first; RECENT holds every other repository, by the + time it was last opened, and repositories found in the clone folder but never opened come + last, by name. While searching, one group shows the results. +- Each row shows the number of changed files and the ahead and behind counts against the + upstream. A repository whose folder is gone is dimmed and marked "missing". +- A right-click on a row opens a menu: Pin or Unpin, Remove from list, Open folder and + Open terminal. +- "+ Clone or open" at the bottom opens the Add repository screen, and a hint line under it + lists two shortcuts. + +The row status comes from a background scan that reads the branch, the ahead and behind +counts and the number of changed files, never a patch. At most four repositories are +scanned at the same time. The scan runs at startup, when the window gains focus, after an +operation on a repository and on the auto-fetch timer. + +## Content area + +With a repository open, the content area has a header and four tabs: + +- The header shows the repository name, a chip with the branch (or "detached at" and a + short hash), a chip with the ahead and behind counts when the branch has an upstream, + buttons to open the folder and a terminal, and Fetch, Pull and Push. Push is the primary + button when the branch is ahead, Pull when it is behind. The "⋯" menu at the right lists + the remotes. +- The tabs are Changes (with the number of changed files), History, Branches and Stashes + (with the number of stashes). + +With no repository open, on the first start for example, the content area shows the Add +repository screen. Preferences replace the content area while they are open; the sidebar +stays. + +## Keyboard + +| Keys | Action | +|---|---| +| Ctrl+K | open the repository search | +| Ctrl+1 to Ctrl+4 | Changes, History, Branches, Stashes | +| Alt+Up, Alt+Down | previous or next repository in the list | +| Ctrl+, | open or close Preferences | +| F2 | rename the selected branch, on the Branches tab | +| Escape | close the search, a menu or Preferences | + +On macOS, Cmd replaces Ctrl. ## What it leaves out -GitKraken has more than this, and so did earlier notes for GitSpace. None of the following -exists, and none of it is planned yet: +GitKraken has more than this. None of the following exists, and none of it is planned yet: -- a right-hand context rail; -- context menus on tabs, or tabs that detach into their own window; -- a commit graph: History is a plain list of commits; +- a commit graph with lanes: History draws one line with a dot per commit; +- interactive rebase, blame, amend and staging single hunks; +- tabs that detach into their own window; - telemetry of any kind, including on navigation (see [Privacy](../../README.md#privacy)). - -The interface runs on iced and is meant to move to the shared Colony UI kit (see -[ui-stack.md](ui-stack.md)); this page changes with that move. diff --git a/docs/project/ui-stack.md b/docs/project/ui-stack.md index e5d7cd3..5a47826 100644 --- a/docs/project/ui-stack.md +++ b/docs/project/ui-stack.md @@ -1,21 +1,43 @@ # The UI stack -## Today: iced 0.13 - -GitSpace draws its window with [iced](https://iced.rs) 0.13 on the wgpu renderer, with tokio -as its runtime. The application follows iced's model: `GitSpaceApp` in `src/ui/app.rs` holds -the state, `update` handles one message at a time, and `view` builds the header, the left -rail and the active tab from that state. Each panel in `src/ui/` has its own `Message` enum, -`update` and `view`. - -Git, keyring and network work never runs in `update` or `view`. It goes to an iced `Task` on -tokio's blocking pool and comes back as a message, so the window keeps drawing during a clone, -a search, a fetch, a merge or a keyring prompt. - -The look is GitSpace's own: four Catppuccin palettes in `src/ui/theme.rs`, the bundled -JetBrains Mono Nerd Font (Regular) in `src/ui/fonts.rs`, and menu items in `src/ui/menu.rs`. - -## Before: egui +## Today: iced 0.14 and colony-ui + +GitSpace draws its window with [iced](https://iced.rs) 0.14 on the wgpu renderer, with tokio +as its runtime, and takes its look from +[colony-ui](https://crates.io/crates/colony-ui) 0.1.6, the design system the other Project +Colony programs share. The application follows iced's model: `GitSpaceApp` in +`src/ui/app.rs` holds the state, `update` handles one message at a time, and `view` builds +the sidebar and the content area from that state. Each screen in `src/ui/` has its own +`Message` enum, `update` and `view`. + +Git, keyring, network and folder-scan work never runs in `update` or `view`. It goes to an +iced `Task` on tokio's blocking pool and comes back as a message carrying the repository +path, so the window keeps drawing during a clone, a search, a fetch, a merge or a keyring +prompt, and a result for a repository that is no longer open is dropped. + +What comes from colony-ui: + +- the palettes of its 26 theme families and the accent colours, read through + `colony_ui::theme::Palette` each time a widget is drawn; +- the text sizes from `Typography::current()` and the interface, glyph and + dyslexia-friendly fonts; +- the sidebar pieces (identity button, nav labels and items, the selection style), the + Preferences page with its General, Appearance and Accessibility categories, dropdowns, + toggles and the success toast; +- the per-user folders (`Colony/GitSpace/`) and the English and French locale switch. + +GitSpace adds the widgets the kit does not have yet in `src/ui/widgets/`: push buttons in +four strengths, chips, tabs with counts, a segmented control, "⋯" and right-click menus +drawn as iced overlays, error toasts with action buttons, and one line of text that ends in +"…" when its space is too narrow. They follow the kit's rules +(palette roles, `Typography`, the selection style) so they can move into colony-ui later. + +Nothing in `src/ui/` stores a colour, a size, a font or a translated string. A test fails on +any hex colour literal there, and another on a literal user-visible string. Changing the +theme, accent, text size, dyslexia font or language in Preferences therefore redraws every +screen at once. + +## Before: egui, then iced 0.13 The first versions used [egui](https://github.com/emilk/egui) 0.27 through eframe. egui was chosen over Tauri with a web frontend to keep one language end to end and a small binary @@ -23,10 +45,7 @@ with no web view. It was replaced because the other Project Colony programs shar system built on iced, and because the immediate-mode panels ran their git calls inside the frame. -## Where it is going: colony-ui - -The shared design system, -[colony-ui](https://github.com/Project-Colony/Project-Colony-Resources/tree/main/crates/colony-ui), -is built on iced 0.14. It brings the shared typography, themes, preferences page, English and -French locales and per-user paths. Moving GitSpace onto it means upgrading from iced 0.13 to -0.14 first. `rust-version` is 1.100, above the 1.88 floor of iced 0.14. +The first iced version ran on iced 0.13 with GitSpace's own look: four Catppuccin palettes, a +header, a left rail and a strip of seven tabs. colony-ui needs iced 0.14, so the move to the +kit started with that upgrade. `rust-version` is 1.100, above the 1.88 floor of iced 0.14 +and colony-ui. diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 31fb7a6..5f40b8a 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -20,6 +20,7 @@ use url::Url; use zeroize::{Zeroize, ZeroizeOnDrop}; use crate::config::write_private; +use crate::i18n::{t, tf}; pub use oauth::{DeviceFlow, OAuthFlow, OAuthProvider, OAuthResult, OAuthToken}; @@ -74,6 +75,15 @@ impl AuthManager { } } + /// A manager whose token files live in `dir`, with a fresh key: tests never touch the + /// keyring or the real settings folder. + #[cfg(test)] + pub(crate) fn in_dir(dir: &std::path::Path) -> Self { + Self { + storage: tests::storage_in(dir), + } + } + /// Returns the token saved for `host`. An expired OAuth token with a refresh token is /// refreshed first, which blocks on one HTTP request; if that fails, the saved access /// token is returned and the host will reject it. @@ -141,26 +151,26 @@ impl AuthManager { // Basic format validation if trimmed.is_empty() { - return Err("Token cannot be empty".to_string()); + return Err(t("token_empty").to_string()); } if trimmed.len() < MIN_TOKEN_LENGTH { - return Err(format!( - "Token is too short (minimum {} characters)", - MIN_TOKEN_LENGTH + return Err(tf( + "token_too_short", + &[("count", &MIN_TOKEN_LENGTH.to_string())], )); } if trimmed.len() > MAX_TOKEN_LENGTH { - return Err(format!( - "Token is too long (maximum {} characters)", - MAX_TOKEN_LENGTH + return Err(tf( + "token_too_long", + &[("count", &MAX_TOKEN_LENGTH.to_string())], )); } // Check for invalid characters (tokens should be printable ASCII) if !trimmed.chars().all(|c| c.is_ascii_graphic()) { - return Err("Token contains invalid characters".to_string()); + return Err(t("token_invalid_characters").to_string()); } let origin = normalize_host(host)?; @@ -195,8 +205,12 @@ impl AuthManager { // Store the full OAuth token (with refresh token) as JSON in a separate entry let oauth_key = format!("oauth:{host}"); - let oauth_json = serde_json::to_string(token) - .map_err(|e| format!("Failed to serialize OAuth token: {}", e))?; + let oauth_json = serde_json::to_string(token).map_err(|err| { + tf( + "token_oauth_serialize_failed", + &[("error", &err.to_string())], + ) + })?; self.storage.set_token(&oauth_key, &oauth_json)?; info!( @@ -317,7 +331,7 @@ impl TokenStorage { } }) } else if keyring_result.is_err() { - Err("Native keyring unavailable and encrypted storage is disabled".to_string()) + Err(t("keyring_unavailable_no_fallback").to_string()) } else { Ok(()) }; @@ -406,25 +420,25 @@ impl TokenStorage { fn store_in_keyring(&self, host: &str, token: &str) -> Result<(), String> { let entry = Entry::new(SERVICE_NAME, host) - .map_err(|err| format!("Failed to access keyring: {err}"))?; + .map_err(|err| tf("keyring_access_failed", &[("error", &err.to_string())]))?; entry .set_password(token) - .map_err(|err| format!("Failed to store token in keyring: {err}")) + .map_err(|err| tf("keyring_store_failed", &[("error", &err.to_string())])) } fn fetch_from_keyring(&self, host: &str) -> Result, String> { let entry = Entry::new(SERVICE_NAME, host) - .map_err(|err| format!("Failed to access keyring: {err}"))?; + .map_err(|err| tf("keyring_access_failed", &[("error", &err.to_string())]))?; match entry.get_password() { Ok(password) => Ok(Some(password)), Err(keyring::Error::NoEntry) => Ok(None), - Err(err) => Err(format!("Failed to read keyring: {err}")), + Err(err) => Err(tf("keyring_read_failed", &[("error", &err.to_string())])), } } fn remove_from_keyring(&self, host: &str) -> Result<(), String> { let entry = Entry::new(SERVICE_NAME, host) - .map_err(|err| format!("Failed to access keyring: {err}"))?; + .map_err(|err| tf("keyring_access_failed", &[("error", &err.to_string())]))?; match entry.delete_credential() { Ok(()) => Ok(()), Err(keyring::Error::NoEntry) => Ok(()), @@ -434,7 +448,7 @@ impl TokenStorage { warn!(target: "gitspace::auth", error = %err, host, "native keyring unavailable; nothing to remove there"); Ok(()) } - Err(err) => Err(format!("Failed to remove keyring entry: {err}")), + Err(err) => Err(tf("keyring_remove_failed", &[("error", &err.to_string())])), } } @@ -446,10 +460,14 @@ impl TokenStorage { fn write_fallback(&self, map: &TokenMap) -> Result<(), String> { let blob = encrypt_tokens(map, &self.key.0)?; - let serialized = serde_json::to_string_pretty(&blob) - .map_err(|err| format!("Failed to serialize credentials: {err}"))?; + let serialized = serde_json::to_string_pretty(&blob).map_err(|err| { + tf( + "credentials_serialize_failed", + &[("error", &err.to_string())], + ) + })?; write_private(&self.path, serialized.as_bytes()) - .map_err(|err| format!("Failed to write credentials: {err}")) + .map_err(|err| tf("credentials_write_failed", &[("error", &err.to_string())])) } /// Reads the saved tokens before a rewrite. A file that exists but cannot be read or @@ -457,11 +475,13 @@ impl TokenStorage { /// empty map: rewriting it would drop every other saved token. fn read_fallback_for_update(&self) -> Result { self.read_fallback().map_err(|err| { - format!( - "{err}. {} was left untouched so the other saved tokens are kept. Unlock the \ - system keyring or use the same {MASTER_PASSWORD_ENV} as when the tokens were \ - saved, then restart GitSpace, or move the file aside to start over", - self.path.display() + tf( + "credentials_left_untouched", + &[ + ("error", &err), + ("path", &self.path.display().to_string()), + ("variable", MASTER_PASSWORD_ENV), + ], ) }) } @@ -470,10 +490,15 @@ impl TokenStorage { let data = match fs::read_to_string(&self.path) { Ok(data) => data, Err(err) if err.kind() == ErrorKind::NotFound => return Ok(TokenMap::default()), - Err(err) => return Err(format!("Failed to read credential file: {err}")), + Err(err) => { + return Err(tf( + "credentials_read_failed", + &[("error", &err.to_string())], + )) + } }; let blob: EncryptedTokenFile = serde_json::from_str(&data) - .map_err(|err| format!("Failed to parse credential file: {err}"))?; + .map_err(|err| tf("credentials_parse_failed", &[("error", &err.to_string())]))?; let err = match decrypt_tokens(&blob, &self.key.0) { Ok(map) => return Ok(map), Err(err) => err, @@ -522,16 +547,21 @@ impl TokenStorage { let data = match fs::read_to_string(&self.host_path) { Ok(data) => data, Err(err) if err.kind() == ErrorKind::NotFound => return Ok(HostIndex::default()), - Err(err) => return Err(format!("Failed to read host index: {err}")), + Err(err) => return Err(tf("host_index_read_failed", &[("error", &err.to_string())])), }; - serde_json::from_str(&data).map_err(|err| format!("Failed to parse host index: {err}")) + serde_json::from_str(&data) + .map_err(|err| tf("host_index_parse_failed", &[("error", &err.to_string())])) } fn write_host_index(&self, index: &HostIndex) -> Result<(), String> { - let serialized = serde_json::to_string_pretty(index) - .map_err(|err| format!("Failed to serialize host index: {err}"))?; + let serialized = serde_json::to_string_pretty(index).map_err(|err| { + tf( + "host_index_serialize_failed", + &[("error", &err.to_string())], + ) + })?; write_private(&self.host_path, serialized.as_bytes()) - .map_err(|err| format!("Failed to write host index: {err}")) + .map_err(|err| tf("host_index_write_failed", &[("error", &err.to_string())])) } pub fn set_allow_encrypted_fallback(&mut self, allowed: bool) { @@ -544,11 +574,11 @@ fn encrypt_tokens(map: &TokenMap, key: &[u8; 32]) -> Result Result PathBuf { - dirs::config_dir() - .unwrap_or_else(|| PathBuf::from(".")) - .join(SERVICE_NAME) + crate::paths::effective_dirs().0 } /// Loads or creates the local encryption key, used when the keyring cannot hold the key. @@ -632,14 +682,14 @@ fn derive_master_key(password: &[u8], salt: &[u8], out: &mut [u8; 32]) -> bool { fn load_or_create_keyring_key() -> Result<[u8; 32], String> { let entry = Entry::new(SERVICE_NAME, TOKEN_KEYRING_ENTRY) - .map_err(|err| format!("Failed to access keyring: {err}"))?; + .map_err(|err| tf("keyring_access_failed", &[("error", &err.to_string())]))?; match entry.get_password() { Ok(password) => { let decoded = general_purpose::STANDARD .decode(password.trim()) - .map_err(|err| format!("Failed to decode keyring token key: {err}"))?; + .map_err(|err| tf("keyring_key_decode_failed", &[("error", &err.to_string())]))?; if decoded.len() != 32 { - return Err("Keyring token key is invalid".to_string()); + return Err(t("keyring_key_invalid").to_string()); } let mut key = [0u8; 32]; key.copy_from_slice(&decoded); @@ -650,10 +700,13 @@ fn load_or_create_keyring_key() -> Result<[u8; 32], String> { let encoded = general_purpose::STANDARD.encode(key); entry .set_password(&encoded) - .map_err(|err| format!("Failed to store token key in keyring: {err}"))?; + .map_err(|err| tf("keyring_key_store_failed", &[("error", &err.to_string())]))?; Ok(key) } - Err(err) => Err(format!("Failed to read keyring token key: {err}")), + Err(err) => Err(tf( + "keyring_key_read_failed", + &[("error", &err.to_string())], + )), } } @@ -703,12 +756,14 @@ fn normalize_host(host: &str) -> Result { } else { format!("https://{trimmed}") }; - let parsed = - Url::parse(&with_scheme).map_err(|err| format!("Invalid host \"{trimmed}\": {err}"))?; + let parsed = Url::parse(&with_scheme).map_err(|err| { + tf( + "token_invalid_host", + &[("host", trimmed), ("error", &err.to_string())], + ) + })?; if parsed.scheme() != "https" { - return Err( - "The host must use https: GitSpace never sends a token over plain HTTP.".to_string(), - ); + return Err(t("token_host_not_https").to_string()); } Ok(parsed.origin().ascii_serialization()) } @@ -738,6 +793,31 @@ fn token_check(origin: &str) -> Option { } } +/// The account name `token` belongs to on `host`: `login` on GitHub, `username` on GitLab. +/// `None` for another host or when the request fails. +pub async fn fetch_login(host: &str, token: &str) -> Option { + let (TokenCheck::GitHub(url) | TokenCheck::GitLab(url)) = + token_check(&normalize_host(host).ok()?)?; + let body: serde_json::Value = get_http_client() + .get(url) + .bearer_auth(token) + .send() + .await + .ok()? + .error_for_status() + .ok()? + .json() + .await + .ok()?; + user_name(&body) +} + +/// The account name in a GitHub or GitLab `/user` response. +fn user_name(body: &serde_json::Value) -> Option { + let name = body.get("login").or_else(|| body.get("username"))?; + name.as_str().map(str::to_string) +} + async fn validate_github(client: &Client, url: &str, token: &str) -> Result<(), String> { let response = client .get(url) @@ -745,12 +825,12 @@ async fn validate_github(client: &Client, url: &str, token: &str) -> Result<(), .header(AUTHORIZATION, format!("Bearer {}", token)) .send() .await - .map_err(|err| format!("GitHub validation failed: {err}"))?; + .map_err(|err| token_check_failed("GitHub", err))?; if response.status().is_success() { Ok(()) } else { - Err(format!("GitHub rejected token ({}).", response.status())) + Err(token_rejected("GitHub", response.status())) } } @@ -767,15 +847,29 @@ async fn validate_gitlab(client: &Client, url: &str, token: &str) -> Result<(), .headers(headers) .send() .await - .map_err(|err| format!("GitLab validation failed: {err}"))?; + .map_err(|err| token_check_failed("GitLab", err))?; if response.status().is_success() { Ok(()) } else { - Err(format!("GitLab rejected token ({}).", response.status())) + Err(token_rejected("GitLab", response.status())) } } +fn token_check_failed(provider: &str, err: reqwest::Error) -> String { + tf( + "token_check_failed", + &[("provider", provider), ("error", &err.to_string())], + ) +} + +fn token_rejected(provider: &str, status: reqwest::StatusCode) -> String { + tf( + "token_rejected", + &[("provider", provider), ("status", &status.to_string())], + ) +} + /// Returns the lowercase host name of a URL, `host:port`, scp-like `user@host:path` or bare /// host. pub fn extract_host(target: &str) -> Option { @@ -859,7 +953,7 @@ mod tests { } /// A storage in `dir` with a fresh random key, so two calls never share a key. - fn storage_in(dir: &std::path::Path) -> TokenStorage { + pub(super) fn storage_in(dir: &std::path::Path) -> TokenStorage { TokenStorage { key: SecureKey(Generate::generate()), local_key_path: Some(dir.join(TOKEN_LOCAL_KEY_FILE)), @@ -1093,6 +1187,15 @@ mod tests { assert_eq!(extract_host("file:///home/me/repo"), None); } + #[test] + fn user_name_reads_github_login_and_gitlab_username() { + let github = serde_json::json!({ "login": "MotherSphere", "id": 1 }); + let gitlab = serde_json::json!({ "username": "mother", "name": "Mother" }); + assert_eq!(user_name(&github).as_deref(), Some("MotherSphere")); + assert_eq!(user_name(&gitlab).as_deref(), Some("mother")); + assert_eq!(user_name(&serde_json::json!({ "id": 1 })), None); + } + #[tokio::test] async fn plain_http_host_is_refused_before_any_request() { let dir = tempfile::tempdir().expect("tempdir"); diff --git a/src/auth/oauth.rs b/src/auth/oauth.rs index db0d128..9d14419 100644 --- a/src/auth/oauth.rs +++ b/src/auth/oauth.rs @@ -23,6 +23,8 @@ use reqwest::header::ACCEPT; use serde::{Deserialize, Serialize}; use tracing::{error, info, warn}; +use crate::i18n::{t, tf}; + /// OAuth callback server timeout. const CALLBACK_TIMEOUT: Duration = Duration::from_secs(120); @@ -46,8 +48,6 @@ const MAX_POLL_BACKOFF: Duration = Duration::from_secs(60); const BAD_REQUEST: &str = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; -const CODE_EXPIRED: &str = "The code expired before it was approved. Start the sign-in again."; - /// OAuth provider configuration. #[derive(Debug, Clone)] pub struct OAuthProvider { @@ -118,6 +118,10 @@ pub struct OAuthToken { pub client_id: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub token_url: Option, + /// The account name the token belongs to, read once at sign-in. Missing when that read + /// failed and from tokens saved by older releases. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub login: Option, } impl OAuthToken { @@ -131,6 +135,7 @@ impl OAuthToken { host: provider.host.clone(), client_id: Some(provider.client_id.clone()), token_url: Some(provider.token_url.clone()), + login: None, } } @@ -141,21 +146,18 @@ impl OAuthToken { let refresh_token = self .refresh_token .as_ref() - .ok_or("The OAuth token has no refresh token")?; + .ok_or(t("oauth_no_refresh_token"))?; let (Some(client_id), Some(token_url)) = (&self.client_id, &self.token_url) else { - return Err(format!( - "The {} token was saved without its client ID; sign in again", - self.provider - )); + return Err(tf("oauth_no_client_id", &[("provider", &self.provider)])); }; let client = BasicClient::new(ClientId::new(client_id.clone())).set_token_uri( - TokenUrl::new(token_url.clone()).map_err(|e| format!("Invalid token URL: {e}"))?, + TokenUrl::new(token_url.clone()).map_err(|e| invalid_url(token_url, e))?, ); let http_client = http_client()?; let response = client .exchange_refresh_token(&RefreshToken::new(refresh_token.clone())) .request(&|request| send(&http_client, request)) - .map_err(|e| format!("Token refresh failed: {e}"))?; + .map_err(|e| tf("oauth_refresh_failed", &[("error", &e.to_string())]))?; Ok(Self { access_token: response.access_token().secret().to_string(), @@ -208,9 +210,12 @@ impl OAuthFlow { pub fn new(provider: OAuthProvider) -> Result { // Checked before the browser opens, so a busy port is reported up front. TcpListener::bind(("127.0.0.1", CALLBACK_PORT)).map_err(|e| { - format!( - "Port {CALLBACK_PORT} is needed for the GitLab sign-in callback but is in use ({e}). \ - Close the program using it and try again." + tf( + "oauth_port_in_use", + &[ + ("port", &CALLBACK_PORT.to_string()), + ("error", &e.to_string()), + ], ) })?; let redirect_url = format!("http://127.0.0.1:{CALLBACK_PORT}/callback"); @@ -219,15 +224,15 @@ impl OAuthFlow { let client = BasicClient::new(ClientId::new(provider.client_id.clone())) .set_auth_uri( AuthUrl::new(provider.auth_url.clone()) - .map_err(|e| format!("Invalid auth URL: {}", e))?, + .map_err(|e| invalid_url(&provider.auth_url, e))?, ) .set_token_uri( TokenUrl::new(provider.token_url.clone()) - .map_err(|e| format!("Invalid token URL: {}", e))?, + .map_err(|e| invalid_url(&provider.token_url, e))?, ) .set_redirect_uri( - RedirectUrl::new(redirect_url) - .map_err(|e| format!("Invalid redirect URL: {}", e))?, + RedirectUrl::new(redirect_url.clone()) + .map_err(|e| invalid_url(&redirect_url, e))?, ); Ok(Self { @@ -276,7 +281,7 @@ impl OAuthFlow { // Open browser if let Err(err) = webbrowser::open(&auth_url) { - return OAuthResult::Error(format!("Failed to open browser: {}", err)); + return OAuthResult::Error(tf("prefs_browser_failed", &[("error", &err.to_string())])); } // Wait for callback @@ -289,11 +294,11 @@ impl OAuthFlow { /// Waits for the OAuth callback on a local HTTP server. fn wait_for_callback(&self) -> Result { let listener = TcpListener::bind(("127.0.0.1", CALLBACK_PORT)) - .map_err(|e| format!("Failed to bind callback server: {}", e))?; + .map_err(|e| tf("oauth_callback_listen_failed", &[("error", &e.to_string())]))?; listener .set_nonblocking(true) - .map_err(|e| format!("Failed to set non-blocking: {}", e))?; + .map_err(|e| tf("oauth_callback_listen_failed", &[("error", &e.to_string())]))?; let start = Instant::now(); let expected_state = self @@ -311,7 +316,7 @@ impl OAuthFlow { loop { // Check timeout if start.elapsed() > CALLBACK_TIMEOUT { - return Err("OAuth callback timed out".to_string()); + return Err(t("oauth_callback_timed_out").to_string()); } // Try to accept connection @@ -346,7 +351,10 @@ impl OAuthFlow { thread::sleep(Duration::from_millis(100)); } Err(e) => { - return Err(format!("Failed to accept connection: {}", e)); + return Err(tf( + "oauth_callback_accept_failed", + &[("error", &e.to_string())], + )); } } } @@ -355,7 +363,7 @@ impl OAuthFlow { /// Exchanges the authorization code for tokens. fn exchange_code(self, code: String) -> OAuthResult { let Some(pkce_verifier) = self.pkce_verifier else { - return OAuthResult::Error("PKCE verifier not initialized".to_string()); + return OAuthResult::Error(t("oauth_pkce_missing").to_string()); }; info!( @@ -393,7 +401,10 @@ impl OAuthFlow { error = %err, "Token exchange failed" ); - OAuthResult::Error(format!("Token exchange failed: {}", err)) + OAuthResult::Error(tf( + "oauth_token_exchange_failed", + &[("error", &err.to_string())], + )) } } } @@ -417,11 +428,11 @@ impl DeviceFlow { let device_auth_url = provider .device_auth_url .clone() - .ok_or_else(|| format!("{} does not support the device flow", provider.name))?; + .ok_or_else(|| tf("oauth_no_device_flow", &[("provider", &provider.name)]))?; let client = BasicClient::new(ClientId::new(provider.client_id.clone())) .set_device_authorization_url( - DeviceAuthorizationUrl::new(device_auth_url) - .map_err(|e| format!("Invalid device authorization URL: {e}"))?, + DeviceAuthorizationUrl::new(device_auth_url.clone()) + .map_err(|e| invalid_url(&device_auth_url, e))?, ); let http_client = http_client()?; @@ -434,13 +445,18 @@ impl DeviceFlow { .exchange_device_code() .add_scopes(provider.scopes.iter().cloned().map(Scope::new)) .request(&|request| send(&http_client, request)) - .map_err(|e| format!("Could not get a sign-in code from {}: {e}", provider.name))?; + .map_err(|e| { + tf( + "oauth_code_request_failed", + &[("provider", &provider.name), ("error", &e.to_string())], + ) + })?; // The user is sent to this page, so never to anything but HTTPS. if details.verification_uri().url().scheme() != "https" { - return Err(format!( - "{} sent a verification page that is not HTTPS", - provider.name + return Err(tf( + "oauth_verification_not_https", + &[("provider", &provider.name)], )); } @@ -478,7 +494,7 @@ impl DeviceFlow { return OAuthResult::Cancelled; } if Instant::now() >= deadline { - return OAuthResult::Error(CODE_EXPIRED.to_string()); + return OAuthResult::Error(t("oauth_code_expired").to_string()); } let poll = match self.request_token() { @@ -557,11 +573,17 @@ fn next_device_poll( DeviceCodeErrorResponseType::SlowDown => { return DevicePoll::Retry(interval + SLOW_DOWN_STEP) } - DeviceCodeErrorResponseType::ExpiredToken => CODE_EXPIRED.to_string(), + DeviceCodeErrorResponseType::ExpiredToken => t("oauth_code_expired").to_string(), DeviceCodeErrorResponseType::AccessDenied => { - format!("The sign-in was denied on {}.", provider.name) + tf("oauth_denied", &[("provider", &provider.name)]) } - _ => format!("{} refused the sign-in: {response}", provider.name), + _ => tf( + "oauth_refused", + &[ + ("provider", &provider.name), + ("error", &response.to_string()), + ], + ), }; return DevicePoll::Done(OAuthResult::Error(result)); } @@ -572,9 +594,12 @@ fn next_device_poll( ))), // A rate limit or a server or proxy error page is passing: ask again later. Err(_) if status == 429 || status >= 500 => DevicePoll::Unavailable, - Err(_) => DevicePoll::Done(OAuthResult::Error(format!( - "Unexpected answer from {} (HTTP {status})", - provider.name + Err(_) => DevicePoll::Done(OAuthResult::Error(tf( + "oauth_unexpected_answer", + &[ + ("provider", &provider.name), + ("status", &status.to_string()), + ], ))), } } @@ -595,7 +620,15 @@ fn http_client() -> Result { .timeout(HTTP_TIMEOUT) .redirect(reqwest::redirect::Policy::none()) .build() - .map_err(|e| format!("Failed to build HTTP client: {e}")) + .map_err(|e| tf("oauth_http_client_failed", &[("error", &e.to_string())])) +} + +/// A sign-in URL that does not parse; the built-in ones always do, a saved one may not. +fn invalid_url(url: &str, err: impl std::fmt::Display) -> String { + tf( + "oauth_invalid_url", + &[("url", url), ("error", &err.to_string())], + ) } /// Sends an oauth2 request through `client`, the app's reqwest client with TLS. @@ -652,14 +685,12 @@ fn parse_callback(request: &str, expected_state: &str) -> Callback { if let Some(error) = params.get("error") { let description = params .get("error_description") - .map_or("Unknown error", String::as_str); + .map_or(t("oauth_unknown_error"), String::as_str); return Callback::Answer(Err(format!("{error}: {description}"))); } match params.get("code") { Some(code) => Callback::Answer(Ok(code.clone())), - None => Callback::Answer(Err( - "The sign-in callback has no authorization code".to_string() - )), + None => Callback::Answer(Err(t("oauth_no_authorization_code").to_string())), } } @@ -810,10 +841,13 @@ mod tests { #[test] fn device_poll_stops_when_the_code_expired_or_was_denied() { let expired = poll(200, r#"{"error":"expired_token"}"#); - assert!(matches!(expired, DevicePoll::Done(OAuthResult::Error(e)) if e == CODE_EXPIRED)); + assert!( + matches!(expired, DevicePoll::Done(OAuthResult::Error(e)) if e == t("oauth_code_expired")) + ); let denied = poll(200, r#"{"error":"access_denied"}"#); - assert!(matches!(denied, DevicePoll::Done(OAuthResult::Error(e)) if e.contains("denied"))); + let denied_on = tf("oauth_denied", &[("provider", "GitHub")]); + assert!(matches!(denied, DevicePoll::Done(OAuthResult::Error(e)) if e == denied_on)); let other = poll(200, r#"{"error":"device_flow_disabled"}"#); assert!(matches!( @@ -935,6 +969,7 @@ mod tests { host: "test.com".to_string(), client_id: None, token_url: None, + login: None, }; assert!(token.is_expired()); // Less than 5 minutes = expired @@ -992,6 +1027,7 @@ mod tests { host: "gitlab.com".to_string(), client_id: Some("client".to_string()), token_url: Some(format!("http://127.0.0.1:{port}/oauth/token")), + login: None, }; assert!(token.is_expired()); let refreshed = token.refresh().expect("refresh"); @@ -1016,6 +1052,6 @@ mod tests { .unwrap(); assert_eq!(token.client_id, None); let err = token.refresh().expect_err("no client ID"); - assert!(err.contains("sign in again"), "{err}"); + assert_eq!(err, tf("oauth_no_client_id", &[("provider", "GitLab")])); } } diff --git a/src/config.rs b/src/config.rs index 9da30ad..ab609a9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,13 +2,16 @@ use std::fs; use std::io::{self, ErrorKind, Write}; use std::path::{Path, PathBuf}; +use colony_ui::i18n::Locale; +use colony_ui::preferences::StandardPreferences; use serde::de::DeserializeOwned; use serde::{Deserialize, Deserializer, Serialize}; +use serde_json::Value; use tracing::{error, warn}; -const MAX_RECENT: usize = 15; +use crate::i18n::{t, tf}; + const CONFIG_FILE_NAME: &str = "config.json"; -const APP_CONFIG_DIR: &str = "gitspace"; pub const MIN_LOG_RETENTION_FILES: usize = 1; pub const MAX_LOG_RETENTION_FILES: usize = 30; /// Auto-fetch interval bounds, in minutes. Zero would make `iced::time::every` panic, and the @@ -19,7 +22,7 @@ const MAX_AUTO_FETCH_INTERVAL_MINUTES: u64 = 24 * 60; #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct AppConfig { #[serde(default)] - recent_repos: Vec, + repos: Vec, #[serde(default)] preferences: Preferences, #[serde(default)] @@ -30,20 +33,29 @@ pub struct AppConfig { keep_file_on_disk: bool, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -pub struct RecentRepo { +/// A repository in the list: opened or cloned by the user, or found in the clone folder. +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct RepoEntry { pub path: String, + #[serde(default)] + pub pinned: bool, + /// Seconds since the Unix epoch; `None` for a found repository never opened. + #[serde(default)] + pub last_opened: Option, + /// Found by the clone-folder scan rather than opened by the user. + #[serde(default)] + pub discovered: bool, + /// A found repository the user removed: kept so the next scan does not add it back. + #[serde(default)] + pub hidden: bool, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] -pub enum ThemeMode { - #[serde(alias = "Light")] - Latte, - Frappe, - Macchiato, - #[serde(alias = "Dark")] +pub enum Language { #[default] - Mocha, + System, + English, + French, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] @@ -66,15 +78,17 @@ pub struct LoggingOptions { retention_files: usize, } -/// Label shown in the theme pick list. -impl std::fmt::Display for ThemeMode { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(match self { - ThemeMode::Latte => "Latte", - ThemeMode::Frappe => "Frappe", - ThemeMode::Macchiato => "Macchiato", - ThemeMode::Mocha => "Mocha", - }) +impl Language { + pub fn locale(self) -> Locale { + match self { + Language::English => Locale::En, + Language::French => Locale::Fr, + // LC_ALL overrides LANG; neither set (as on Windows) means English. + Language::System => ["LC_ALL", "LANG"] + .iter() + .find_map(|name| std::env::var(name).ok().filter(|tag| !tag.is_empty())) + .map_or(Locale::En, |tag| Locale::from_tag(&tag)), + } } } @@ -100,8 +114,15 @@ impl Default for LoggingOptions { #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct Preferences { + /// Appearance and accessibility, stored flat next to GitSpace's own keys. + #[serde(flatten)] + pub standard: StandardPreferences, #[serde(default, deserialize_with = "default_on_error")] - theme: ThemeMode, + language: Language, + #[serde(default = "default_true")] + reopen_last_repo: bool, + #[serde(default = "default_true")] + scan_clone_folder: bool, #[serde(default = "default_clone_path")] default_clone_path: String, #[serde(default)] @@ -119,7 +140,10 @@ pub struct Preferences { impl Default for Preferences { fn default() -> Self { Self { - theme: ThemeMode::Mocha, + standard: StandardPreferences::default(), + language: Language::default(), + reopen_last_repo: true, + scan_clone_folder: true, default_clone_path: default_clone_path(), network: NetworkOptions::default(), allow_encrypted_tokens: false, @@ -135,9 +159,10 @@ impl AppConfig { Self::load_from(&config_path()) } - /// Reads the config without ever losing it. An invalid theme value falls back to its - /// default on its own. A file that still cannot be parsed is copied to - /// `config.json.bak` before the defaults are used, so the next save cannot destroy it. + /// Reads the config without ever losing it. Values written by older builds are carried + /// over, and an invalid language value falls back to its default on its own. A file that + /// still cannot be parsed is copied to `config.json.bak` before the defaults are used, so + /// the next save cannot destroy it. fn load_from(path: &Path) -> Self { let bytes = match fs::read(path) { Ok(bytes) => bytes, @@ -155,9 +180,15 @@ impl AppConfig { }; } }; - let parse_error = match serde_json::from_slice(&bytes) { - Ok(config) => return config, - Err(err) => err, + let (parse_error, value) = match serde_json::from_slice::(&bytes) { + Ok(mut value) => { + migrate_legacy(&mut value, chrono::Utc::now().timestamp()); + match Self::deserialize(&value) { + Ok(config) => return config, + Err(err) => (err, Some(value)), + } + } + Err(err) => (err, None), }; // Keep the unreadable file before anything can overwrite it. If even that fails, never // save over it. @@ -171,10 +202,7 @@ impl AppConfig { backup_error = ?backup_result.as_ref().err(), "failed to parse config; keeping the values that are valid" ); - let config = serde_json::from_slice::(&bytes) - .ok() - .and_then(|value| lenient(&value)) - .unwrap_or_default(); + let config = value.and_then(|value| lenient(&value)).unwrap_or_default(); Self { keep_file_on_disk: backup_result.is_err(), ..config @@ -196,27 +224,73 @@ impl AppConfig { write_atomic(path, &content) } - pub fn touch_recent>(&mut self, path: P) -> bool { - let normalized = path.as_ref().to_string_lossy().to_string(); - if self - .recent_repos - .first() - .map(|entry| entry.path == normalized) - .unwrap_or(false) - { + /// Every listed repository, the last opened first, hidden ones included. + pub fn repos(&self) -> &[RepoEntry] { + &self.repos + } + + /// Records that `path` was opened at `now` (Unix seconds): adds it if needed, moves it to + /// the front and shows it again if it was hidden. Returns whether anything changed. + pub fn open_repo(&mut self, path: &str, now: i64) -> bool { + let index = self.repos.iter().position(|entry| entry.path == path); + if index == Some(0) && self.repos[0].last_opened == Some(now) && !self.repos[0].hidden { return false; } + let mut entry = index.map_or_else( + || RepoEntry { + path: path.to_string(), + ..RepoEntry::default() + }, + |index| self.repos.remove(index), + ); + entry.last_opened = Some(now); + entry.hidden = false; + self.repos.insert(0, entry); + true + } - self.recent_repos.retain(|entry| entry.path != normalized); - self.recent_repos.insert(0, RecentRepo { path: normalized }); - if self.recent_repos.len() > MAX_RECENT { - self.recent_repos.truncate(MAX_RECENT); + pub fn set_pinned(&mut self, path: &str, pinned: bool) { + if let Some(entry) = self.repos.iter_mut().find(|entry| entry.path == path) { + entry.pinned = pinned; } - true } - pub fn recent_repos(&self) -> &[RecentRepo] { - &self.recent_repos + /// Removes `path` from the list. A found repository is only hidden, so the next scan of + /// the clone folder does not add it back. + pub fn hide_repo(&mut self, path: &str) { + let Some(index) = self.repos.iter().position(|entry| entry.path == path) else { + return; + }; + if self.repos[index].discovered { + self.repos[index].hidden = true; + } else { + self.repos.remove(index); + } + } + + /// Adds the repositories a scan found that are not listed yet, hidden ones included. + /// Returns whether any was added. + pub fn merge_discovered(&mut self, paths: &[String]) -> bool { + let before = self.repos.len(); + for path in paths { + if !self.repos.iter().any(|entry| &entry.path == path) { + self.repos.push(RepoEntry { + path: path.clone(), + discovered: true, + ..RepoEntry::default() + }); + } + } + self.repos.len() != before + } + + /// The visible repository opened most recently; on a tie, the one nearer the front. + pub fn last_repo(&self) -> Option<&RepoEntry> { + self.repos + .iter() + .rev() + .filter(|entry| !entry.hidden && entry.last_opened.is_some()) + .max_by_key(|entry| entry.last_opened) } pub fn preferences(&self) -> &Preferences { @@ -236,9 +310,55 @@ impl AppConfig { } } +/// Rewrites what older builds saved into today's fields: the Catppuccin `theme` and the +/// capped `recent_repos` list, whose order becomes last-opened times counting back from `now`. +fn migrate_legacy(config: &mut Value, now: i64) { + if let Some(preferences) = config.get_mut("preferences") { + migrate_legacy_preferences(preferences); + } + let Some(config) = config.as_object_mut() else { + return; + }; + let Some(recent) = config.remove("recent_repos") else { + return; + }; + if config.contains_key("repos") { + return; + } + let repos = recent + .as_array() + .into_iter() + .flatten() + .filter_map(|entry| entry.get("path")?.as_str()) + .zip(0..) + .map(|(path, age)| serde_json::json!({ "path": path, "last_opened": now - age })) + .collect(); + config.insert("repos".to_string(), Value::Array(repos)); +} + +fn migrate_legacy_preferences(preferences: &mut Value) { + let Some(preferences) = preferences.as_object_mut() else { + return; + }; + let Some(theme) = preferences.remove("theme") else { + return; + }; + if preferences.contains_key("selected_theme") { + return; + } + let variant = match theme.as_str() { + Some("Latte" | "Light") => "latte", + Some("Frappe") => "frappe", + Some("Macchiato") => "macchiato", + Some("Mocha" | "Dark") => "mocha", + _ => return, + }; + preferences.insert("selected_theme".to_string(), "catppuccin".into()); + preferences.insert("selected_variant".to_string(), variant.into()); +} + fn config_path() -> PathBuf { - let base = dirs::config_dir().unwrap_or_else(|| PathBuf::from(".")); - base.join(APP_CONFIG_DIR).join(CONFIG_FILE_NAME) + crate::paths::effective_dirs().0.join(CONFIG_FILE_NAME) } fn backup_path(path: &Path) -> PathBuf { @@ -377,6 +497,10 @@ fn default_clone_path() -> String { .to_string() } +fn default_true() -> bool { + true +} + fn default_network_timeout() -> u64 { 30 } @@ -409,12 +533,30 @@ fn clamp_auto_fetch_interval(minutes: u64) -> u64 { } impl Preferences { - pub fn theme_mode(&self) -> ThemeMode { - self.theme + pub fn language(&self) -> Language { + self.language + } + + pub fn set_language(&mut self, language: Language) { + self.language = language; + } + + /// Whether the last opened repository is opened again at startup. + pub fn reopen_last_repo(&self) -> bool { + self.reopen_last_repo + } + + pub fn set_reopen_last_repo(&mut self, reopen: bool) { + self.reopen_last_repo = reopen; + } + + /// Whether the default clone folder is searched for repositories to list. + pub fn scan_clone_folder(&self) -> bool { + self.scan_clone_folder } - pub fn set_theme_mode(&mut self, mode: ThemeMode) { - self.theme = mode; + pub fn set_scan_clone_folder(&mut self, scan: bool) { + self.scan_clone_folder = scan; } pub fn default_clone_path(&self) -> &str { @@ -494,11 +636,16 @@ impl Preferences { pub fn from_path>(path: P) -> std::io::Result { let invalid = |message: String| io::Error::new(ErrorKind::InvalidData, message); let contents = fs::read_to_string(path)?; - let mut value: serde_json::Value = serde_json::from_str(&contents) - .map_err(|err| invalid(format!("Failed to parse preferences: {err}")))?; - if let Some(preferences) = value.get_mut("preferences").map(serde_json::Value::take) { + let mut value: serde_json::Value = serde_json::from_str(&contents).map_err(|err| { + invalid(tf( + "preferences_parse_failed", + &[("error", &err.to_string())], + )) + })?; + if let Some(preferences) = value.get_mut("preferences").map(Value::take) { value = preferences; } + migrate_legacy_preferences(&mut value); let known = serde_json::to_value(Self::default()).map_err(io::Error::other)?; let has_preferences = match (&value, &known) { (serde_json::Value::Object(fields), serde_json::Value::Object(known)) => { @@ -507,12 +654,14 @@ impl Preferences { _ => false, }; if !has_preferences { - return Err(invalid( - "The file does not contain GitSpace preferences".to_string(), - )); + return Err(invalid(t("preferences_not_found").to_string())); } - serde_json::from_value(value) - .map_err(|err| invalid(format!("Failed to parse preferences: {err}"))) + serde_json::from_value(value).map_err(|err| { + invalid(tf( + "preferences_parse_failed", + &[("error", &err.to_string())], + )) + }) } } @@ -533,6 +682,148 @@ impl LoggingOptions { mod tests { use super::*; + #[test] + fn legacy_config_keeps_every_value() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join(CONFIG_FILE_NAME); + fs::write( + &path, + r#"{ + "preferences": { + "theme": "Latte", + "default_clone_path": "/x", + "pinned_branches": ["main"], + "network": {"http_proxy": "http://p:1"}, + "auto_fetch_interval_minutes": 15 + }, + "recent_repos": [{"path": "/a"}, {"path": "/b"}] + }"#, + ) + .expect("write config"); + + let config = AppConfig::load_from(&path); + let preferences = config.preferences(); + assert_eq!(preferences.standard.selected_theme, "catppuccin"); + assert_eq!(preferences.standard.selected_variant, "latte"); + assert_eq!(preferences.default_clone_path(), "/x"); + assert_eq!(preferences.pinned_branches(), ["main"]); + assert_eq!(preferences.network().http_proxy, "http://p:1"); + assert_eq!(preferences.auto_fetch_interval_minutes(), 15); + let repos = config.repos(); + let paths: Vec<_> = repos.iter().map(|repo| repo.path.as_str()).collect(); + assert_eq!(paths, ["/a", "/b"]); + assert!(repos[0].last_opened > repos[1].last_opened); + assert!(repos.iter().all(|repo| !repo.pinned && !repo.discovered)); + assert_eq!( + config.last_repo().map(|repo| repo.path.as_str()), + Some("/a") + ); + assert!(!backup_path(&path).exists()); + } + + #[test] + fn open_repo_bumps_and_unhides() { + let mut config = AppConfig::default(); + assert!(config.open_repo("/a", 10)); + assert!(config.open_repo("/b", 20)); + assert_eq!( + config.last_repo().map(|repo| repo.path.as_str()), + Some("/b") + ); + assert!(config.open_repo("/a", 30)); + assert_eq!(config.repos().len(), 2); + assert_eq!(config.repos()[0].path, "/a"); + assert_eq!(config.repos()[0].last_opened, Some(30)); + assert_eq!( + config.last_repo().map(|repo| repo.path.as_str()), + Some("/a") + ); + assert!(!config.open_repo("/a", 30), "nothing changed"); + + config.merge_discovered(&["/c".to_string()]); + config.set_pinned("/c", true); + config.hide_repo("/c"); + assert!(config + .repos() + .iter() + .any(|repo| repo.path == "/c" && repo.hidden)); + assert!(config.open_repo("/c", 40)); + let entry = &config.repos()[0]; + assert_eq!(entry.path, "/c"); + assert!(!entry.hidden && entry.pinned && entry.discovered); + assert_eq!(entry.last_opened, Some(40)); + } + + #[test] + fn hide_repo_hides_discovered_and_removes_opened() { + let mut config = AppConfig::default(); + config.open_repo("/opened", 10); + config.merge_discovered(&["/found".to_string()]); + config.hide_repo("/opened"); + config.hide_repo("/found"); + config.hide_repo("/unknown"); + + let repos = config.repos(); + assert_eq!(repos.len(), 1); + assert_eq!(repos[0].path, "/found"); + assert!(repos[0].hidden && repos[0].discovered); + assert!(config.last_repo().is_none()); + } + + #[test] + fn merge_discovered_skips_known_and_hidden() { + let mut config = AppConfig::default(); + config.open_repo("/opened", 10); + assert!(config.merge_discovered(&["/hidden".to_string()])); + config.hide_repo("/hidden"); + + let found = ["/opened", "/hidden", "/new"].map(String::from); + assert!(config.merge_discovered(&found)); + assert!(!config.merge_discovered(&found), "second scan adds nothing"); + let repos = config.repos(); + assert_eq!(repos.len(), 3); + let opened = repos.iter().find(|repo| repo.path == "/opened").unwrap(); + assert!(!opened.discovered); + let hidden = repos.iter().find(|repo| repo.path == "/hidden").unwrap(); + assert!(hidden.hidden); + let new = repos.iter().find(|repo| repo.path == "/new").unwrap(); + assert!(new.discovered && !new.hidden && new.last_opened.is_none()); + } + + #[test] + fn round_trip_writes_standard_preferences_flat() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join(CONFIG_FILE_NAME); + fs::write( + &path, + r#"{"preferences": {"theme": "Frappe"}, "recent_repos": [{"path": "/a"}]}"#, + ) + .expect("write config"); + let mut config = AppConfig::load_from(&path); + let mut preferences = config.preferences().clone(); + preferences.standard.dyslexia_font = true; + config.set_preferences(preferences); + config.save_to(&path).expect("save"); + + let saved: serde_json::Value = + serde_json::from_slice(&fs::read(&path).expect("read")).expect("json"); + let saved_preferences = &saved["preferences"]; + assert_eq!(saved_preferences["selected_theme"], "catppuccin"); + assert_eq!(saved_preferences["selected_variant"], "frappe"); + assert_eq!(saved_preferences["dyslexia_font"], true); + assert_eq!(saved_preferences["language"], "System"); + assert_eq!(saved_preferences["reopen_last_repo"], true); + assert_eq!(saved_preferences["scan_clone_folder"], true); + assert!(saved_preferences.get("theme").is_none()); + assert!(saved_preferences.get("standard").is_none()); + assert!(saved.get("recent_repos").is_none()); + assert_eq!(saved["repos"][0]["path"], "/a"); + + let reloaded = AppConfig::load_from(&path); + assert_eq!(reloaded.preferences(), config.preferences()); + assert_eq!(reloaded.repos(), config.repos()); + } + #[test] fn invalid_values_and_removed_settings_keep_the_rest_of_the_config() { let dir = tempfile::tempdir().expect("tempdir"); @@ -553,9 +844,9 @@ mod tests { .expect("write config"); let config = AppConfig::load_from(&path); - assert_eq!(config.recent_repos()[0].path, "/work/repo"); + assert_eq!(config.repos()[0].path, "/work/repo"); let preferences = config.preferences(); - assert_eq!(preferences.theme_mode(), ThemeMode::Mocha); + assert_eq!(preferences.standard, StandardPreferences::default()); assert_eq!(preferences.pinned_branches(), ["main"]); assert_eq!(config.logging().retention_files(), 12); assert!(!backup_path(&path).exists()); @@ -591,7 +882,8 @@ mod tests { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("exports").join("preferences.json"); let mut preferences = Preferences::default(); - preferences.set_theme_mode(ThemeMode::Latte); + preferences.standard.selected_theme = "catppuccin".to_string(); + preferences.standard.selected_variant = "latte".to_string(); preferences.set_pinned_branches(vec!["main".to_string()]); preferences.save_to_path(&path).expect("export"); assert_eq!(Preferences::from_path(&path).expect("import"), preferences); @@ -617,6 +909,9 @@ mod tests { let err = Preferences::from_path(&path).expect_err(contents); assert_eq!(err.kind(), ErrorKind::InvalidData, "{contents}"); } + fs::write(&path, r#"{"unrelated": true}"#).expect("write"); + let err = Preferences::from_path(&path).expect_err("no preferences"); + assert_eq!(err.to_string(), t("preferences_not_found")); } #[test] @@ -627,16 +922,16 @@ mod tests { fs::write(&path, corrupt).expect("write config"); let mut config = AppConfig::load_from(&path); - assert!(config.recent_repos().is_empty()); + assert!(config.repos().is_empty()); let backup = backup_path(&path); assert_eq!(backup.file_name().unwrap(), "config.json.bak"); assert_eq!(fs::read_to_string(&backup).expect("read backup"), corrupt); - config.touch_recent("/work/other"); + config.open_repo("/work/other", 1); config.save_to(&path).expect("save"); assert_eq!(fs::read_to_string(&backup).expect("read backup"), corrupt); let reloaded = AppConfig::load_from(&path); - assert_eq!(reloaded.recent_repos()[0].path, "/work/other"); + assert_eq!(reloaded.repos()[0].path, "/work/other"); } #[test] @@ -657,7 +952,7 @@ mod tests { .expect("write"); let config = AppConfig::load_from(&path); - assert_eq!(config.recent_repos().len(), 1); + assert_eq!(config.repos().len(), 1); assert!(config.preferences().allow_encrypted_tokens()); assert_eq!( config.preferences().auto_fetch_interval_minutes(), @@ -683,12 +978,12 @@ mod tests { let dir = tempfile::tempdir().expect("tempdir"); let path = dir.path().join("nested").join(CONFIG_FILE_NAME); let mut config = AppConfig::default(); - config.touch_recent("/work/repo"); + config.open_repo("/work/repo", 1); config.save_to(&path).expect("first save"); - config.touch_recent("/work/other"); + config.open_repo("/work/other", 2); config.save_to(&path).expect("second save"); - assert_eq!(AppConfig::load_from(&path).recent_repos().len(), 2); + assert_eq!(AppConfig::load_from(&path).repos().len(), 2); let entries: Vec<_> = fs::read_dir(path.parent().unwrap()) .expect("read dir") .map(|entry| entry.expect("entry").file_name()) @@ -707,13 +1002,13 @@ mod tests { std::os::unix::fs::symlink(&target, &link).expect("symlink"); let mut config = AppConfig::load_from(&link); - config.touch_recent("/work/repo"); + config.open_repo("/work/repo", 1); config.save_to(&link).expect("save"); assert!(fs::symlink_metadata(&link) .expect("link metadata") .file_type() .is_symlink()); - assert_eq!(AppConfig::load_from(&target).recent_repos().len(), 1); + assert_eq!(AppConfig::load_from(&target).repos().len(), 1); } } diff --git a/src/error.rs b/src/error.rs index 513cec6..b401e10 100644 --- a/src/error.rs +++ b/src/error.rs @@ -7,51 +7,49 @@ use std::path::PathBuf; use thiserror::Error; -/// Application-level error type with user-friendly messages. +use crate::i18n::{t, tf}; + +/// Application-level error type with user-friendly messages, in the interface language. The +/// detail is GitSpace's own sentence, translated where it is written, or the library's text. #[derive(Debug, Clone, Error)] pub enum AppError { /// Git operation failed. - #[error("Git operation failed: {0}")] + #[error("{}", tf("error_git_detail", &[("detail", .0.as_str())]))] Git(String), /// Network request failed. - #[error("Network request failed: {0}")] + #[error("{}", tf("error_network_detail", &[("detail", .0.as_str())]))] Network(String), /// File system operation failed. - #[error("I/O operation failed: {0}")] + #[error("{}", tf("error_io_detail", &[("detail", .0.as_str())]))] Io(String), /// Input validation failed. - #[error("Validation failed: {0}")] + #[error("{}", tf("error_validation_detail", &[("detail", .0.as_str())]))] Validation(String), /// Configuration error. - #[error("Configuration error: {0}")] + #[error("{}", tf("error_config_detail", &[("detail", .0.as_str())]))] Config(String), /// Unexpected error. - #[error("Unexpected error: {0}")] + #[error("{}", tf("error_unknown_detail", &[("detail", .0.as_str())]))] Unknown(String), } impl AppError { /// Returns a user-friendly message suitable for display. pub fn user_message(&self) -> String { - match self { - Self::Git(_) => "Git operation failed. Please check the repository status.".to_string(), - Self::Network(_) => { - "Network request failed. Check your connection or proxy settings.".to_string() - } - Self::Io(_) => { - "File system operation failed. Verify permissions and disk space.".to_string() - } - Self::Validation(_) => { - "The provided input is not valid. Please double-check and try again.".to_string() - } - Self::Config(_) => "Configuration error. Please check your settings.".to_string(), - Self::Unknown(_) => "An unexpected error occurred.".to_string(), - } + let key = match self { + Self::Git(_) => "error_git", + Self::Network(_) => "error_network", + Self::Io(_) => "error_io", + Self::Validation(_) => "error_validation", + Self::Config(_) => "error_config", + Self::Unknown(_) => "error_unknown", + }; + t(key).to_string() } /// Returns the technical detail of the error. @@ -76,11 +74,11 @@ impl From for AppError { impl From for AppError { fn from(value: reqwest::Error) -> Self { if value.is_status() { - Self::Network(format!("HTTP error: {}", value)) + Self::Network(tf("error_http_status", &[("error", &value.to_string())])) } else if value.is_timeout() { - Self::Network("The request timed out.".to_string()) + Self::Network(t("error_timed_out").to_string()) } else if value.is_connect() { - Self::Network("Failed to connect to server.".to_string()) + Self::Network(t("error_connect").to_string()) } else { Self::Network(value.to_string()) } @@ -95,7 +93,7 @@ impl From for AppError { impl From for AppError { fn from(value: serde_json::Error) -> Self { - Self::Config(format!("JSON parse error: {}", value)) + Self::Config(tf("error_json", &[("error", &value.to_string())])) } } @@ -113,8 +111,7 @@ impl From<&str> for AppError { /// Returns the application logs directory, creating it if necessary. pub fn logs_directory() -> PathBuf { - let base = dirs::data_dir().unwrap_or_else(|| PathBuf::from(".")); - let path = base.join("gitspace").join("logs"); + let path = crate::paths::effective_dirs().1.join("logs"); if let Err(err) = std::fs::create_dir_all(&path) { tracing::warn!(error = %err, "failed to create logs directory"); } @@ -136,10 +133,22 @@ mod tests { fn user_message_is_friendly() { let err = AppError::Network("connection refused".to_string()); let msg = err.user_message(); - assert!(msg.contains("Network")); + assert_eq!(msg, t("error_network")); assert!(!msg.contains("connection refused")); } + #[test] + fn messages_come_from_the_label_table() { + // The French table has the same keys (checked in i18n), so French shows French. + let err = AppError::Git("libgit2 text".to_string()); + assert_eq!(err.user_message(), t("error_git")); + assert_eq!( + err.to_string(), + tf("error_git_detail", &[("detail", "libgit2 text")]) + ); + assert_ne!(t("error_git_detail"), "error_git_detail"); + } + #[test] fn detail_returns_inner_message() { let err = AppError::Validation("email is invalid".to_string()); diff --git a/src/git/branch.rs b/src/git/branch.rs index 9f4fc99..8135f35 100644 --- a/src/git/branch.rs +++ b/src/git/branch.rs @@ -2,7 +2,7 @@ use std::path::Path; use std::process::Command; use chrono::Utc; -use git2::{build::CheckoutBuilder, BranchType, Error, Repository}; +use git2::{build::CheckoutBuilder, BranchType, Error, ErrorCode, Oid, Repository}; use crate::git::repo_cache::with_cached_repo; @@ -16,7 +16,6 @@ pub enum BranchKind { pub struct BranchEntry { pub name: String, pub kind: BranchKind, - pub is_head: bool, } pub fn list_branches>(repo_path: P) -> Result, Error> { @@ -34,7 +33,6 @@ pub fn list_branches>(repo_path: P) -> Result, E entries.push(BranchEntry { name: name.to_string(), kind, - is_head: branch.is_head(), }); } } @@ -44,6 +42,100 @@ pub fn list_branches>(repo_path: P) -> Result, E }) } +/// A branch with what the Branches tab shows next to it. +#[derive(Debug, Clone)] +pub struct BranchOverview { + pub name: String, + pub kind: BranchKind, + pub is_head: bool, + pub upstream: Option, + pub upstream_ahead: usize, + pub upstream_behind: usize, + pub ahead_of_head: usize, + pub behind_head: usize, + pub merged_into_head: bool, + pub last_commit_time: Option, +} + +/// Lists branches with their divergence from HEAD and from their upstream. +/// +/// Runs one `graph_ahead_behind` against HEAD and one `merge_base` per branch, so it belongs +/// in a background task. With an unborn HEAD the counts against HEAD stay 0 and no branch is +/// marked merged. +pub fn list_branch_overview(repo_path: &str) -> Result, Error> { + with_cached_repo(repo_path, |repo| { + let head = repo.head().ok().and_then(|head| head.target()); + let mut entries = Vec::new(); + for branch_result in repo.branches(None)? { + let (branch, branch_type) = branch_result?; + let Some(name) = branch.name()? else { + continue; + }; + let kind = match branch_type { + BranchType::Local => BranchKind::Local, + BranchType::Remote => BranchKind::Remote, + }; + let is_head = branch.is_head(); + // Symbolic refs such as origin/HEAD resolve to their target. + let tip = branch.get().peel_to_commit().ok(); + let upstream = branch.upstream().ok(); + let upstream_name = match &upstream { + Some(upstream) => upstream.name()?.map(str::to_string), + None => None, + }; + + let mut entry = BranchOverview { + name: name.to_string(), + kind, + is_head, + upstream: upstream_name, + upstream_ahead: 0, + upstream_behind: 0, + ahead_of_head: 0, + behind_head: 0, + merged_into_head: false, + last_commit_time: tip.as_ref().map(|commit| commit.time().seconds()), + }; + if let Some(tip) = tip.map(|commit| commit.id()) { + if let Some(upstream_tip) = upstream.and_then(|upstream| upstream.get().target()) { + (entry.upstream_ahead, entry.upstream_behind) = + repo.graph_ahead_behind(tip, upstream_tip)?; + } + if let Some(head) = head { + (entry.ahead_of_head, entry.behind_head) = + repo.graph_ahead_behind(tip, head)?; + // A branch with no history in common with HEAD (gh-pages) has no merge base. + entry.merged_into_head = !is_head + && match repo.merge_base(tip, head) { + Ok(base) => base == tip, + Err(error) if error.code() == ErrorCode::NotFound => false, + Err(error) => return Err(error), + }; + } + } + entries.push(entry); + } + + entries.sort_by(|a, b| (kind_order(&a.kind), &a.name).cmp(&(kind_order(&b.kind), &b.name))); + Ok(entries) + }) +} + +/// The commit HEAD points at, attached or detached; `None` before the first commit. +pub fn head_commit(repo_path: &str) -> Result, Error> { + with_cached_repo(repo_path, |repo| { + Ok(repo.head().ok().and_then(|head| head.target())) + }) +} + +/// Sets the upstream of a local branch (`origin/main`), or removes it with `None`. +pub fn set_upstream(repo_path: &str, branch: &str, upstream: Option<&str>) -> Result<(), Error> { + with_cached_repo(repo_path, |repo| { + repo.find_branch(branch, BranchType::Local)? + .set_upstream(upstream) + }) +} + pub fn create_branch>( repo_path: P, name: &str, @@ -141,7 +233,8 @@ pub fn restore_file_from_branch>( path: &str, ) -> Result<(), String> { let output = Command::new("git") - .args(["checkout", branch, "--", path]) + // Literal pathspecs: a file named `*.md` must not also restore README.md. + .args(["--literal-pathspecs", "checkout", branch, "--", path]) .current_dir(repo_path.as_ref()) .output() .map_err(|err| err.to_string())?; @@ -156,7 +249,11 @@ pub fn restore_file_from_branch>( } fn branch_sort_key(entry: &BranchEntry) -> usize { - match entry.kind { + kind_order(&entry.kind) +} + +fn kind_order(kind: &BranchKind) -> usize { + match kind { BranchKind::Local => 0, BranchKind::Remote => 1, } diff --git a/src/git/clone.rs b/src/git/clone.rs index 2bd5b8a..5c1e6b3 100644 --- a/src/git/clone.rs +++ b/src/git/clone.rs @@ -10,6 +10,7 @@ use crate::error::AppError; use crate::git::transport::{ configure_fetch_options, create_remote_callbacks, validate_transport_url, StallTimer, }; +use crate::i18n::tf; /// Request parameters for cloning a repository. #[derive(Debug, Clone)] @@ -83,8 +84,9 @@ pub fn clone_repository( .clone(&request.url, &request.destination) .map_err(|err| { if timed_out.load(Ordering::SeqCst) { - AppError::Network(format!( - "Clone stopped: no data arrived for {timeout_secs} seconds" + AppError::Network(tf( + "clone_stalled", + &[("seconds", &timeout_secs.to_string())], )) } else { AppError::from(err) diff --git a/src/git/commit.rs b/src/git/commit.rs index 7151086..8bc223c 100644 --- a/src/git/commit.rs +++ b/src/git/commit.rs @@ -1,17 +1,17 @@ use git2::{ErrorCode, Oid, Repository, RepositoryState}; +use crate::i18n::{t, tf}; + /// Commits the index on HEAD with the identity from the Git config. A first commit on an /// unborn branch has no parent. Refuses an empty message, an index that matches HEAD, and a /// merge or rebase in progress (this commit would drop the second parent). pub fn commit_index(repo_path: &str, message: &str) -> Result { if message.trim().is_empty() { - return Err(git2::Error::from_str("The commit message is empty.")); + return Err(git2::Error::from_str(t("commit_message_empty"))); } let repo = Repository::open(repo_path)?; if repo.state() != RepositoryState::Clean { - return Err(git2::Error::from_str( - "A merge, rebase or other operation is in progress; finish it with git first.", - )); + return Err(git2::Error::from_str(t("commit_operation_in_progress"))); } let tree = repo.find_tree(repo.index()?.write_tree()?)?; @@ -25,14 +25,11 @@ pub fn commit_index(repo_path: &str, message: &str) -> Result None => tree.is_empty(), }; if unchanged { - return Err(git2::Error::from_str("Nothing is staged for commit.")); + return Err(git2::Error::from_str(t("commit_nothing_staged"))); } let signature = repo.signature().map_err(|err| { - git2::Error::from_str(&format!( - "Set user.name and user.email in your Git config to commit ({})", - err.message() - )) + git2::Error::from_str(&tf("commit_identity_missing", &[("error", err.message())])) })?; let message = git2::message_prettify(message, None)?; let parents: Vec<_> = parent.iter().collect(); @@ -96,12 +93,13 @@ mod tests { assert!(commit_index(path, "nothing").is_err()); stage(&repo, "a.txt", "one"); - assert!(commit_index(path, " \n").is_err()); + let err = commit_index(path, " \n").unwrap_err(); + assert_eq!(err.message(), t("commit_message_empty")); commit_index(path, "first").unwrap(); // The index matches HEAD. let err = commit_index(path, "again").unwrap_err(); - assert!(err.message().contains("Nothing is staged")); + assert_eq!(err.message(), t("commit_nothing_staged")); let head = repo.head().unwrap().peel_to_commit().unwrap(); assert_eq!(head.message().ok(), Some("first\n")); } diff --git a/src/git/compare.rs b/src/git/compare.rs deleted file mode 100644 index 9687bce..0000000 --- a/src/git/compare.rs +++ /dev/null @@ -1,107 +0,0 @@ -use git2::{Diff, Oid, Repository}; -// Utilise le cache thread-local pour éviter de réouvrir le dépôt à chaque appel -use crate::git::repo_cache::with_cached_repo; - -#[derive(Debug, Clone)] -pub struct BranchComparison { - pub commit: Option, - pub diff: Option, -} - -#[derive(Debug, Clone)] -pub struct BranchCommit { - pub id: String, - pub summary: String, - pub author: String, -} - -#[derive(Debug, Clone)] -pub struct DiffSummary { - pub files_changed: usize, - pub additions: usize, - pub deletions: usize, -} - -pub fn compare_branch_with_head( - repo_path: &str, - branch_name: &str, -) -> Result { - // Lecture seule de la comparaison — utilise le cache thread-local - with_cached_repo(repo_path, |repo| { - let branch_commit = branch_commit(repo, branch_name)?; - let diff = match branch_commit - .as_ref() - .and_then(|commit| Oid::from_str(&commit.id).ok()) - { - Some(oid) => { - diff_summary_between(repo, Some(oid), repo.head().ok().and_then(|h| h.target()))? - } - None => None, - }; - - Ok(BranchComparison { - commit: branch_commit, - diff, - }) - }) -} - -fn branch_commit( - repo: &Repository, - branch_name: &str, -) -> Result, git2::Error> { - let reference_name = format!("refs/heads/{branch_name}"); - let commit = if let Ok(reference) = repo.find_reference(&reference_name) { - reference.peel_to_commit()? - } else { - match repo.revparse_single(branch_name) { - Ok(object) => object.peel_to_commit()?, - Err(_) => return Ok(None), - } - }; - - let id = commit.id().to_string(); - let summary = commit - .summary() - .ok() - .flatten() - .unwrap_or_default() - .to_string(); - let author = commit.author().name().unwrap_or("Unknown").to_string(); - - Ok(Some(BranchCommit { - id, - summary, - author, - })) -} - -fn diff_summary_between( - repo: &Repository, - from: Option, - to: Option, -) -> Result, git2::Error> { - if from.is_none() && to.is_none() { - return Ok(None); - } - let from_tree = match from { - Some(oid) => Some(repo.find_commit(oid)?.tree()?), - None => None, - }; - let to_tree = match to { - Some(oid) => Some(repo.find_commit(oid)?.tree()?), - None => None, - }; - - let diff = repo.diff_tree_to_tree(from_tree.as_ref(), to_tree.as_ref(), None)?; - Ok(Some(diff_summary(diff)?)) -} - -fn diff_summary(diff: Diff) -> Result { - let stats = diff.stats()?; - Ok(DiffSummary { - files_changed: stats.files_changed(), - additions: stats.insertions(), - deletions: stats.deletions(), - }) -} diff --git a/src/git/diff.rs b/src/git/diff.rs index 65c0b17..7c714e9 100644 --- a/src/git/diff.rs +++ b/src/git/diff.rs @@ -35,7 +35,7 @@ fn delta_path(delta: &DiffDelta<'_>) -> String { .unwrap_or_else(|| "(unknown)".to_string()) } -fn collect_diff_files(diff: Diff) -> Result, git2::Error> { +pub(crate) fn collect_diff_files(diff: Diff) -> Result, git2::Error> { let mut files: HashMap = HashMap::new(); diff.print(DiffFormat::Patch, |delta, _hunk, line| { @@ -95,7 +95,7 @@ fn collect_diff_files(diff: Diff) -> Result, git2::Error> { } /// Collect only diff summaries without patch content (for lazy loading) -fn collect_diff_summaries(diff: &Diff) -> Result, git2::Error> { +pub(crate) fn collect_diff_summaries(diff: &Diff) -> Result, git2::Error> { let mut summaries = Vec::with_capacity(diff.deltas().len()); for (index, delta) in diff.deltas().enumerate() { // `None` for a binary file, which has no lines to count. @@ -120,7 +120,7 @@ fn collect_diff_summaries(diff: &Diff) -> Result, git2::Err Ok(summaries) } -fn head_tree(repo: &Repository) -> Result>, git2::Error> { +pub(crate) fn head_tree(repo: &Repository) -> Result>, git2::Error> { let head = match repo.head() { Ok(head) => head, Err(_) => return Ok(None), @@ -152,7 +152,7 @@ pub(crate) fn commit_against_parent<'r>( /// Options that limit a diff to exactly `path`, without glob matching, so names such as /// `[draft].md` work. -fn single_path_options(path: &str) -> DiffOptions { +pub(crate) fn single_path_options(path: &str) -> DiffOptions { let mut options = DiffOptions::new(); options.pathspec(path).disable_pathspec_match(true); options diff --git a/src/git/discover.rs b/src/git/discover.rs new file mode 100644 index 0000000..c696fee --- /dev/null +++ b/src/git/discover.rs @@ -0,0 +1,15 @@ +use std::path::{Path, PathBuf}; + +/// Direct sub-folders of `root` that hold a `.git` directory or file, sorted by name. +/// Nested folders are not searched. An unreadable `root` gives an empty list. +pub fn discover_repositories(root: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(root) else { + return Vec::new(); + }; + let mut found: Vec = entries + .filter_map(|entry| entry.ok().map(|entry| entry.path())) + .filter(|path| path.is_dir() && path.join(".git").exists()) + .collect(); + found.sort_by(|a, b| a.file_name().cmp(&b.file_name())); + found +} diff --git a/src/git/log.rs b/src/git/log.rs index b6b78d0..10f97c8 100644 --- a/src/git/log.rs +++ b/src/git/log.rs @@ -1,4 +1,6 @@ -use git2::{BranchType, ErrorCode, Repository, Time}; +use std::collections::HashMap; + +use git2::{BranchType, ErrorCode, Oid, Repository, Time}; use crate::git::diff::commit_against_parent; // Utilise le cache thread-local pour éviter de réouvrir le dépôt à chaque appel @@ -16,7 +18,7 @@ pub struct CommitFilter { #[derive(Debug, Clone)] pub struct CommitInfo { pub id: String, - /// Pre-computed short ID (first 8 chars) to avoid repeated string slicing in UI + /// The first 7 characters of the ID, as `git log --oneline` shows them. pub short_id: String, pub summary: String, pub message: String, @@ -26,6 +28,25 @@ pub struct CommitInfo { pub files_changed: Option, pub additions: Option, pub deletions: Option, + /// More than one parent marks a merge commit. + pub parent_count: usize, + /// Branches and tags pointing at this commit; filled by `read_commit_log` only. + pub refs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RefLabel { + pub name: String, + pub kind: RefKind, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum RefKind { + Local, + Remote, + Tag, + /// The checked-out branch, or `HEAD` itself when detached. + Head, } pub fn list_local_branches(repo_path: &str) -> Result, git2::Error> { @@ -73,6 +94,8 @@ pub fn read_commit_log( revwalk.push_head()?; } + let mut ref_map = build_ref_map(repo)?; + // `limit` counts matching commits, so filters may walk further back. let mut commits = Vec::with_capacity(limit.min(256)); for oid_result in revwalk { @@ -85,6 +108,8 @@ pub fn read_commit_log( } let mut info = commit_info_from_commit(&commit); + // Each commit comes out of the walk once, so its labels can be moved out. + info.refs = ref_map.remove(&commit.id()).unwrap_or_default(); if include_stats { let stats = commit_against_parent(repo, commit.id(), None)?.stats()?; info.files_changed = Some(stats.files_changed()); @@ -98,6 +123,59 @@ pub fn read_commit_log( }) } +/// Maps every commit some branch, remote branch or tag points at to its labels. +fn build_ref_map(repo: &Repository) -> Result>, git2::Error> { + let head = repo.head().ok(); + let current_branch = head + .as_ref() + .filter(|head| head.is_branch()) + .and_then(|head| head.name().ok().map(str::to_string)); + + let mut map: HashMap> = HashMap::new(); + for reference in repo.references()? { + let reference = reference?; + // `refs/remotes/origin/HEAD` only repeats another remote branch. + if reference.kind() == Some(git2::ReferenceType::Symbolic) { + continue; + } + let kind = if reference.is_branch() { + if reference.name().ok() == current_branch.as_deref() { + RefKind::Head + } else { + RefKind::Local + } + } else if reference.is_remote() { + RefKind::Remote + } else if reference.is_tag() { + RefKind::Tag + } else { + continue; + }; + let (Ok(name), Ok(commit)) = (reference.shorthand(), reference.peel_to_commit()) else { + continue; + }; + map.entry(commit.id()).or_default().push(RefLabel { + name: name.to_string(), + kind, + }); + } + + if let Some(oid) = head + .filter(|head| !head.is_branch()) + .and_then(|head| head.target()) + { + map.entry(oid).or_default().push(RefLabel { + name: "HEAD".to_string(), + kind: RefKind::Head, + }); + } + + for labels in map.values_mut() { + labels.sort_by(|a, b| (a.kind, &a.name).cmp(&(b.kind, &b.name))); + } + Ok(map) +} + fn matches_filter(commit: &git2::Commit<'_>, filter: &CommitFilter) -> bool { if let Some(author_filter) = &filter.author { let author_text = format!( @@ -111,16 +189,19 @@ fn matches_filter(commit: &git2::Commit<'_>, filter: &CommitFilter) -> bool { } } + // The History filter field: message, author name or email, or the start of the hash. if let Some(search) = &filter.search { let search_lower = search.to_lowercase(); - let message = commit.message().unwrap_or_default().to_lowercase(); - let summary = commit - .summary() - .ok() - .flatten() - .unwrap_or_default() - .to_lowercase(); - if !message.contains(&search_lower) && !summary.contains(&search_lower) { + let author = commit.author(); + let haystack = format!( + "{}\n{}\n{}", + commit.message().unwrap_or_default(), + author.name().unwrap_or_default(), + author.email().unwrap_or_default() + ) + .to_lowercase(); + if !haystack.contains(&search_lower) && !commit.id().to_string().starts_with(&search_lower) + { return false; } } @@ -130,21 +211,6 @@ fn matches_filter(commit: &git2::Commit<'_>, filter: &CommitFilter) -> bool { && filter.until.is_none_or(|until| timestamp <= until) } -pub fn latest_commit_for_branch( - repo_path: &str, - branch_name: &str, -) -> Result, git2::Error> { - // Récupération du dernier commit d'une branche via le cache - with_cached_repo(repo_path, |repo| { - let oid = resolve_branch_oid(repo, branch_name)?; - let Some(oid) = oid else { - return Ok(None); - }; - let commit = repo.find_commit(oid)?; - Ok(Some(commit_info_from_commit(&commit))) - }) -} - pub fn commits_between_refs( repo_path: &str, from_ref: &str, @@ -208,7 +274,7 @@ fn resolve_ref_oid(repo: &Repository, reference: &str) -> Result) -> CommitInfo { let id = commit.id().to_string(); - let short_id = id.chars().take(8).collect(); + let short_id = id.chars().take(7).collect(); CommitInfo { id, short_id, @@ -225,5 +291,7 @@ fn commit_info_from_commit(commit: &git2::Commit<'_>) -> CommitInfo { files_changed: None, additions: None, deletions: None, + parent_count: commit.parent_count(), + refs: Vec::new(), } } diff --git a/src/git/merge.rs b/src/git/merge.rs index 961db39..5f14979 100644 --- a/src/git/merge.rs +++ b/src/git/merge.rs @@ -6,6 +6,7 @@ use std::time::Duration; // Utilise le cache thread-local pour les opérations en lecture seule use crate::git::repo_cache::with_cached_repo; +use crate::i18n::tf; /// Default timeout for git operations (5 minutes). const GIT_OPERATION_TIMEOUT: Duration = Duration::from_secs(300); @@ -18,7 +19,6 @@ pub enum MergeStrategy { #[derive(Debug, Clone)] pub struct MergeOutcome { - pub message: String, pub had_conflicts: bool, pub conflicts: Vec, } @@ -46,25 +46,7 @@ pub fn merge_branch>( return Err(message); } - let message = if output.status.success() { - format!( - "{} completed", - match strategy { - MergeStrategy::Merge => "Merge", - MergeStrategy::Rebase => "Rebase", - } - ) - } else { - let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); - if stderr.is_empty() { - "Operation completed with conflicts".to_string() - } else { - stderr - } - }; - Ok(MergeOutcome { - message, had_conflicts: !conflicts.is_empty(), conflicts, }) @@ -111,7 +93,12 @@ fn run_git_command_with_timeout( .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() - .map_err(|err| format!("Failed to start git {command}: {err}"))?; + .map_err(|err| { + tf( + "git_start_failed", + &[("command", command), ("error", &err.to_string())], + ) + })?; // Drain both pipes while git runs: a full pipe buffer would block it forever. let stdout = child.stdout.take().map(drain); @@ -138,16 +125,22 @@ fn run_git_command_with_timeout( // Kill the process let _ = child.kill(); let _ = child.wait(); - return Err(format!( - "Git {command} timed out after {} seconds", - timeout.as_secs() + return Err(tf( + "git_timed_out", + &[ + ("command", command), + ("seconds", &timeout.as_secs().to_string()), + ], )); } // Sleep briefly before checking again std::thread::sleep(Duration::from_millis(100)); } Err(err) => { - return Err(format!("Failed to wait for git {command}: {err}")); + return Err(tf( + "git_wait_failed", + &[("command", command), ("error", &err.to_string())], + )); } } } diff --git a/src/git/mod.rs b/src/git/mod.rs index 0a1a43b..46f5261 100644 --- a/src/git/mod.rs +++ b/src/git/mod.rs @@ -1,8 +1,8 @@ pub mod branch; pub mod clone; pub mod commit; -pub mod compare; pub mod diff; +pub mod discover; pub mod log; pub mod merge; pub mod remote; diff --git a/src/git/remote.rs b/src/git/remote.rs index 5c84bc0..27207ca 100644 --- a/src/git/remote.rs +++ b/src/git/remote.rs @@ -13,6 +13,7 @@ use crate::git::transport::{ configure_fetch_options, configure_push_options, create_push_callbacks, create_remote_callbacks, validate_transport_url, }; +use crate::i18n::{t, tf}; /// Information about a configured remote. #[derive(Debug, Clone)] @@ -113,8 +114,9 @@ pub fn pull_branch>( let repo = Repository::open(path)?; let local_ref_name = format!("refs/heads/{local_branch}"); if repo.find_reference("HEAD")?.symbolic_target()? != Some(local_ref_name.as_str()) { - return Err(AppError::Git(format!( - "Pull only updates the checked-out branch, and {local_branch} is not checked out." + return Err(AppError::Git(tf( + "remote_pull_not_checked_out", + &[("branch", local_branch)], ))); } @@ -132,9 +134,7 @@ pub fn pull_branch>( return Ok(PullOutcome::FastForward); } - Err(AppError::Git( - "Non-fast-forward pull required. Please merge or rebase manually.".to_string(), - )) + Err(AppError::Git(t("remote_pull_diverged").to_string())) } /// Pushes a local branch to a branch on a remote. @@ -157,8 +157,9 @@ pub fn push_branch>( let repo = Repository::open(path)?; let local_ref_name = format!("refs/heads/{local_branch}"); if repo.find_reference("HEAD")?.symbolic_target()? != Some(local_ref_name.as_str()) { - return Err(AppError::Git(format!( - "Push only sends the checked-out branch, and {local_branch} is not checked out." + return Err(AppError::Git(tf( + "remote_push_not_checked_out", + &[("branch", local_branch)], ))); } let mut remote = repo.find_remote(remote_name)?; diff --git a/src/git/stash.rs b/src/git/stash.rs index 5792ad6..d77b78a 100644 --- a/src/git/stash.rs +++ b/src/git/stash.rs @@ -1,4 +1,10 @@ -use git2::{Repository, Signature, StashApplyOptions}; +use git2::{Diff, DiffOptions, Oid, Repository, Signature, StashApplyOptions, StatusOptions}; + +use crate::git::diff::{ + collect_diff_files, collect_diff_summaries, commit_against_parent, single_path_options, + FileDiff, FileDiffSummary, +}; +use crate::i18n::t; #[derive(Debug, Clone)] pub struct StashEntry { @@ -6,22 +12,99 @@ pub struct StashEntry { pub message: String, /// The stash commit id, used to check that `index` still points to this stash. pub id: String, + /// The branch the stash was made on; `None` for a detached HEAD. + pub branch: Option, + /// Commit time of the stash, in seconds since the Unix epoch. + pub time: i64, + /// Files the stash changes against the commit it was made on, untracked files included. + pub file_count: usize, } pub fn list_stashes(repo_path: &str) -> Result, git2::Error> { let mut repo = Repository::open(repo_path)?; - let mut entries = Vec::new(); - + let mut found = Vec::new(); repo.stash_foreach(|index, name, oid| { - entries.push(StashEntry { - index, - message: name.to_string(), - id: oid.to_string(), - }); + found.push((index, name.to_string(), *oid)); true })?; - Ok(entries) + found + .into_iter() + .map(|(index, message, oid)| { + let file_count = stash_diff(&repo, oid, None)?.deltas().len(); + Ok(StashEntry { + index, + branch: stash_branch(&message), + time: repo.find_commit(oid)?.time().seconds(), + file_count, + message, + id: oid.to_string(), + }) + }) + .collect() +} + +/// The branch in git's `WIP on : ...` or `On : ...` stash message. Branch +/// names cannot contain `:`, so the first one ends the name. +fn stash_branch(message: &str) -> Option { + let rest = message + .strip_prefix("WIP on ") + .or_else(|| message.strip_prefix("On "))?; + let (branch, _) = rest.split_once(':')?; + (branch != "(no branch)").then(|| branch.to_string()) +} + +/// The stash `oid` against the commit it was made on. "Include untracked files" keeps the +/// untracked files in the stash's third parent, so they are added as new files. +fn stash_diff<'r>( + repo: &'r Repository, + oid: Oid, + mut options: Option<&mut DiffOptions>, +) -> Result, git2::Error> { + let mut diff = commit_against_parent(repo, oid, options.as_deref_mut())?; + if let Ok(untracked) = repo.find_commit(oid)?.parent(2) { + diff.merge(&repo.diff_tree_to_tree(None, Some(&untracked.tree()?), options)?)?; + } + Ok(diff) +} + +/// Files of the stash at `index` against the commit it was made on, if it is still the +/// stash `id`. +pub fn stash_files( + repo_path: &str, + index: usize, + id: &str, +) -> Result, git2::Error> { + let mut repo = Repository::open(repo_path)?; + ensure_stash_id(&mut repo, index, id)?; + let diff = stash_diff(&repo, Oid::from_str(id)?, None)?; + collect_diff_summaries(&diff) +} + +/// The patch of `path` in the stash at `index`, if it is still the stash `id`. +pub fn stash_file_patch( + repo_path: &str, + index: usize, + id: &str, + path: &str, +) -> Result, git2::Error> { + let mut repo = Repository::open(repo_path)?; + ensure_stash_id(&mut repo, index, id)?; + let mut options = single_path_options(path); + let diff = stash_diff(&repo, Oid::from_str(id)?, Some(&mut options))?; + Ok(collect_diff_files(diff)?.into_iter().next()) +} + +/// How many files a stash made now would take; ignored files never count. +pub fn count_stashable(repo_path: &str, include_untracked: bool) -> Result { + let repo = Repository::open(repo_path)?; + let mut options = StatusOptions::new(); + options + .include_untracked(include_untracked) + .recurse_untracked_dirs(include_untracked) + .include_ignored(false); + let count = repo.statuses(Some(&mut options))?.len(); + Ok(count) } pub fn create_stash( @@ -38,16 +121,21 @@ pub fn create_stash( flags |= git2::StashFlags::INCLUDE_UNTRACKED; } - repo.stash_save2(&signature, Some(message), Some(flags))?; + // With no message, git writes its own "WIP on : " one. + let message = (!message.is_empty()).then_some(message); + repo.stash_save2(&signature, message, Some(flags))?; Ok(()) } -/// Applies the stash at `index`, if it is still the stash `id`. libgit2's default safe -/// checkout fails instead of overwriting a modified file. -pub fn apply_stash(repo_path: &str, index: usize, id: &str) -> Result<(), git2::Error> { +/// Applies the stash at `index`, if it is still the stash `id`, and returns whether the +/// apply left conflicts. libgit2's default safe checkout fails instead of overwriting a +/// modified file, but a conflicting change is applied with markers and still succeeds. +pub fn apply_stash(repo_path: &str, index: usize, id: &str) -> Result { let mut repo = Repository::open(repo_path)?; ensure_stash_id(&mut repo, index, id)?; - repo.stash_apply(index, Some(&mut StashApplyOptions::new())) + repo.stash_apply(index, Some(&mut StashApplyOptions::new()))?; + let conflicts = repo.index()?.has_conflicts(); + Ok(conflicts) } /// Drops the stash at `index`, if it is still the stash `id`. @@ -65,9 +153,23 @@ fn ensure_stash_id(repo: &mut Repository, index: usize, id: &str) -> Result<(), true })?; if !matches { - return Err(git2::Error::from_str( - "The stash list changed; refresh and try again.", - )); + return Err(git2::Error::from_str(t("stash_list_changed"))); } Ok(()) } + +#[cfg(test)] +mod tests { + use super::stash_branch; + + #[test] + fn stash_branch_reads_both_message_forms() { + assert_eq!(stash_branch("On main: msg").as_deref(), Some("main")); + assert_eq!( + stash_branch("WIP on feature/x: 1a2b3c4 summary").as_deref(), + Some("feature/x") + ); + assert_eq!(stash_branch("WIP on (no branch): 1a2b3c4 summary"), None); + assert_eq!(stash_branch("custom message"), None); + } +} diff --git a/src/git/status.rs b/src/git/status.rs index e12b492..3d490fa 100644 --- a/src/git/status.rs +++ b/src/git/status.rs @@ -1,6 +1,13 @@ -use std::path::Path; +use std::path::{Component, Path}; -use git2::{BranchType, ErrorCode}; +use git2::build::CheckoutBuilder; +use git2::{ + BranchType, Delta, Diff, DiffFindOptions, DiffOptions, ErrorCode, Patch, Repository, Status, + StatusOptions, +}; + +use crate::git::diff::head_tree; +use crate::i18n::t; // Utilise le cache thread-local pour éviter de réouvrir le dépôt à chaque appel use crate::git::repo_cache::with_cached_repo; @@ -10,61 +17,257 @@ pub struct RepoStatus { pub upstream: Option, pub ahead: Option, pub behind: Option, + /// Short hash of the commit HEAD points at when no branch is checked out. + pub detached_at: Option, } pub fn read_repo_status>(path: P) -> Result { // Lecture seule du statut — utilise le cache thread-local - with_cached_repo(path, |repo| { - let head = match repo.head() { - Ok(head) => head, - // A fresh `git init`: HEAD names a branch with no commit yet. - Err(err) if err.code() == ErrorCode::UnbornBranch => { - let head = repo.find_reference("HEAD")?; - let branch = head - .symbolic_target()? - .map(|target| target.strip_prefix("refs/heads/").unwrap_or(target)); - return Ok(RepoStatus { - branch: branch.map(str::to_string), - ..RepoStatus::default() - }); - } - Err(err) => return Err(err), - }; + with_cached_repo(path, repo_status) +} - if !head.is_branch() { +fn repo_status(repo: &Repository) -> Result { + let head = match repo.head() { + Ok(head) => head, + // A fresh `git init`: HEAD names a branch with no commit yet. + Err(err) if err.code() == ErrorCode::UnbornBranch => { + let head = repo.find_reference("HEAD")?; + let branch = head + .symbolic_target()? + .map(|target| target.strip_prefix("refs/heads/").unwrap_or(target)); return Ok(RepoStatus { - branch: None, - upstream: None, - ahead: None, - behind: None, + branch: branch.map(str::to_string), + ..RepoStatus::default() }); } + Err(err) => return Err(err), + }; - let branch_name = head.shorthand().ok().map(|name| name.to_string()); - let mut status = RepoStatus { - branch: branch_name.clone(), - upstream: None, - ahead: None, - behind: None, - }; + if !head.is_branch() { + return Ok(RepoStatus { + detached_at: head + .target() + .map(|oid| oid.to_string().chars().take(7).collect()), + ..RepoStatus::default() + }); + } - if let Some(name) = branch_name { - let branch = repo.find_branch(&name, BranchType::Local)?; + let branch_name = head.shorthand().ok().map(|name| name.to_string()); + let mut status = RepoStatus { + branch: branch_name.clone(), + ..RepoStatus::default() + }; - if let Ok(upstream) = branch.upstream() { - status.upstream = upstream.name()?.map(|name| name.to_string()); + if let Some(name) = branch_name { + let branch = repo.find_branch(&name, BranchType::Local)?; - if let (Some(local_oid), Some(upstream_oid)) = - (branch.get().target(), upstream.get().target()) - { - if let Ok((ahead, behind)) = repo.graph_ahead_behind(local_oid, upstream_oid) { - status.ahead = Some(ahead); - status.behind = Some(behind); - } + if let Ok(upstream) = branch.upstream() { + status.upstream = upstream.name()?.map(|name| name.to_string()); + + if let (Some(local_oid), Some(upstream_oid)) = + (branch.get().target(), upstream.get().target()) + { + if let Ok((ahead, behind)) = repo.graph_ahead_behind(local_oid, upstream_oid) { + status.ahead = Some(ahead); + status.behind = Some(behind); } } } + } + + Ok(status) +} + +/// The cheap status shown next to a repository in the sidebar. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct QuickStatus { + pub branch: Option, + pub ahead: usize, + pub behind: usize, + /// Changed and untracked entries; an untracked folder counts once. + pub changed: usize, + /// The folder is gone or no longer opens as a repository. + pub missing: bool, +} + +/// Branch, divergence from upstream and changed-entry count, without building patches. +/// Never fails: a path that does not open as a repository is reported as `missing`. +pub fn quick_status(path: &str) -> QuickStatus { + // Opened fresh, not cached: a cached handle would outlive a deleted folder, and a scan + // of many repositories would only churn the small cache. + let Ok(repo) = Repository::open(path) else { + return QuickStatus { + missing: true, + ..QuickStatus::default() + }; + }; + let status = repo_status(&repo).unwrap_or_default(); + let mut options = StatusOptions::new(); + options + .include_untracked(true) + .recurse_untracked_dirs(false) + .include_ignored(false); + let changed = repo + .statuses(Some(&mut options)) + .map(|statuses| statuses.len()) + .unwrap_or(0); + QuickStatus { + branch: status.branch, + ahead: status.ahead.unwrap_or(0), + behind: status.behind.unwrap_or(0), + changed, + missing: false, + } +} + +/// Untracked files above this size are listed without counting their lines. +const MAX_UNTRACKED_COUNT_SIZE: u64 = 1024 * 1024; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChangeKind { + Added, + Modified, + Deleted, + Renamed, + Untracked, + Conflicted, + TypeChange, +} + +#[derive(Debug, Clone)] +pub struct ChangedFile { + pub path: String, + /// The previous path of a renamed file. + pub old_path: Option, + pub kind: ChangeKind, + pub additions: usize, + pub deletions: usize, + #[cfg_attr(not(test), expect(dead_code, reason = "no screen shows it yet"))] + pub binary: bool, +} + +#[derive(Debug, Clone, Default)] +pub struct Changes { + pub staged: Vec, + pub unstaged: Vec, +} + +/// Staged (HEAD to index) and unstaged (index to work tree, with untracked files) changes, +/// with line counts per file. No patch text is kept. +pub fn read_changes(repo_path: &str) -> Result { + with_cached_repo(repo_path, |repo| { + let mut index = repo.index()?; + index.read(true)?; + + let base_tree = head_tree(repo)?; + let mut staged = repo.diff_tree_to_index(base_tree.as_ref(), Some(&index), None)?; + staged.find_similar(Some(DiffFindOptions::new().renames(true)))?; + + let mut options = DiffOptions::new(); + options + .include_untracked(true) + .recurse_untracked_dirs(true) + .show_untracked_content(true); + let unstaged = repo.diff_index_to_workdir(Some(&index), Some(&mut options))?; + let workdir = repo.workdir(); + + Ok(Changes { + staged: changed_files(&staged, None)?, + unstaged: changed_files(&unstaged, workdir)?, + }) + }) +} + +/// One entry per delta. `workdir` is set for the work tree diff, to size untracked files. +fn changed_files(diff: &Diff<'_>, workdir: Option<&Path>) -> Result, git2::Error> { + let mut files = Vec::with_capacity(diff.deltas().len()); + for (index, delta) in diff.deltas().enumerate() { + let kind = match delta.status() { + Delta::Added | Delta::Copied => ChangeKind::Added, + Delta::Modified | Delta::Unreadable => ChangeKind::Modified, + Delta::Deleted => ChangeKind::Deleted, + Delta::Renamed => ChangeKind::Renamed, + Delta::Untracked => ChangeKind::Untracked, + Delta::Conflicted => ChangeKind::Conflicted, + Delta::Typechange => ChangeKind::TypeChange, + Delta::Unmodified | Delta::Ignored => continue, + }; + let path_of = + |file: git2::DiffFile<'_>| file.path().map(|path| path.to_string_lossy().into_owned()); + let path = path_of(delta.new_file()) + .or_else(|| path_of(delta.old_file())) + .unwrap_or_default(); + let old_path = (kind == ChangeKind::Renamed) + .then(|| path_of(delta.old_file())) + .flatten(); - Ok(status) + let too_large = kind == ChangeKind::Untracked + && workdir + .and_then(|root| std::fs::metadata(root.join(&path)).ok()) + .is_some_and(|meta| meta.len() > MAX_UNTRACKED_COUNT_SIZE); + // Conflicted and unreadable entries have no single content to compare. + let counted = + !too_large && !matches!(delta.status(), Delta::Conflicted | Delta::Unreadable); + let patch = if counted { + // A file that cannot be read (no permission, say) is listed without counts. + Patch::from_diff(diff, index).ok().flatten() + } else { + None + }; + let (additions, deletions) = match &patch { + Some(patch) => { + let (_context, additions, deletions) = patch.line_stats()?; + (additions, deletions) + } + None => (0, 0), + }; + let binary = delta.flags().is_binary() + || patch + .as_ref() + .is_some_and(|patch| patch.delta().flags().is_binary()); + + files.push(ChangedFile { + path, + old_path, + kind, + additions, + deletions, + binary, + }); + } + Ok(files) +} + +/// Throws away the work tree changes of one file: a tracked file goes back to its index +/// version, an untracked file is removed. `path` is relative to the work tree. +pub fn discard_file(repo_path: &str, path: &str) -> Result<(), git2::Error> { + let relative = Path::new(path); + if path.is_empty() + || !relative + .components() + .all(|component| matches!(component, Component::Normal(_))) + { + return Err(git2::Error::from_str(t("discard_path_outside_repository"))); + } + + with_cached_repo(repo_path, |repo| { + let workdir = repo + .workdir() + .ok_or_else(|| git2::Error::from_str(t("repo_no_work_tree")))?; + let mut index = repo.index()?; + index.read(true)?; + + if index.get_path(relative, 0).is_some() { + let mut checkout = CheckoutBuilder::new(); + checkout.force().disable_pathspec_match(true).path(path); + return repo.checkout_index(Some(&mut index), Some(&mut checkout)); + } + // Only a file git reports as untracked is removed, never an ignored or .git file. + if repo.status_file(relative)?.contains(Status::WT_NEW) { + std::fs::remove_file(workdir.join(relative)) + .map_err(|err| git2::Error::from_str(&err.to_string())) + } else { + Err(git2::Error::from_str(t("discard_no_changes"))) + } }) } diff --git a/src/git/tests.rs b/src/git/tests.rs index bbd88b3..d47b09c 100644 --- a/src/git/tests.rs +++ b/src/git/tests.rs @@ -6,13 +6,20 @@ use git2::{BranchType, Commit, Oid, Repository, RepositoryInitOptions, ResetType use crate::config::NetworkOptions; use crate::git::branch; -use crate::git::branch::{list_branches, rename_branch, BranchKind}; +use crate::git::branch::{ + list_branch_overview, list_branches, rename_branch, set_upstream, BranchKind, BranchOverview, +}; use crate::git::diff::{commit_diff_file, commit_diff_summaries, diff_file}; -use crate::git::log::{read_commit_log, CommitFilter}; +use crate::git::discover::discover_repositories; +use crate::git::log::{read_commit_log, CommitFilter, RefKind}; use crate::git::merge::detect_conflicts; use crate::git::remote::{fetch_remote, list_remotes, pull_branch, push_branch, PullOutcome}; -use crate::git::stash::{apply_stash, create_stash, drop_stash, list_stashes}; -use crate::git::status::read_repo_status; +use crate::git::stash::{ + apply_stash, count_stashable, create_stash, drop_stash, list_stashes, stash_file_patch, + stash_files, +}; +use crate::git::status::{discard_file, quick_status, read_changes, read_repo_status, ChangeKind}; +use crate::i18n::t; fn init_temp_repo() -> (tempfile::TempDir, Repository) { let temp_dir = tempfile::tempdir().expect("create temp dir"); @@ -82,6 +89,18 @@ fn repo_status_reports_tracking_progress() { assert_eq!(status.behind, Some(0)); } +#[test] +fn repo_status_names_the_commit_of_a_detached_head() { + let (_dir, repo) = init_temp_repo(); + let first = write_commit(&repo, "f.txt", "1", "first"); + write_commit(&repo, "f.txt", "2", "second"); + repo.set_head_detached(first).unwrap(); + + let status = read_repo_status(repo.path().parent().unwrap()).expect("status"); + assert_eq!(status.branch, None); + assert_eq!(status.detached_at, Some(first.to_string()[..7].to_string())); +} + #[test] fn branch_lifecycle_is_managed() { let (_dir, repo) = init_temp_repo(); @@ -374,11 +393,25 @@ fn stash_drop_refuses_a_changed_stash_list() { create_stash(path, "second", false).expect("stash"); let err = drop_stash(path, first.index, &first.id).expect_err("stale index"); - assert!(err.message().contains("refresh"), "{}", err.message()); + assert_eq!(err.message(), t("stash_list_changed")); assert_eq!(list_stashes(path).unwrap().len(), 2); assert!(apply_stash(path, first.index, &first.id).is_err()); } +#[test] +fn stash_without_a_message_gets_git_s_own() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + let path = root.to_str().unwrap(); + write_commit(&repo, "a.txt", "base", "initial"); + fs::write(root.join("a.txt"), "edited").unwrap(); + create_stash(path, "", false).expect("stash"); + + let stash = list_stashes(path).unwrap().remove(0); + assert!(stash.message.starts_with("WIP on "), "{}", stash.message); + assert!(stash.branch.is_some()); +} + #[test] fn stash_apply_keeps_edits_in_other_files() { let (_dir, repo) = init_temp_repo(); @@ -391,12 +424,34 @@ fn stash_apply_keeps_edits_in_other_files() { fs::write(root.join("b.txt"), "unsaved").unwrap(); let stash = list_stashes(path).unwrap().remove(0); - apply_stash(path, stash.index, &stash.id).expect("apply"); + let conflicts = apply_stash(path, stash.index, &stash.id).expect("apply"); + assert!(!conflicts); assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "stashed"); assert_eq!(fs::read_to_string(root.join("b.txt")).unwrap(), "unsaved"); } +#[test] +fn stash_apply_reports_conflicts() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + let path = root.to_str().unwrap(); + write_commit(&repo, "a.txt", "base", "add a"); + fs::write(root.join("a.txt"), "stashed").unwrap(); + create_stash(path, "a", false).expect("stash"); + write_commit(&repo, "a.txt", "committed", "edit a"); + + let stash = list_stashes(path).unwrap().remove(0); + let conflicts = apply_stash(path, stash.index, &stash.id).expect("apply"); + + assert!(conflicts); + assert!(Repository::open(root) + .unwrap() + .index() + .unwrap() + .has_conflicts()); +} + #[test] fn stash_uses_the_configured_signature() { let (_dir, repo) = init_temp_repo(); @@ -413,6 +468,110 @@ fn stash_uses_the_configured_signature() { assert_eq!(commit.author().email().unwrap(), "ada@example.com"); } +#[test] +fn stash_entry_has_branch_time_and_file_count() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + let path = root.to_str().unwrap(); + write_commit(&repo, "a.txt", "a", "add a"); + write_commit(&repo, "b.txt", "b", "add b"); + fs::write(root.join("a.txt"), "changed a").unwrap(); + fs::write(root.join("b.txt"), "changed b").unwrap(); + create_stash(path, "two files", false).expect("stash"); + + let stash = list_stashes(path).unwrap().remove(0); + assert_eq!(stash.branch.as_deref(), Some("main")); + assert_eq!(stash.file_count, 2); + let stash_commit = repo.find_commit(Oid::from_str(&stash.id).unwrap()).unwrap(); + assert_eq!(stash.time, stash_commit.time().seconds()); + assert!(stash.time > 0); +} + +#[test] +fn stash_files_lists_changed_paths() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + let path = root.to_str().unwrap(); + write_commit(&repo, "a.txt", "a\n", "add a"); + write_commit(&repo, "b.txt", "b\n", "add b"); + fs::write(root.join("a.txt"), "a\nmore\n").unwrap(); + create_stash(path, "one file", false).expect("stash"); + + let stash = list_stashes(path).unwrap().remove(0); + let files = stash_files(path, stash.index, &stash.id).expect("files"); + assert_eq!(files.len(), 1); + assert_eq!(files[0].path, "a.txt"); + assert_eq!((files[0].additions, files[0].deletions), (1, 0)); + + let patch = stash_file_patch(path, stash.index, &stash.id, "a.txt") + .expect("patch") + .expect("a.txt changed"); + assert!(patch.patch.contains("+more"), "{}", patch.patch); + assert!(stash_file_patch(path, stash.index, &stash.id, "b.txt") + .unwrap() + .is_none()); +} + +#[test] +fn stash_lists_the_untracked_files_it_saved() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + let path = root.to_str().unwrap(); + write_commit(&repo, "a.txt", "a\n", "add a"); + fs::write(root.join("a.txt"), "a\nmore\n").unwrap(); + fs::write(root.join("brand-new.txt"), "new\n").unwrap(); + create_stash(path, "mixed", true).expect("stash"); + assert!(!root.join("brand-new.txt").exists()); + + // git keeps the untracked file in the stash's third parent, not in the stash tree. + let stash = list_stashes(path).unwrap().remove(0); + assert_eq!(stash.file_count, 2); + let files = stash_files(path, stash.index, &stash.id).expect("files"); + let paths: Vec<&str> = files.iter().map(|file| file.path.as_str()).collect(); + assert_eq!(paths, ["a.txt", "brand-new.txt"]); + assert_eq!((files[1].additions, files[1].deletions), (1, 0)); + let patch = stash_file_patch(path, stash.index, &stash.id, "brand-new.txt") + .expect("patch") + .expect("brand-new.txt is in the stash"); + assert!(patch.patch.contains("+new"), "{}", patch.patch); +} + +#[test] +fn stash_files_refuses_a_changed_list() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + let path = root.to_str().unwrap(); + write_commit(&repo, "a.txt", "base", "initial"); + fs::write(root.join("a.txt"), "first").unwrap(); + create_stash(path, "first", false).expect("stash"); + let first = list_stashes(path).unwrap().remove(0); + fs::write(root.join("a.txt"), "second").unwrap(); + create_stash(path, "second", false).expect("stash"); + + let err = stash_files(path, first.index, &first.id).expect_err("stale index"); + assert_eq!(err.message(), t("stash_list_changed")); + assert!(stash_file_patch(path, first.index, &first.id, "a.txt").is_err()); +} + +#[test] +fn count_stashable_respects_untracked() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + let path = root.to_str().unwrap(); + write_commit(&repo, ".gitignore", "*.log\n", "ignore logs"); + write_commit(&repo, "a.txt", "a", "add a"); + assert_eq!(count_stashable(path, true).unwrap(), 0); + + fs::write(root.join("a.txt"), "changed").unwrap(); + fs::create_dir(root.join("new")).unwrap(); + fs::write(root.join("new/one.txt"), "1").unwrap(); + fs::write(root.join("new/two.txt"), "2").unwrap(); + fs::write(root.join("debug.log"), "ignored").unwrap(); + + assert_eq!(count_stashable(path, false).unwrap(), 1); + assert_eq!(count_stashable(path, true).unwrap(), 3); +} + #[test] fn checkout_refuses_to_overwrite_a_modified_file() { let (_dir, repo) = init_temp_repo(); @@ -428,6 +587,23 @@ fn checkout_refuses_to_overwrite_a_modified_file() { assert_eq!(repo.head().unwrap().shorthand().unwrap(), "main"); } +#[test] +fn restore_from_branch_takes_the_path_literally() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "a.txt", "one", "initial"); + let first = write_commit(&repo, "[a].txt", "bracket", "glob name"); + repo.branch("other", &repo.find_commit(first).unwrap(), false) + .unwrap(); + fs::write(root.join("a.txt"), "dirty").unwrap(); + fs::write(root.join("[a].txt"), "edited").unwrap(); + + // `[a].txt` is a glob that also matches `a.txt`, and a name Windows accepts. + branch::restore_file_from_branch(root, "other", "[a].txt").expect("restore"); + assert_eq!(fs::read_to_string(root.join("[a].txt")).unwrap(), "bracket"); + assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "dirty"); +} + #[test] fn commit_diff_summaries_count_lines() { let (_dir, repo) = init_temp_repo(); @@ -506,6 +682,27 @@ fn log_limit_counts_matching_commits() { assert!(commits[0].summary.contains("needle")); } +#[test] +fn log_search_matches_author_and_hash_prefix() { + let (_dir, repo) = init_temp_repo(); + let path = repo.path().parent().unwrap().to_str().unwrap().to_string(); + let first = write_commit(&repo, "f.txt", "1", "first"); + write_commit(&repo, "f.txt", "2", "second"); + let search = |text: &str| { + let filter = CommitFilter { + search: Some(text.to_string()), + ..Default::default() + }; + read_commit_log(&path, &filter, 10, false).expect("log") + }; + + assert_eq!(search("TESTER@example").len(), 2, "author email"); + let by_hash = search(&first.to_string()[..7].to_uppercase()); + assert_eq!(by_hash.len(), 1); + assert_eq!(by_hash[0].id, first.to_string()); + assert!(search("nobody").is_empty()); +} + #[test] fn log_branch_filter_accepts_remote_branches() { let (_dir, repo) = init_temp_repo(); @@ -572,3 +769,508 @@ fn conflicts_written_by_another_handle_are_detected() { assert_eq!(detect_conflicts(root).unwrap(), vec!["c.txt".to_string()]); } + +#[test] +fn read_changes_counts_lines_per_file() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "f.txt", "one\ntwo\nthree\nfour\nfive\n", "initial"); + // Three lines changed and two appended: 5 added, 3 removed. + fs::write( + root.join("f.txt"), + "ONE\nTWO\nTHREE\nfour\nfive\nsix\nseven\n", + ) + .unwrap(); + fs::write(root.join("new.txt"), "a\nb\nc\nd\n").unwrap(); + + let changes = read_changes(root.to_str().unwrap()).expect("changes"); + assert!(changes.staged.is_empty()); + let file = changes.unstaged.iter().find(|f| f.path == "f.txt").unwrap(); + assert_eq!(file.kind, ChangeKind::Modified); + assert_eq!((file.additions, file.deletions), (5, 3)); + assert!(!file.binary); + let new = changes + .unstaged + .iter() + .find(|f| f.path == "new.txt") + .unwrap(); + assert_eq!(new.kind, ChangeKind::Untracked); + assert_eq!((new.additions, new.deletions), (4, 0)); +} + +#[test] +fn read_changes_splits_staged_and_unstaged() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "b.txt", "b\n", "add b"); + write_commit(&repo, "c.txt", "same content\nfor the rename\n", "add c"); + + fs::write(root.join("a.txt"), "a\n").unwrap(); + fs::write(root.join("b.txt"), "b\nstaged\n").unwrap(); + fs::rename(root.join("c.txt"), root.join("d.txt")).unwrap(); + let mut index = repo.index().unwrap(); + index.add_path(Path::new("a.txt")).unwrap(); + index.add_path(Path::new("b.txt")).unwrap(); + index.remove_path(Path::new("c.txt")).unwrap(); + index.add_path(Path::new("d.txt")).unwrap(); + index.write().unwrap(); + fs::write(root.join("b.txt"), "b\nstaged\nunstaged\n").unwrap(); + + let changes = read_changes(root.to_str().unwrap()).expect("changes"); + let staged: Vec<_> = changes + .staged + .iter() + .map(|f| (f.path.as_str(), f.kind, f.additions, f.deletions)) + .collect(); + assert!( + staged.contains(&("a.txt", ChangeKind::Added, 1, 0)), + "{staged:?}" + ); + assert!( + staged.contains(&("b.txt", ChangeKind::Modified, 1, 0)), + "{staged:?}" + ); + let renamed = changes.staged.iter().find(|f| f.path == "d.txt").unwrap(); + assert_eq!(renamed.kind, ChangeKind::Renamed); + assert_eq!(renamed.old_path.as_deref(), Some("c.txt")); + assert_eq!(changes.staged.len(), 3); + + assert_eq!(changes.unstaged.len(), 1, "{:?}", changes.unstaged); + let unstaged = &changes.unstaged[0]; + assert_eq!( + (unstaged.path.as_str(), unstaged.kind), + ("b.txt", ChangeKind::Modified) + ); + assert_eq!((unstaged.additions, unstaged.deletions), (1, 0)); +} + +#[test] +fn read_changes_handles_two_thousand_untracked_files() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "README.md", "hello\n", "initial"); + fs::create_dir(root.join("many")).unwrap(); + for i in 0..2000 { + fs::write(root.join("many").join(format!("{i}.txt")), "line\n").unwrap(); + } + + let started = std::time::Instant::now(); + let changes = read_changes(root.to_str().unwrap()).expect("changes"); + let elapsed = started.elapsed(); + assert_eq!(changes.unstaged.len(), 2000); + assert!(changes + .unstaged + .iter() + .all(|f| f.kind == ChangeKind::Untracked && f.additions == 1)); + assert!(elapsed < std::time::Duration::from_secs(5), "{elapsed:?}"); +} + +#[test] +fn read_changes_skips_counting_large_untracked_files() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "README.md", "hello\n", "initial"); + fs::write(root.join("big.txt"), "x\n".repeat(600 * 1024)).unwrap(); + + let changes = read_changes(root.to_str().unwrap()).expect("changes"); + assert_eq!(changes.unstaged.len(), 1); + assert_eq!(changes.unstaged[0].additions, 0); +} + +#[cfg(unix)] +#[test] +fn read_changes_lists_files_it_cannot_read() { + use std::os::unix::fs::PermissionsExt; + + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "locked.txt", "one\n", "initial"); + fs::write(root.join("locked.txt"), "one\ntwo\n").unwrap(); + fs::write(root.join("secret.txt"), "hidden\n").unwrap(); + fs::write(root.join("open.txt"), "a\nb\n").unwrap(); + for name in ["locked.txt", "secret.txt"] { + fs::set_permissions(root.join(name), fs::Permissions::from_mode(0o000)).unwrap(); + } + + let changes = read_changes(root.to_str().unwrap()).expect("changes"); + for name in ["locked.txt", "secret.txt"] { + fs::set_permissions(root.join(name), fs::Permissions::from_mode(0o644)).unwrap(); + } + let paths: Vec<_> = changes.unstaged.iter().map(|f| f.path.as_str()).collect(); + assert_eq!(paths.len(), 3, "{paths:?}"); + let open = changes + .unstaged + .iter() + .find(|f| f.path == "open.txt") + .unwrap(); + assert_eq!((open.additions, open.deletions), (2, 0)); +} + +#[test] +fn discard_file_restores_a_tracked_file() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "a.txt", "original\n", "add a"); + write_commit(&repo, "b.txt", "b\n", "add b"); + fs::write(root.join("a.txt"), "edited\n").unwrap(); + fs::write(root.join("b.txt"), "kept edit\n").unwrap(); + + discard_file(root.to_str().unwrap(), "a.txt").expect("discard"); + + // A Windows checkout may turn line endings into CRLF (core.autocrlf). + assert_eq!( + fs::read_to_string(root.join("a.txt")) + .unwrap() + .replace("\r\n", "\n"), + "original\n" + ); + assert_eq!( + fs::read_to_string(root.join("b.txt")).unwrap(), + "kept edit\n" + ); +} + +#[test] +fn discard_file_removes_an_untracked_file() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "a.txt", "a\n", "add a"); + fs::write(root.join("scratch.txt"), "temp\n").unwrap(); + + discard_file(root.to_str().unwrap(), "scratch.txt").expect("discard"); + + assert!(!root.join("scratch.txt").exists()); + assert!(root.join("a.txt").exists()); +} + +#[test] +fn discard_file_refuses_a_path_outside_the_repo() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap(); + write_commit(&repo, "a.txt", "a\n", "add a"); + + let path = root.to_str().unwrap(); + let err = discard_file(path, "../x").expect_err("outside"); + assert_eq!(err.message(), t("discard_path_outside_repository")); + assert!(discard_file(path, "/etc/hostname").is_err()); + assert!(discard_file(path, ".git/config").is_err()); + assert!(root.join(".git/config").exists()); +} + +/// Commits `contents` to `path` on top of `parent` and points `refs/heads/` at it, +/// without touching HEAD or the working tree. +fn commit_on_branch(repo: &Repository, branch: &str, parent: Option, message: &str) -> Oid { + let blob = repo.blob(message.as_bytes()).expect("blob"); + let mut builder = repo.treebuilder(None).expect("tree builder"); + builder + .insert(format!("{branch}.txt"), blob, 0o100644) + .expect("insert"); + let tree = repo + .find_tree(builder.write().expect("tree")) + .expect("find tree"); + let sig = Signature::now("Tester", "tester@example.com").expect("signature"); + let parents: Vec = parent + .map(|id| repo.find_commit(id).unwrap()) + .into_iter() + .collect(); + let parent_refs: Vec<&Commit> = parents.iter().collect(); + let refname = format!("refs/heads/{branch}"); + repo.commit(Some(&refname), &sig, &sig, message, &tree, &parent_refs) + .expect("commit") +} + +fn overview_of<'a>(list: &'a [BranchOverview], name: &str) -> &'a BranchOverview { + list.iter() + .find(|entry| entry.name == name) + .unwrap_or_else(|| panic!("{name} missing from overview")) +} + +#[test] +fn overview_counts_ahead_and_behind_head() { + let (_dir, repo) = init_temp_repo(); + let base = write_commit(&repo, "file.txt", "base", "base"); + let feature = commit_on_branch(&repo, "feature", Some(base), "feature one"); + commit_on_branch(&repo, "feature", Some(feature), "feature two"); + write_commit(&repo, "file.txt", "main", "main moves on"); + let root = repo.path().parent().unwrap().to_str().unwrap(); + + let list = list_branch_overview(root).expect("overview"); + let main = overview_of(&list, "main"); + assert!(main.is_head); + assert_eq!((main.ahead_of_head, main.behind_head), (0, 0)); + let feature = overview_of(&list, "feature"); + assert!(!feature.is_head); + assert_eq!(feature.kind, BranchKind::Local); + assert_eq!((feature.ahead_of_head, feature.behind_head), (2, 1)); + assert!(!feature.merged_into_head); + assert!(feature.last_commit_time.is_some()); +} + +#[test] +fn overview_marks_merged_branches() { + let (_dir, repo) = init_temp_repo(); + let base = write_commit(&repo, "file.txt", "base", "base"); + repo.branch("done", &repo.find_commit(base).unwrap(), false) + .expect("branch"); + write_commit(&repo, "file.txt", "later", "later"); + commit_on_branch(&repo, "open", Some(base), "not merged"); + let root = repo.path().parent().unwrap().to_str().unwrap(); + + let list = list_branch_overview(root).expect("overview"); + let done = overview_of(&list, "done"); + assert!(done.merged_into_head); + assert_eq!((done.ahead_of_head, done.behind_head), (0, 1)); + assert!(!overview_of(&list, "open").merged_into_head); + assert!(!overview_of(&list, "main").merged_into_head); +} + +#[test] +fn overview_lists_a_branch_without_shared_history() { + let (_dir, repo) = init_temp_repo(); + write_commit(&repo, "file.txt", "base", "base"); + write_commit(&repo, "file.txt", "next", "next"); + let orphan = commit_on_branch(&repo, "orphan", None, "orphan one"); + commit_on_branch(&repo, "orphan", Some(orphan), "orphan two"); + let root = repo.path().parent().unwrap().to_str().unwrap(); + + let list = list_branch_overview(root).expect("overview"); + let orphan = overview_of(&list, "orphan"); + assert!(!orphan.merged_into_head); + assert_eq!((orphan.ahead_of_head, orphan.behind_head), (2, 2)); +} + +#[test] +fn overview_reports_upstream_divergence() { + let (_dir, repo) = init_temp_repo(); + let first = write_commit(&repo, "file.txt", "one", "one"); + let second = write_commit(&repo, "file.txt", "two", "two"); + ensure_remote_tracking(&repo, "main", "origin/main", first); + let remote_only = repo.find_commit(first).unwrap(); + let sig = Signature::now("Tester", "tester@example.com").unwrap(); + let remote_tip = repo + .commit( + Some("refs/remotes/origin/main"), + &sig, + &sig, + "remote", + &remote_only.tree().unwrap(), + &[&remote_only], + ) + .expect("remote commit"); + assert_ne!(remote_tip, second); + let root = repo.path().parent().unwrap().to_str().unwrap(); + + let list = list_branch_overview(root).expect("overview"); + let main = overview_of(&list, "main"); + assert_eq!(main.upstream.as_deref(), Some("origin/main")); + assert_eq!((main.upstream_ahead, main.upstream_behind), (1, 1)); + let remote = overview_of(&list, "origin/main"); + assert_eq!(remote.kind, BranchKind::Remote); + assert!(remote.upstream.is_none()); + assert_eq!((remote.ahead_of_head, remote.behind_head), (1, 1)); +} + +#[test] +fn overview_on_unborn_head_is_empty_counts() { + let (_dir, repo) = init_temp_repo(); + let other = commit_on_branch(&repo, "other", None, "first"); + commit_on_branch(&repo, "other", Some(other), "second"); + assert!(repo.head().is_err()); + let root = repo.path().parent().unwrap().to_str().unwrap(); + + let list = list_branch_overview(root).expect("overview"); + let other = overview_of(&list, "other"); + assert!(!other.is_head); + assert_eq!((other.ahead_of_head, other.behind_head), (0, 0)); + assert_eq!((other.upstream_ahead, other.upstream_behind), (0, 0)); + assert!(!other.merged_into_head); + assert!(other.last_commit_time.is_some()); +} + +#[test] +fn set_upstream_sets_and_clears() { + let (_dir, repo) = init_temp_repo(); + let first = write_commit(&repo, "file.txt", "one", "one"); + repo.remote("origin", "https://example.com/remote.git") + .expect("remote"); + repo.reference("refs/remotes/origin/main", first, true, "remote ref") + .expect("remote ref"); + let root = repo.path().parent().unwrap().to_str().unwrap(); + + set_upstream(root, "main", Some("origin/main")).expect("set"); + let main = repo.find_branch("main", BranchType::Local).unwrap(); + assert_eq!( + main.upstream().unwrap().name().unwrap(), + Some("origin/main") + ); + assert_eq!( + overview_of(&list_branch_overview(root).unwrap(), "main") + .upstream + .as_deref(), + Some("origin/main") + ); + + set_upstream(root, "main", None).expect("clear"); + assert!(repo + .find_branch("main", BranchType::Local) + .unwrap() + .upstream() + .is_err()); + assert!(set_upstream(root, "missing", None).is_err()); +} + +#[test] +fn log_reports_merge_commits_with_two_parents() { + let (_dir, repo) = init_temp_repo(); + let path = repo.path().parent().unwrap().to_str().unwrap().to_string(); + let base = write_commit(&repo, "file.txt", "base", "base"); + let side = commit_on_branch(&repo, "side", Some(base), "side"); + let main_tip = write_commit(&repo, "file.txt", "main", "main"); + + let sig = Signature::now("Tester", "tester@example.com").expect("signature"); + let tree = repo.find_commit(main_tip).unwrap().tree().unwrap(); + let parents = [ + &repo.find_commit(main_tip).unwrap(), + &repo.find_commit(side).unwrap(), + ]; + let merge = repo + .commit(Some("HEAD"), &sig, &sig, "merge side", &tree, &parents) + .expect("merge commit"); + + let commits = read_commit_log(&path, &CommitFilter::default(), 10, false).expect("log"); + let count_of = |oid: Oid| { + commits + .iter() + .find(|commit| commit.id == oid.to_string()) + .map(|commit| commit.parent_count) + }; + assert_eq!(count_of(merge), Some(2)); + assert_eq!(count_of(main_tip), Some(1)); + assert_eq!(count_of(base), Some(0)); +} + +#[test] +fn log_labels_branches_remotes_and_tags() { + let (_dir, repo) = init_temp_repo(); + let path = repo.path().parent().unwrap().to_str().unwrap().to_string(); + let first = write_commit(&repo, "f.txt", "1", "first"); + let second = write_commit(&repo, "f.txt", "2", "second"); + let sig = Signature::now("Tester", "tester@example.com").expect("signature"); + let target = repo.find_object(first, None).unwrap(); + repo.tag("v1", &target, &sig, "release", false) + .expect("annotated tag"); + repo.reference("refs/remotes/origin/main", first, true, "test") + .unwrap(); + repo.branch("feature", &repo.find_commit(second).unwrap(), false) + .unwrap(); + + let commits = read_commit_log(&path, &CommitFilter::default(), 10, false).expect("log"); + let labels_of = |oid: Oid| { + let commit = commits + .iter() + .find(|commit| commit.id == oid.to_string()) + .expect("commit in log"); + commit + .refs + .iter() + .map(|label| (label.name.clone(), label.kind)) + .collect::>() + }; + + let first_labels = labels_of(first); + assert_eq!(first_labels.len(), 2, "{first_labels:?}"); + assert!(first_labels.contains(&("v1".to_string(), RefKind::Tag))); + assert!(first_labels.contains(&("origin/main".to_string(), RefKind::Remote))); + + let second_labels = labels_of(second); + assert!(second_labels.contains(&("main".to_string(), RefKind::Head))); + assert!(second_labels.contains(&("feature".to_string(), RefKind::Local))); +} + +#[test] +fn log_labels_a_detached_head() { + let (_dir, repo) = init_temp_repo(); + let path = repo.path().parent().unwrap().to_str().unwrap().to_string(); + let first = write_commit(&repo, "f.txt", "1", "first"); + write_commit(&repo, "f.txt", "2", "second"); + repo.set_head_detached(first).unwrap(); + + let commits = read_commit_log(&path, &CommitFilter::default(), 10, false).expect("log"); + let labels = &commits + .iter() + .find(|commit| commit.id == first.to_string()) + .expect("detached commit in log") + .refs; + assert_eq!(labels.len(), 1, "{labels:?}"); + assert_eq!(labels[0].name, "HEAD"); + assert_eq!(labels[0].kind, RefKind::Head); +} + +#[test] +fn discovers_direct_children_with_a_git_dir() { + let root = tempfile::tempdir().expect("root"); + Repository::init(root.path().join("zeta")).expect("init zeta"); + Repository::init(root.path().join("alpha")).expect("init alpha"); + // A linked worktree or submodule has a `.git` file instead of a directory. + fs::create_dir(root.path().join("linked")).unwrap(); + fs::write(root.path().join("linked/.git"), "gitdir: ../elsewhere").unwrap(); + + let found = discover_repositories(root.path()); + let names: Vec<_> = found + .iter() + .map(|path| path.file_name().unwrap().to_str().unwrap()) + .collect(); + assert_eq!(names, ["alpha", "linked", "zeta"]); + assert!(found.iter().all(|path| path.parent() == Some(root.path()))); +} + +#[test] +fn discovery_skips_nested_and_plain_folders() { + let root = tempfile::tempdir().expect("root"); + fs::create_dir_all(root.path().join("group/inner")).unwrap(); + Repository::init(root.path().join("group/inner")).expect("init nested"); + fs::create_dir(root.path().join("plain")).unwrap(); + fs::write(root.path().join("file.txt"), "not a folder").unwrap(); + + assert!(discover_repositories(root.path()).is_empty()); + assert!(discover_repositories(&root.path().join("does-not-exist")).is_empty()); +} + +#[test] +fn quick_status_counts_changes_and_divergence() { + let (_dir, repo) = init_temp_repo(); + let root = repo.path().parent().unwrap().to_str().unwrap().to_string(); + let first = write_commit(&repo, "a.txt", "one", "first"); + ensure_remote_tracking(&repo, "main", "origin/main", first); + write_commit(&repo, "a.txt", "two", "second"); + fs::write(repo.path().parent().unwrap().join("a.txt"), "edited").unwrap(); + fs::write(repo.path().parent().unwrap().join("new.txt"), "new").unwrap(); + // An untracked folder counts once, however many files it holds. + fs::create_dir(repo.path().parent().unwrap().join("build")).unwrap(); + for name in ["x", "y", "z"] { + fs::write(repo.path().parent().unwrap().join("build").join(name), name).unwrap(); + } + + let status = quick_status(&root); + assert!(!status.missing); + assert_eq!(status.branch.as_deref(), Some("main")); + assert_eq!((status.ahead, status.behind), (1, 0)); + assert_eq!(status.changed, 3); +} + +#[test] +fn quick_status_of_a_deleted_folder_is_missing() { + let (dir, repo) = init_temp_repo(); + write_commit(&repo, "a.txt", "one", "first"); + let root = dir.path().to_str().unwrap().to_string(); + assert!(!quick_status(&root).missing); + drop(repo); + drop(dir); + + let status = quick_status(&root); + assert!(status.missing); + assert_eq!(status.branch, None); + assert_eq!(status.changed, 0); + let plain = tempfile::tempdir().unwrap(); + assert!(quick_status(plain.path().to_str().unwrap()).missing); +} diff --git a/src/git/transport.rs b/src/git/transport.rs index 7226318..8fc3283 100644 --- a/src/git/transport.rs +++ b/src/git/transport.rs @@ -15,27 +15,22 @@ use git2::{ use crate::config::NetworkOptions; use crate::error::AppError; +use crate::i18n::t; /// Validates that a URL conforms to the network policy (SSH/HTTPS/HTTP settings). pub fn validate_transport_url(url: &str, network: &NetworkOptions) -> Result<(), AppError> { let url_lower = url.to_lowercase(); if is_ssh_url(&url_lower) && !network.allow_ssh { - return Err(AppError::Validation( - "SSH access is disabled in your network preferences.".to_string(), - )); + return Err(AppError::Validation(t("network_ssh_blocked").to_string())); } if url_lower.starts_with("https://") && !network.use_https { - return Err(AppError::Validation( - "HTTPS connections are disabled in your network preferences.".to_string(), - )); + return Err(AppError::Validation(t("network_https_blocked").to_string())); } if url_lower.starts_with("http://") && network.use_https { - return Err(AppError::Validation( - "Plain HTTP is blocked. Enable HTTP in settings or use HTTPS.".to_string(), - )); + return Err(AppError::Validation(t("network_http_blocked").to_string())); } Ok(()) @@ -134,14 +129,10 @@ fn token_credentials( ) -> Result { let url = url.to_ascii_lowercase(); if url.starts_with("http://") { - return Err(git2::Error::from_str( - "This remote uses plain HTTP: GitSpace never sends a token over it. Use an https:// remote URL.", - )); + return Err(git2::Error::from_str(t("token_remote_plain_http"))); } if !url.starts_with("https://") { - return Err(git2::Error::from_str( - "GitSpace sends a saved token only to https:// remotes.", - )); + return Err(git2::Error::from_str(t("token_https_remotes_only"))); } Cred::userpass_plaintext(username_from_url.unwrap_or("git"), token) } @@ -230,21 +221,16 @@ impl CredentialPicker { return Cred::default(); } - Err(git2::Error::from_str(&self.failure_message(url))) + Err(git2::Error::from_str(self.failure_message(url))) } - fn failure_message(&self, url: &str) -> String { + fn failure_message(&self, url: &str) -> &'static str { if is_ssh_url(url) { - "SSH authentication failed: neither ssh-agent nor a key in ~/.ssh (id_ed25519, \ - id_ecdsa, id_rsa) was accepted. Add your key to ssh-agent, or use an https:// \ - remote with a saved token." - .to_string() + t("auth_ssh_failed") } else if self.sent_token { - "The remote refused the saved token. Check that it is still valid and can access \ - this repository." - .to_string() + t("auth_token_refused") } else { - "This remote needs authentication: save a token for its host in GitSpace.".to_string() + t("auth_token_needed") } } } @@ -406,7 +392,8 @@ mod tests { "github.com:user/repo.git", "git://github.com/repo.git", ] { - assert!(token_credentials(url, None, "secret").is_err(), "{url}"); + let err = token_credentials(url, None, "secret").err().expect(url); + assert_eq!(err.message(), t("token_https_remotes_only")); let mut picker = CredentialPicker::new(Some("secret".into()), Vec::new()); assert!(picker .next(url, None, CredentialType::USER_PASS_PLAINTEXT) @@ -427,7 +414,8 @@ mod tests { #[test] fn token_is_never_offered_over_plain_http() { - assert!(token_credentials("http://git.example.com/repo.git", None, "secret").is_err()); + let err = token_credentials("http://git.example.com/repo.git", None, "secret").err(); + assert_eq!(err.unwrap().message(), t("token_remote_plain_http")); assert!(token_credentials("HTTP://git.example.com/repo.git", None, "secret").is_err()); assert!(token_credentials("https://git.example.com/repo.git", None, "secret").is_ok()); @@ -468,7 +456,7 @@ mod tests { } // The token is never sent as an SSH password, so every method is used up. let err = picker.next(url, Some("git"), ssh).err().expect("a refusal"); - assert!(err.message().contains("ssh-agent"), "{}", err.message()); + assert_eq!(err.message(), t("auth_ssh_failed")); assert!(picker.next(url, Some("git"), ssh).is_err()); } @@ -483,11 +471,7 @@ mod tests { CredentialType::USER_PASS_PLAINTEXT ); let err = picker.next(url, None, allowed).err().expect("a refusal"); - assert!( - err.message().contains("refused the saved token"), - "{}", - err.message() - ); + assert_eq!(err.message(), t("auth_token_refused")); } #[test] @@ -504,7 +488,7 @@ mod tests { CredentialType::DEFAULT ); let err = picker.next(url, None, allowed).err().expect("a refusal"); - assert!(err.message().contains("save a token"), "{}", err.message()); + assert_eq!(err.message(), t("auth_token_needed")); } #[test] diff --git a/src/i18n.rs b/src/i18n.rs new file mode 100644 index 0000000..4a22466 --- /dev/null +++ b/src/i18n.rs @@ -0,0 +1,157 @@ +//! GitSpace's own labels in English and French. +//! +//! Kit labels (theme names, accents) come from `colony_ui::i18n`; this table +//! holds GitSpace's vocabulary. The active locale is the one set with +//! `colony_ui::i18n::set_locale`, so both tables switch together. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Mutex, OnceLock}; + +use colony_ui::i18n::Locale; + +const EN: &str = include_str!("i18n/en.json"); +const FR: &str = include_str!("i18n/fr.json"); + +/// Looks up a label in the active locale; falls back to English, then to the key. +pub fn t(key: &str) -> &'static str { + lookup(colony_ui::i18n::locale(), key) +} + +/// Looks up a label and replaces each `{name}` placeholder with its value. +pub fn tf(key: &str, args: &[(&str, &str)]) -> String { + fill(t(key), args) +} + +fn fill(label: &str, args: &[(&str, &str)]) -> String { + args.iter().fold(label.to_owned(), |out, (name, value)| { + out.replace(&format!("{{{name}}}"), value) + }) +} + +fn table(locale: Locale) -> &'static HashMap { + static EN_TABLE: OnceLock> = OnceLock::new(); + static FR_TABLE: OnceLock> = OnceLock::new(); + let (cell, source) = match locale { + Locale::En => (&EN_TABLE, EN), + Locale::Fr => (&FR_TABLE, FR), + }; + // Both files are embedded and parsed by the tests below, so this cannot fail in a tested build. + cell.get_or_init(|| serde_json::from_str(source).expect("embedded label table is valid JSON")) +} + +fn lookup(locale: Locale, key: &str) -> &'static str { + table(locale) + .get(key) + .or_else(|| table(Locale::En).get(key)) + .map(String::as_str) + .unwrap_or_else(|| intern(key)) +} + +/// Shows an unknown key as itself. Interned so a view redrawn every frame leaks it only once. +fn intern(key: &str) -> &'static str { + static UNKNOWN: OnceLock>> = OnceLock::new(); + let mut unknown = UNKNOWN.get_or_init(Default::default).lock().unwrap(); + if let Some(found) = unknown.get(key) { + return found; + } + let leaked: &'static str = Box::leak(key.into()); + unknown.insert(leaked); + leaked +} + +#[cfg(test)] +mod tests { + use super::*; + + fn placeholders(label: &str) -> HashSet<&str> { + label + .split('{') + .skip(1) + .filter_map(|rest| rest.split_once('}').map(|(name, _)| name)) + .collect() + } + + #[test] + fn en_and_fr_have_identical_key_sets() { + let en: HashSet<_> = table(Locale::En).keys().collect(); + let fr: HashSet<_> = table(Locale::Fr).keys().collect(); + assert_eq!( + en, + fr, + "missing on one side: {:?}", + en.symmetric_difference(&fr) + ); + } + + #[test] + fn placeholders_match_between_locales() { + let fr = table(Locale::Fr); + for (key, en_label) in table(Locale::En) { + let fr_label = fr.get(key).map(String::as_str).unwrap_or_default(); + assert_eq!(placeholders(en_label), placeholders(fr_label), "key {key}"); + } + } + + #[test] + fn lookups_fill_placeholders_and_fall_back_to_the_key() { + assert_eq!( + lookup(Locale::Fr, "startup_migration_failed"), + table(Locale::Fr)["startup_migration_failed"] + ); + assert_eq!(lookup(Locale::Fr, "no_such_key"), "no_such_key"); + assert_eq!( + fill( + "Opened {repo} on {branch}", + &[("repo", "GitSpace"), ("branch", "main")] + ), + "Opened GitSpace on main" + ); + } + + #[test] + fn ui_has_no_literal_strings() { + let mut files = Vec::new(); + let mut dirs = vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ui")]; + while let Some(dir) = dirs.pop() { + for entry in std::fs::read_dir(&dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + dirs.push(path); + } else if path.extension().is_some_and(|ext| ext == "rs") { + files.push(path); + } + } + } + + let mut offenders = Vec::new(); + for file in files { + let source = std::fs::read_to_string(&file).unwrap(); + for (number, line) in crate::ui::non_test_lines(&source) { + if line.contains("// i18n: not user-visible") { + continue; + } + let literal = ["text(\"", "button(\""].iter().any(|call| { + line.match_indices(call).any(|(at, _)| { + line[at + call.len()..] + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic()) + }) + }); + if literal { + offenders.push(format!( + "{}:{}: {}", + file.display(), + number + 1, + line.trim() + )); + } + } + } + assert!( + offenders.is_empty(), + "literal UI strings:\n{}", + offenders.join("\n") + ); + } +} diff --git a/src/i18n/en.json b/src/i18n/en.json new file mode 100644 index 0000000..26267df --- /dev/null +++ b/src/i18n/en.json @@ -0,0 +1,494 @@ +{ + "add_repo_browse": "Browse", + "add_repo_choose_folder": "Choose a folder…", + "add_repo_clone": "Clone", + "add_repo_clone_failed": "Could not clone the repository", + "add_repo_clone_interrupted": "The clone task stopped: {error}", + "add_repo_connect": "Connect an account", + "add_repo_decimal_mark": ".", + "add_repo_folder_hint": "Pick a folder that holds a Git repository.", + "add_repo_github": "GitHub", + "add_repo_gitlab": "GitLab", + "add_repo_gitlab_unexpected": "Unexpected answer from the GitLab server", + "add_repo_in": "In", + "add_repo_local_folder": "Local folder", + "add_repo_no_results": "No repository found.", + "add_repo_not_a_repo": "{path} is not a Git repository.", + "add_repo_per_second": "{size}/s", + "add_repo_private": "private", + "add_repo_public": "public", + "add_repo_receiving": "Receiving objects · {done} / {total} · {size} · {speed}", + "add_repo_resolving": "Resolving deltas · {done} / {total}", + "add_repo_search_failed": "Could not search the repositories", + "add_repo_search_github": "Search your repositories and your organisations'", + "add_repo_search_gitlab": "Search GitLab projects", + "add_repo_searching": "Searching…", + "add_repo_signed_out": "No account connected: only public repositories are listed.", + "add_repo_size_gb": "{value} GB", + "add_repo_size_kb": "{value} KB", + "add_repo_size_mb": "{value} MB", + "add_repo_starting": "Starting the clone…", + "add_repo_title": "Add a repository", + "add_repo_url": "URL", + "add_repo_url_placeholder": "https://github.com/owner/repo.git or git@gitlab.com:owner/repo.git", + "auth_ssh_failed": "SSH authentication failed: neither ssh-agent nor a key in ~/.ssh (id_ed25519, id_ecdsa, id_rsa) was accepted. Add your key to ssh-agent, or use an https:// remote with a saved token.", + "auth_token_needed": "This remote needs authentication: save a token for its host in GitSpace.", + "auth_token_refused": "The remote refused the saved token. Check that it is still valid and can access this repository.", + "branches_actions": "Branch actions", + "branches_apply": "Apply", + "branches_archive": "Archive as tag…", + "branches_archive_button": "Archive", + "branches_archive_confirm": "Tag the tip of {branch} under archive/? The branch itself stays.", + "branches_archive_failed": "Could not archive the branch", + "branches_archived": "Archived {branch} as {tag}", + "branches_behind": "behind {branch}", + "branches_change_upstream": "Change upstream…", + "branches_changed_outside": "The repository changed outside GitSpace after this was shown, so nothing was done. Check the branches and try again.", + "branches_checked_out": "Checked out {name}", + "branches_checkout": "Check out", + "branches_checkout_failed": "Could not check out the branch", + "branches_commit_ahead": "commit ahead", + "branches_commits_ahead": "commits ahead", + "branches_commits_failed": "Could not read the commits: {error}", + "branches_commits_only_on": "Commits only on {branch}", + "branches_conflicts": "Stopped on conflicts", + "branches_conflicts_detail": "Resolve them in the Changes tab: {files}", + "branches_copy_name": "Copy name", + "branches_create": "Create", + "branches_create_failed": "Could not create the branch", + "branches_created": "Created branch {name}", + "branches_current": "current", + "branches_delete": "Delete…", + "branches_delete_button": "Delete", + "branches_delete_failed": "Could not delete the branch", + "branches_delete_merged": "Delete {branch}? It is merged into {current}.", + "branches_delete_unmerged": "Delete {branch}? It is not merged into {current}, so its own commits will be on no branch.", + "branches_deleted": "Deleted branch {name}", + "branches_empty": "No branches yet.", + "branches_filter_options": "Filter options", + "branches_filter_placeholder": "Filter…", + "branches_in_sync": "in sync with its upstream", + "branches_last_commit": "last commit {when}", + "branches_latest_commits": "Latest commits on {branch}", + "branches_load_failed": "Could not read the branches: {error}", + "branches_local_group": "LOCAL · {count}", + "branches_merge_button": "Merge", + "branches_merge_confirm": "Merge {branch} into {current}?", + "branches_merge_failed": "The merge failed", + "branches_merge_into": "Merge into {current}", + "branches_merged": "merged", + "branches_merged_into": "Merged {branch} into {current}", + "branches_name_placeholder": "Branch name", + "branches_new": "+ New", + "branches_new_prompt": "New branch from {current}", + "branches_next_page": "Next page", + "branches_no_match": "No branches match the filter.", + "branches_no_own_commits": "Every commit of {branch} is already on {current}.", + "branches_no_upstream": "no upstream", + "branches_no_upstream_choice": "No upstream", + "branches_note_merge": "Merge: {current} gets the commits of {branch} ({count}) in a new merge commit. You confirm before it runs.", + "branches_note_rebase": "Rebase: the commits of {current} are replayed on top of {branch}, which rewrites them. You confirm before it runs.", + "branches_pin": "Pin to top", + "branches_previous_page": "Previous page", + "branches_rebase_button": "Rebase", + "branches_rebase_confirm": "Rebase {current} onto {branch}? The commits of {current} are rewritten.", + "branches_rebase_failed": "The rebase failed", + "branches_rebase_onto": "Rebase {current} onto it", + "branches_rebased": "Rebased {current} onto {branch}", + "branches_remote_branch": "remote branch", + "branches_rename": "Rename", + "branches_rename_button": "Rename", + "branches_rename_failed": "Could not rename the branch", + "branches_rename_prompt": "Rename {branch} to", + "branches_renamed": "Renamed {old} to {new}", + "branches_select": "Select a branch to see where it stands.", + "branches_show_all": "Show all branches", + "branches_stale_only": "Show stale branches only", + "branches_tracks": "tracks {upstream}", + "branches_unpin": "Unpin", + "branches_upstream_ahead": "{count} ahead of its upstream", + "branches_upstream_behind": "{count} behind its upstream", + "branches_upstream_diverged": "{ahead} ahead and {behind} behind its upstream", + "branches_upstream_failed": "Could not change the upstream", + "branches_upstream_prompt": "Upstream of {branch}", + "branches_upstream_removed": "{branch} no longer has an upstream", + "branches_upstream_set": "{branch} now tracks {upstream}", + "branches_view_in_history": "View in History →", + "changes_author": "author {name}", + "changes_cancel": "Cancel", + "changes_commit": "Commit", + "changes_commit_failed": "Commit failed", + "changes_commit_options": "Templates and sign-off", + "changes_committed": "Committed {hash}", + "changes_copy_path": "Copy path", + "changes_description_placeholder": "Description (optional)", + "changes_discard": "Discard changes…", + "changes_discard_button": "Discard", + "changes_discard_confirm": "Discard the changes to {file}? This cannot be undone.", + "changes_discard_failed": "Could not discard the changes", + "changes_file_actions": "File actions", + "changes_load_failed": "Could not read the changes", + "changes_loading": "Loading…", + "changes_no_diff": "No text changes to show for this file.", + "changes_nothing_detail": "The working tree on {branch} matches the last commit.", + "changes_nothing_title": "Nothing to commit", + "changes_on_branch": "on {branch}", + "changes_open_file": "Open file", + "changes_open_file_failed": "Could not open the file", + "changes_restore_button": "Restore", + "changes_restore_failed": "Could not restore the file", + "changes_restore_from_branch": "Restore from branch…", + "changes_restore_prompt": "Restore {file} from", + "changes_restore_warning": "Its local changes will be lost.", + "changes_select_file": "Select a file to see its changes.", + "changes_signoff": "Add Signed-off-by line", + "changes_signoff_missing": "Sign-off needs user.name and user.email", + "changes_stage_all": "Stage all", + "changes_stage_failed": "Could not stage the file", + "changes_stage_file": "Stage file", + "changes_staged": "STAGED · {count}", + "changes_staged_many": "{count} files staged", + "changes_staged_one": "1 file staged", + "changes_summary_placeholder": "Summary (required)", + "changes_template": "Template: {name}", + "changes_template_feature": "Feature", + "changes_template_feature_text": "feat: short summary\n\n- describe the change\n- add context or links", + "changes_template_fix": "Fix", + "changes_template_fix_text": "fix: bug summary\n\nExplain the root cause and how it was fixed.", + "changes_template_wip": "WIP", + "changes_template_wip_text": "WIP: describe the work in progress", + "changes_truncated": "The diff stops here: the file is too large to show in full.", + "changes_unstage_all": "Unstage all", + "changes_unstage_failed": "Could not unstage the file", + "changes_unstage_file": "Unstage file", + "changes_unstaged": "UNSTAGED · {count}", + "clone_stalled": "Clone stopped: no data arrived for {seconds} seconds", + "commit_identity_missing": "Set user.name and user.email in your Git config to commit ({error})", + "commit_message_empty": "The commit message is empty.", + "commit_nothing_staged": "Nothing is staged for commit.", + "commit_operation_in_progress": "A merge, rebase or other operation is in progress; finish it with git first.", + "config_save_failed": "Could not save the preferences", + "copy_log_path": "Copy log path", + "credentials_ciphertext_decode_failed": "Failed to decode ciphertext: {error}", + "credentials_decrypt_failed": "Failed to decrypt credentials: {error}", + "credentials_decrypted_parse_failed": "Failed to parse decrypted credentials: {error}", + "credentials_encoding_invalid": "Invalid credential encoding: {error}", + "credentials_left_untouched": "{error}. {path} was left untouched so the other saved tokens are kept. Unlock the system keyring or use the same {variable} as when the tokens were saved, then restart GitSpace, or move the file aside to start over", + "credentials_nonce_decode_failed": "Failed to decode nonce: {error}", + "credentials_nonce_length": "Invalid nonce length: {count} bytes", + "credentials_parse_failed": "Failed to parse credential file: {error}", + "credentials_read_failed": "Failed to read credential file: {error}", + "credentials_serialize_failed": "Failed to serialize credentials: {error}", + "credentials_write_failed": "Failed to write credentials: {error}", + "discard_no_changes": "the file has no changes to discard", + "discard_path_outside_repository": "the path is outside the repository", + "error_config": "Configuration error. Please check your settings.", + "error_config_detail": "Configuration error: {detail}", + "error_connect": "Failed to connect to server.", + "error_git": "Git operation failed. Please check the repository status.", + "error_git_detail": "Git operation failed: {detail}", + "error_http_status": "HTTP error: {error}", + "error_io": "File system operation failed. Verify permissions and disk space.", + "error_io_detail": "I/O operation failed: {detail}", + "error_json": "JSON parse error: {error}", + "error_network": "Network request failed. Check your connection or proxy settings.", + "error_network_detail": "Network request failed: {detail}", + "error_timed_out": "The request timed out.", + "error_unknown": "An unexpected error occurred.", + "error_unknown_detail": "Unexpected error: {detail}", + "error_validation": "The provided input is not valid. Please double-check and try again.", + "error_validation_detail": "Validation failed: {detail}", + "git_start_failed": "Failed to start git {command}: {error}", + "git_timed_out": "Git {command} timed out after {seconds} seconds", + "git_wait_failed": "Failed to wait for git {command}: {error}", + "header_auto_fetch_failed": "Background fetch failed", + "header_detached": "detached at {hash}", + "header_fetch": "Fetch", + "header_fetch_failed": "Fetch failed", + "header_fetch_remote": "Fetch {remote}", + "header_fetched": "Fetched {remote}", + "header_fetching": "Fetching…", + "header_folder_missing": "Repository folder not found: {path}", + "header_no_branch": "No branch is checked out.", + "header_no_remote": "This repository has no remote.", + "header_no_remotes": "No remotes", + "header_no_terminal": "No supported terminal emulator found on PATH", + "header_no_upstream": "No upstream branch", + "header_pull": "Pull", + "header_pull_failed": "Pull failed", + "header_pulled": "Pulled {branch} from {remote}", + "header_pulling": "Pulling…", + "header_push": "Push", + "header_push_failed": "Push failed", + "header_pushed": "Pushed {branch} to {remote}", + "header_pushing": "Pushing…", + "header_remotes": "Remotes", + "header_status_failed": "Could not read the repository status", + "header_up_to_date": "Already up to date", + "header_upstream": "Tracks {upstream}", + "history_branch_created": "Created branch {name}", + "history_branch_name": "Branch name", + "history_branch_prompt": "New branch at {hash}", + "history_checked_out": "Checked out {hash}", + "history_checkout": "Check out this commit…", + "history_checkout_button": "Check out", + "history_checkout_confirm": "Check out {hash}? HEAD will be detached, so new commits will not be on any branch.", + "history_checkout_failed": "Could not check out the commit", + "history_commit_actions": "Commit actions", + "history_copy_hash": "Copy hash", + "history_create_branch": "Create branch here…", + "history_create_button": "Create", + "history_create_failed": "Could not create the branch", + "history_current_branch": "Current branch", + "history_empty": "No commits yet.", + "history_filter_placeholder": "Filter: message, author, hash…", + "history_load_failed": "Could not read the history: {error}", + "history_load_more": "Load more", + "history_no_match": "No commits match the filter.", + "history_parent": "parent {hash}", + "history_parents": "parents {hashes}", + "history_select_commit": "Select a commit to see its changes.", + "history_select_file": "Select a file to see its diff.", + "host_index_parse_failed": "Failed to parse host index: {error}", + "host_index_read_failed": "Failed to read host index: {error}", + "host_index_serialize_failed": "Failed to serialize host index: {error}", + "host_index_write_failed": "Failed to write host index: {error}", + "keyring_access_failed": "Failed to access keyring: {error}", + "keyring_key_decode_failed": "Failed to decode keyring token key: {error}", + "keyring_key_invalid": "Keyring token key is invalid", + "keyring_key_read_failed": "Failed to read keyring token key: {error}", + "keyring_key_store_failed": "Failed to store token key in keyring: {error}", + "keyring_read_failed": "Failed to read keyring: {error}", + "keyring_remove_failed": "Failed to remove keyring entry: {error}", + "keyring_store_failed": "Failed to store token in keyring: {error}", + "keyring_unavailable_no_fallback": "Native keyring unavailable and encrypted storage is disabled", + "network_http_blocked": "Plain HTTP is blocked while Prefer HTTPS is on in your network preferences.", + "network_https_blocked": "HTTPS connections are blocked while Prefer HTTPS is off in your network preferences.", + "network_ssh_blocked": "SSH access is blocked while Allow SSH is off in your network preferences.", + "oauth_callback_accept_failed": "Failed to accept connection: {error}", + "oauth_callback_listen_failed": "Failed to open the sign-in callback server: {error}", + "oauth_callback_timed_out": "OAuth callback timed out", + "oauth_code_expired": "The code expired before it was approved. Start the sign-in again.", + "oauth_code_request_failed": "Could not get a sign-in code from {provider}: {error}", + "oauth_denied": "The sign-in was denied on {provider}.", + "oauth_http_client_failed": "Failed to build HTTP client: {error}", + "oauth_invalid_url": "Invalid URL {url}: {error}", + "oauth_no_authorization_code": "The sign-in callback has no authorization code", + "oauth_no_client_id": "The {provider} token was saved without its client ID; sign in again", + "oauth_no_device_flow": "{provider} does not support the device flow", + "oauth_no_refresh_token": "The OAuth token has no refresh token", + "oauth_pkce_missing": "PKCE verifier not initialized", + "oauth_port_in_use": "Port {port} is needed for the GitLab sign-in callback but is in use ({error}). Close the program using it and try again.", + "oauth_refresh_failed": "Token refresh failed: {error}", + "oauth_refused": "{provider} refused the sign-in: {error}", + "oauth_token_exchange_failed": "Token exchange failed: {error}", + "oauth_unexpected_answer": "Unexpected answer from {provider} (HTTP {status})", + "oauth_unknown_error": "Unknown error", + "oauth_verification_not_https": "{provider} sent a verification page that is not HTTPS", + "open_folder_failed": "Could not open the folder", + "open_terminal_failed": "Could not open a terminal", + "preferences_not_found": "The file does not contain GitSpace preferences", + "preferences_parse_failed": "Failed to parse preferences: {error}", + "prefs_about_desc": "Version, licence and where GitSpace keeps its files.", + "prefs_account_oauth": "signed in with OAuth", + "prefs_account_oauth_user": "{user} · signed in with OAuth", + "prefs_account_token": "personal access token", + "prefs_accounts_desc": "Tokens are kept in the system keyring and only sent to their own host.", + "prefs_accounts_none": "No account connected yet.", + "prefs_allow_ssh": "Allow SSH", + "prefs_allow_ssh_desc": "Off: remotes with an SSH URL are refused.", + "prefs_browse": "Browse", + "prefs_browser_failed": "Could not open the browser: {error}", + "prefs_cancel": "Cancel", + "prefs_cat_accounts": "Accounts", + "prefs_cat_git": "Git", + "prefs_cat_gitspace": "GitSpace", + "prefs_cat_network": "Network", + "prefs_client_ids_built_in": "This build has a client ID built in (GITSPACE_GITHUB_CLIENT_ID or GITSPACE_GITLAB_CLIENT_ID), used instead of the one typed here.", + "prefs_client_ids_desc": "Register an OAuth app with the provider and enter its client ID. GitHub: tick “Enable Device Flow”; the callback URL is not used. GitLab: untick “Confidential” and set the redirect URI to http://127.0.0.1:9876/callback.", + "prefs_cloning_desc": "Where new repositories go.", + "prefs_config_folder": "Settings folder", + "prefs_connected": "connected", + "prefs_connection_desc": "The transfer timeout and the protocols GitSpace may use.", + "prefs_copy": "Copy", + "prefs_default_folder": "Default folder", + "prefs_default_folder_desc": "New repositories are cloned here. Press Enter to apply a typed path.", + "prefs_disconnect": "Disconnect", + "prefs_disconnect_failed": "Could not disconnect: {error}", + "prefs_encrypted_fallback": "Allow an encrypted file", + "prefs_encrypted_fallback_desc": "Also saves tokens in an encrypted file. Off: a token is only saved when the system keyring works.", + "prefs_export": "Export…", + "prefs_export_failed": "Could not export the preferences", + "prefs_exported": "Preferences saved to {path}.", + "prefs_fetch": "Fetch in the background", + "prefs_fetch_desc": "Fetches the remote of the open repository on a timer.", + "prefs_fetch_interval": "Interval", + "prefs_fetch_interval_desc": "Time between two fetches.", + "prefs_fetch_toggle_desc": "For the open repository only.", + "prefs_file_desc": "Copy your preferences to another computer, or go back to the defaults.", + "prefs_git_desc": "Where to clone, and when to look for new commits.", + "prefs_github_client_id": "GitHub client ID", + "prefs_github_desc": "GitHub shows a code to enter on its sign-in page.", + "prefs_github_enter_code": "Enter this code at {uri}.", + "prefs_github_requesting": "Asking GitHub for a code…", + "prefs_github_start": "Get a sign-in code", + "prefs_github_waiting": "Waiting for you to approve on GitHub…", + "prefs_gitlab_client_id": "GitLab client ID", + "prefs_gitlab_desc": "GitLab opens a browser window to sign in.", + "prefs_gitlab_opening": "Opening the browser…", + "prefs_gitlab_start": "Sign in with the browser", + "prefs_http_proxy": "HTTP proxy", + "prefs_http_proxy_desc": "Used for http:// remotes.", + "prefs_https_proxy": "HTTPS proxy", + "prefs_https_proxy_desc": "Used for https:// remotes.", + "prefs_idle_timeout": "Idle timeout", + "prefs_idle_timeout_desc": "Seconds without data before a transfer stops.", + "prefs_import": "Import…", + "prefs_import_failed": "Could not import the preferences", + "prefs_imported": "Preferences imported.", + "prefs_language": "Interface language", + "prefs_language_desc": "Applies at once to every screen.", + "prefs_language_english": "English", + "prefs_language_french": "Français", + "prefs_language_row_desc": "System follows the language of your session.", + "prefs_language_system": "System", + "prefs_licence": "Licence", + "prefs_logs_desc": "GitSpace writes one log file per day.", + "prefs_logs_folder": "Logs folder", + "prefs_logs_kept": "Log files kept", + "prefs_logs_kept_desc": "Older files are deleted at the next start.", + "prefs_minutes": "{count} min", + "prefs_network_desc": "How GitSpace reaches remote servers.", + "prefs_no_client_id": "Enter an OAuth client ID first, under OAuth app client IDs.", + "prefs_open": "Open", + "prefs_open_github": "Open github.com", + "prefs_open_link_failed": "Could not open the link", + "prefs_open_logs": "Open the logs folder", + "prefs_pinned_desc": "Pinned branches stay at the top of the Branches tab.", + "prefs_pinned_none": "No pinned branch. Pin one from the Branches tab.", + "prefs_prefer_https": "Prefer HTTPS", + "prefs_prefer_https_desc": "On: plain http:// remotes are refused. Off: https:// remotes are refused.", + "prefs_proxy_desc": "Leave a field empty to connect directly.", + "prefs_proxy_example": "http://proxy.example.com:8080", + "prefs_reopen_last": "Reopen the last repository at startup", + "prefs_reopen_last_desc": "Off: GitSpace starts on the Add repository screen.", + "prefs_reset": "Reset to defaults", + "prefs_reset_confirm": "Reset every preference to its default? This cannot be undone.", + "prefs_reset_yes": "Reset", + "prefs_scan_folder": "List the repositories in this folder", + "prefs_scan_folder_desc": "Adds each repository one level down to the sidebar.", + "prefs_section_client_ids": "OAuth app client IDs", + "prefs_section_cloning": "Cloning", + "prefs_section_connection": "Connection", + "prefs_section_fetch": "Background fetch", + "prefs_section_file": "Preferences file", + "prefs_section_github": "Sign in to GitHub", + "prefs_section_gitlab": "Sign in to GitLab", + "prefs_section_language": "Language", + "prefs_section_logs": "Logs", + "prefs_section_pinned": "Pinned branches", + "prefs_section_proxy": "Proxy", + "prefs_section_startup": "Startup", + "prefs_section_storage": "Token storage", + "prefs_section_token": "Add a token", + "prefs_signin_cancelled": "Sign-in cancelled.", + "prefs_signin_done": "Signed in.", + "prefs_signin_failed": "Sign-in failed: {error}", + "prefs_signin_saving": "Saving the token…", + "prefs_source_code": "Source code", + "prefs_startup_desc": "What GitSpace shows when it starts.", + "prefs_storage_desc": "Where tokens are saved when the system keyring cannot hold them.", + "prefs_token_checking": "Checking the token…", + "prefs_token_desc": "A personal access token, for self-hosted servers or when OAuth is not available.", + "prefs_token_empty": "Enter a host and a token.", + "prefs_token_host": "Host, e.g. github.com or gitlab.example.com", + "prefs_token_rejected": "The token was refused: {error}", + "prefs_token_save": "Validate and save", + "prefs_token_saved": "Token checked and saved.", + "prefs_token_store_failed": "Could not save the token: {error}", + "prefs_token_value": "Personal access token", + "prefs_unpin": "Remove", + "prefs_version": "Version", + "remote_pull_diverged": "Non-fast-forward pull required. Please merge or rebase manually.", + "remote_pull_not_checked_out": "Pull only updates the checked-out branch, and {branch} is not checked out.", + "remote_push_not_checked_out": "Push only sends the checked-out branch, and {branch} is not checked out.", + "repo_missing_detail": "{path} is missing or is not a Git repository.", + "repo_missing_title": "Repository not found", + "repo_no_work_tree": "the repository has no work tree", + "retry": "Retry", + "sidebar_add": "+ Clone or open", + "sidebar_hint": "Ctrl+K search · Alt+↑↓ repository", + "sidebar_missing": "missing", + "sidebar_open_folder": "Open folder", + "sidebar_open_terminal": "Open terminal", + "sidebar_pin": "Pin", + "sidebar_pinned": "PINNED", + "sidebar_recent": "RECENT", + "sidebar_remove": "Remove from list", + "sidebar_repositories": "Repositories · {count}", + "sidebar_results": "{count} RESULTS", + "sidebar_results_one": "1 RESULT", + "sidebar_search_close": "Close search (Esc)", + "sidebar_search_hint": "↑↓ choose · Enter open · Esc close", + "sidebar_search_placeholder": "Search repositories", + "sidebar_search_tip": "Search (Ctrl+K)", + "sidebar_unpin": "Unpin", + "startup_migration_failed": "Could not move your settings to the new folder", + "startup_migration_failed_detail": "GitSpace is using the old folder for now. {error}", + "stash_list_changed": "The stash list changed; refresh and try again.", + "stashes_actions": "Stash actions", + "stashes_applied": "Stash #{index} applied", + "stashes_applied_conflicts": "Stash #{index} applied with conflicts", + "stashes_applied_dropped": "Stash #{index} applied and dropped", + "stashes_applied_not_dropped": "The stash was applied but not dropped: {error}", + "stashes_apply": "Apply", + "stashes_apply_and_drop": "Apply and drop", + "stashes_apply_drop_failed": "Could not apply and drop the stash", + "stashes_apply_failed": "Could not apply the stash", + "stashes_close_contents": "Close the contents", + "stashes_conflicts_kept": "The apply left conflicts, so the stash was kept. Resolve them, then drop the stash.", + "stashes_create": "Stash changes", + "stashes_create_failed": "Could not stash the changes", + "stashes_created": "Changes stashed", + "stashes_detached": "on a detached HEAD", + "stashes_drop": "Drop…", + "stashes_drop_button": "Drop", + "stashes_drop_confirm": "Drop stash #{index} “{message}”? This cannot be undone.", + "stashes_drop_failed": "Could not drop the stash", + "stashes_dropped": "Stash #{index} dropped", + "stashes_empty_detail": "Stashed changes are listed here until you apply or drop them.", + "stashes_empty_title": "No stashes", + "stashes_files": "{count} files", + "stashes_include_untracked": "Include untracked files", + "stashes_load_failed": "Could not read the stashes: {error}", + "stashes_message_placeholder": "Stash message…", + "stashes_nothing_to_stash": "No changes to stash.", + "stashes_on_branch": "on {branch}", + "stashes_one_file": "1 file", + "stashes_select_file": "Choose a file to see its changes.", + "stashes_show_contents": "Show contents", + "stashes_will_stash_many": "{count} changed files will be stashed and the working copy becomes clean.", + "stashes_will_stash_one": "1 changed file will be stashed and the working copy becomes clean.", + "tab_branches": "Branches", + "tab_changes": "Changes", + "tab_history": "History", + "tab_stashes": "Stashes", + "time_days_ago": "{count} days ago", + "time_hours_ago": "{count} h ago", + "time_just_now": "just now", + "time_minutes_ago": "{count} min ago", + "time_yesterday": "yesterday", + "token_check_failed": "{provider} validation failed: {error}", + "token_empty": "Token cannot be empty", + "token_host_not_https": "The host must use https: GitSpace never sends a token over plain HTTP.", + "token_https_remotes_only": "GitSpace sends a saved token only to https:// remotes.", + "token_invalid_characters": "Token contains invalid characters", + "token_invalid_host": "Invalid host \"{host}\": {error}", + "token_oauth_serialize_failed": "Failed to serialize OAuth token: {error}", + "token_rejected": "{provider} rejected token ({status}).", + "token_remote_plain_http": "This remote uses plain HTTP: GitSpace never sends a token over it. Use an https:// remote URL.", + "token_too_long": "Token is too long (maximum {count} characters)", + "token_too_short": "Token is too short (minimum {count} characters)", + "tokens_encrypt_failed": "Failed to encrypt tokens: {error}", + "tokens_serialize_failed": "Failed to serialize tokens: {error}" +} diff --git a/src/i18n/fr.json b/src/i18n/fr.json new file mode 100644 index 0000000..bf24701 --- /dev/null +++ b/src/i18n/fr.json @@ -0,0 +1,494 @@ +{ + "add_repo_browse": "Parcourir", + "add_repo_choose_folder": "Choisir un dossier…", + "add_repo_clone": "Cloner", + "add_repo_clone_failed": "Impossible de cloner le dépôt", + "add_repo_clone_interrupted": "La tâche de clonage s'est arrêtée : {error}", + "add_repo_connect": "Connecter un compte", + "add_repo_decimal_mark": ",", + "add_repo_folder_hint": "Choisissez un dossier qui contient un dépôt Git.", + "add_repo_github": "GitHub", + "add_repo_gitlab": "GitLab", + "add_repo_gitlab_unexpected": "Réponse inattendue du serveur GitLab", + "add_repo_in": "Dans", + "add_repo_local_folder": "Dossier local", + "add_repo_no_results": "Aucun dépôt trouvé.", + "add_repo_not_a_repo": "{path} n'est pas un dépôt Git.", + "add_repo_per_second": "{size}/s", + "add_repo_private": "privé", + "add_repo_public": "public", + "add_repo_receiving": "Réception des objets · {done} / {total} · {size} · {speed}", + "add_repo_resolving": "Résolution des deltas · {done} / {total}", + "add_repo_search_failed": "Impossible de rechercher les dépôts", + "add_repo_search_github": "Rechercher dans vos dépôts et ceux de vos organisations", + "add_repo_search_gitlab": "Rechercher des projets GitLab", + "add_repo_searching": "Recherche…", + "add_repo_signed_out": "Aucun compte connecté : seuls les dépôts publics sont listés.", + "add_repo_size_gb": "{value} Go", + "add_repo_size_kb": "{value} Ko", + "add_repo_size_mb": "{value} Mo", + "add_repo_starting": "Démarrage du clonage…", + "add_repo_title": "Ajouter un dépôt", + "add_repo_url": "URL", + "add_repo_url_placeholder": "https://github.com/owner/repo.git ou git@gitlab.com:owner/repo.git", + "auth_ssh_failed": "L'authentification SSH a échoué : ni ssh-agent ni aucune clé de ~/.ssh (id_ed25519, id_ecdsa, id_rsa) n'a été acceptée. Ajoutez votre clé à ssh-agent, ou utilisez un remote en https:// avec un token enregistré.", + "auth_token_needed": "Ce remote demande une authentification : enregistrez un token pour son hôte dans GitSpace.", + "auth_token_refused": "Le remote a refusé le token enregistré. Vérifiez qu'il est toujours valide et qu'il a accès à ce dépôt.", + "branches_actions": "Actions de la branche", + "branches_apply": "Appliquer", + "branches_archive": "Archiver en tag…", + "branches_archive_button": "Archiver", + "branches_archive_confirm": "Poser un tag sous archive/ sur le dernier commit de {branch} ? La branche reste en place.", + "branches_archive_failed": "Impossible d'archiver la branche", + "branches_archived": "{branch} archivée sous {tag}", + "branches_behind": "de retard sur {branch}", + "branches_change_upstream": "Changer d'upstream…", + "branches_changed_outside": "Le dépôt a changé hors de GitSpace depuis cet affichage : rien n'a été fait. Vérifiez les branches et réessayez.", + "branches_checked_out": "Basculé sur {name}", + "branches_checkout": "Basculer dessus", + "branches_checkout_failed": "Impossible de basculer sur la branche", + "branches_commit_ahead": "commit d'avance", + "branches_commits_ahead": "commits d'avance", + "branches_commits_failed": "Impossible de lire les commits : {error}", + "branches_commits_only_on": "Commits propres à {branch}", + "branches_conflicts": "Arrêt sur des conflits", + "branches_conflicts_detail": "Résolvez-les dans l'onglet Modifications : {files}", + "branches_copy_name": "Copier le nom", + "branches_create": "Créer", + "branches_create_failed": "Impossible de créer la branche", + "branches_created": "Branche {name} créée", + "branches_current": "actuelle", + "branches_delete": "Supprimer…", + "branches_delete_button": "Supprimer", + "branches_delete_failed": "Impossible de supprimer la branche", + "branches_delete_merged": "Supprimer {branch} ? Elle est fusionnée dans {current}.", + "branches_delete_unmerged": "Supprimer {branch} ? Elle n'est pas fusionnée dans {current} : ses propres commits ne seront plus sur aucune branche.", + "branches_deleted": "Branche {name} supprimée", + "branches_empty": "Aucune branche pour l'instant.", + "branches_filter_options": "Options du filtre", + "branches_filter_placeholder": "Filtrer…", + "branches_in_sync": "à jour avec son upstream", + "branches_last_commit": "dernier commit {when}", + "branches_latest_commits": "Derniers commits de {branch}", + "branches_load_failed": "Impossible de lire les branches : {error}", + "branches_local_group": "LOCALES · {count}", + "branches_merge_button": "Fusionner", + "branches_merge_confirm": "Fusionner {branch} dans {current} ?", + "branches_merge_failed": "La fusion a échoué", + "branches_merge_into": "Fusionner dans {current}", + "branches_merged": "fusionnée", + "branches_merged_into": "{branch} fusionnée dans {current}", + "branches_name_placeholder": "Nom de la branche", + "branches_new": "+ Nouvelle", + "branches_new_prompt": "Nouvelle branche depuis {current}", + "branches_next_page": "Page suivante", + "branches_no_match": "Aucune branche ne correspond au filtre.", + "branches_no_own_commits": "Tous les commits de {branch} sont déjà sur {current}.", + "branches_no_upstream": "pas d'upstream", + "branches_no_upstream_choice": "Pas d'upstream", + "branches_note_merge": "Fusionner : {current} reçoit les commits de {branch} ({count}) dans un nouveau commit de fusion. Une confirmation est demandée.", + "branches_note_rebase": "Rebaser : les commits de {current} sont rejoués au-dessus de {branch}, ce qui les réécrit. Une confirmation est demandée.", + "branches_pin": "Épingler en haut", + "branches_previous_page": "Page précédente", + "branches_rebase_button": "Rebaser", + "branches_rebase_confirm": "Rebaser {current} sur {branch} ? Les commits de {current} seront réécrits.", + "branches_rebase_failed": "Le rebase a échoué", + "branches_rebase_onto": "Rebaser {current} dessus", + "branches_rebased": "{current} rebasée sur {branch}", + "branches_remote_branch": "branche distante", + "branches_rename": "Renommer", + "branches_rename_button": "Renommer", + "branches_rename_failed": "Impossible de renommer la branche", + "branches_rename_prompt": "Renommer {branch} en", + "branches_renamed": "{old} renommée en {new}", + "branches_select": "Choisissez une branche pour voir où elle en est.", + "branches_show_all": "Afficher toutes les branches", + "branches_stale_only": "Afficher seulement les branches inactives", + "branches_tracks": "suit {upstream}", + "branches_unpin": "Désépingler", + "branches_upstream_ahead": "{count} d'avance sur son upstream", + "branches_upstream_behind": "{count} de retard sur son upstream", + "branches_upstream_diverged": "{ahead} d'avance et {behind} de retard sur son upstream", + "branches_upstream_failed": "Impossible de changer d'upstream", + "branches_upstream_prompt": "Upstream de {branch}", + "branches_upstream_removed": "{branch} n'a plus d'upstream", + "branches_upstream_set": "{branch} suit maintenant {upstream}", + "branches_view_in_history": "Voir dans l'historique →", + "changes_author": "auteur {name}", + "changes_cancel": "Annuler", + "changes_commit": "Commit", + "changes_commit_failed": "Échec du commit", + "changes_commit_options": "Modèles et sign-off", + "changes_committed": "Commit {hash} créé", + "changes_copy_path": "Copier le chemin", + "changes_description_placeholder": "Description (facultative)…", + "changes_discard": "Annuler les modifications…", + "changes_discard_button": "Annuler les modifications", + "changes_discard_confirm": "Annuler les modifications de {file} ? Cette action est définitive.", + "changes_discard_failed": "Impossible d'annuler les modifications", + "changes_file_actions": "Actions sur le fichier", + "changes_load_failed": "Impossible de lire les modifications", + "changes_loading": "Chargement…", + "changes_no_diff": "Aucune modification de texte à afficher pour ce fichier.", + "changes_nothing_detail": "L'arbre de travail sur {branch} correspond au dernier commit.", + "changes_nothing_title": "Rien à committer", + "changes_on_branch": "sur {branch}", + "changes_open_file": "Ouvrir le fichier", + "changes_open_file_failed": "Impossible d'ouvrir le fichier", + "changes_restore_button": "Restaurer", + "changes_restore_failed": "Impossible de restaurer le fichier", + "changes_restore_from_branch": "Restaurer depuis une branche…", + "changes_restore_prompt": "Restaurer {file} depuis", + "changes_restore_warning": "Ses modifications locales seront perdues.", + "changes_select_file": "Choisissez un fichier pour voir ses modifications.", + "changes_signoff": "Ajouter la ligne Signed-off-by", + "changes_signoff_missing": "Le sign-off demande user.name et user.email", + "changes_stage_all": "Tout indexer", + "changes_stage_failed": "Impossible d'indexer le fichier", + "changes_stage_file": "Indexer le fichier", + "changes_staged": "INDEXÉS · {count}", + "changes_staged_many": "{count} fichiers indexés", + "changes_staged_one": "1 fichier indexé", + "changes_summary_placeholder": "Résumé (obligatoire)", + "changes_template": "Modèle : {name}", + "changes_template_feature": "Fonctionnalité", + "changes_template_feature_text": "feat: résumé court\n\n- décrire le changement\n- ajouter du contexte ou des liens", + "changes_template_fix": "Correctif", + "changes_template_fix_text": "fix: résumé du bug\n\nExpliquer la cause et la correction.", + "changes_template_wip": "WIP", + "changes_template_wip_text": "WIP: décrire le travail en cours", + "changes_truncated": "Le diff s'arrête ici : le fichier est trop grand pour être affiché en entier.", + "changes_unstage_all": "Tout retirer", + "changes_unstage_failed": "Impossible de retirer le fichier de l'index", + "changes_unstage_file": "Retirer de l'index", + "changes_unstaged": "NON INDEXÉS · {count}", + "clone_stalled": "Clonage arrêté : aucune donnée reçue pendant {seconds} secondes", + "commit_identity_missing": "Renseignez user.name et user.email dans votre configuration Git pour faire un commit ({error})", + "commit_message_empty": "Le message du commit est vide.", + "commit_nothing_staged": "Rien n'est indexé pour le commit.", + "commit_operation_in_progress": "Une fusion, un rebase ou une autre opération est en cours ; terminez-la d'abord avec git.", + "config_save_failed": "Impossible d'enregistrer les préférences", + "copy_log_path": "Copier le chemin des journaux", + "credentials_ciphertext_decode_failed": "Impossible de décoder le texte chiffré : {error}", + "credentials_decrypt_failed": "Impossible de déchiffrer les identifiants : {error}", + "credentials_decrypted_parse_failed": "Impossible d'analyser les identifiants déchiffrés : {error}", + "credentials_encoding_invalid": "Encodage des identifiants non valide : {error}", + "credentials_left_untouched": "{error}. {path} n'a pas été modifié, pour garder les autres tokens enregistrés. Déverrouillez le trousseau du système ou utilisez le même {variable} que lors de l'enregistrement des tokens, puis redémarrez GitSpace, ou déplacez le fichier pour repartir de zéro", + "credentials_nonce_decode_failed": "Impossible de décoder le nonce : {error}", + "credentials_nonce_length": "Longueur de nonce non valide : {count} octets", + "credentials_parse_failed": "Impossible d'analyser le fichier des identifiants : {error}", + "credentials_read_failed": "Impossible de lire le fichier des identifiants : {error}", + "credentials_serialize_failed": "Impossible de sérialiser les identifiants : {error}", + "credentials_write_failed": "Impossible d'écrire les identifiants : {error}", + "discard_no_changes": "le fichier n'a aucune modification à annuler", + "discard_path_outside_repository": "le chemin est en dehors du dépôt", + "error_config": "Erreur de configuration. Vérifiez vos réglages.", + "error_config_detail": "Erreur de configuration : {detail}", + "error_connect": "Impossible de joindre le serveur.", + "error_git": "L'opération Git a échoué. Vérifiez l'état du dépôt.", + "error_git_detail": "L'opération Git a échoué : {detail}", + "error_http_status": "Erreur HTTP : {error}", + "error_io": "L'opération sur les fichiers a échoué. Vérifiez les droits d'accès et l'espace disque.", + "error_io_detail": "L'opération sur les fichiers a échoué : {detail}", + "error_json": "Erreur de lecture JSON : {error}", + "error_network": "La requête réseau a échoué. Vérifiez votre connexion ou les réglages du proxy.", + "error_network_detail": "La requête réseau a échoué : {detail}", + "error_timed_out": "La requête a expiré.", + "error_unknown": "Une erreur inattendue s'est produite.", + "error_unknown_detail": "Erreur inattendue : {detail}", + "error_validation": "La saisie n'est pas valide. Vérifiez-la et réessayez.", + "error_validation_detail": "La vérification a échoué : {detail}", + "git_start_failed": "Impossible de lancer git {command} : {error}", + "git_timed_out": "La commande git {command} a été arrêtée au bout de {seconds} secondes", + "git_wait_failed": "Impossible d'attendre la fin de git {command} : {error}", + "header_auto_fetch_failed": "Échec du fetch en arrière-plan", + "header_detached": "détachée sur {hash}", + "header_fetch": "Fetch", + "header_fetch_failed": "Échec du fetch", + "header_fetch_remote": "Fetch de {remote}", + "header_fetched": "Fetch de {remote} terminé", + "header_fetching": "Fetch…", + "header_folder_missing": "Dossier du dépôt introuvable : {path}", + "header_no_branch": "Aucune branche n'est extraite.", + "header_no_remote": "Ce dépôt n'a aucun remote.", + "header_no_remotes": "Aucun remote", + "header_no_terminal": "Aucun émulateur de terminal pris en charge dans le PATH", + "header_no_upstream": "Pas de branche amont", + "header_pull": "Pull", + "header_pull_failed": "Échec du pull", + "header_pulled": "{branch} mise à jour depuis {remote}", + "header_pulling": "Pull…", + "header_push": "Push", + "header_push_failed": "Échec du push", + "header_pushed": "{branch} envoyée vers {remote}", + "header_pushing": "Push…", + "header_remotes": "Remotes", + "header_status_failed": "Impossible de lire l'état du dépôt", + "header_up_to_date": "Déjà à jour", + "header_upstream": "Suit {upstream}", + "history_branch_created": "Branche {name} créée", + "history_branch_name": "Nom de la branche", + "history_branch_prompt": "Nouvelle branche sur {hash}", + "history_checked_out": "{hash} extrait", + "history_checkout": "Extraire ce commit…", + "history_checkout_button": "Extraire", + "history_checkout_confirm": "Extraire {hash} ? HEAD sera détaché : les nouveaux commits ne seront sur aucune branche.", + "history_checkout_failed": "Impossible d'extraire le commit", + "history_commit_actions": "Actions du commit", + "history_copy_hash": "Copier le hash", + "history_create_branch": "Créer une branche ici…", + "history_create_button": "Créer", + "history_create_failed": "Impossible de créer la branche", + "history_current_branch": "Branche actuelle", + "history_empty": "Aucun commit pour l'instant.", + "history_filter_placeholder": "Filtrer : message, auteur, hash…", + "history_load_failed": "Impossible de lire l'historique : {error}", + "history_load_more": "Charger plus", + "history_no_match": "Aucun commit ne correspond au filtre.", + "history_parent": "parent {hash}", + "history_parents": "parents {hashes}", + "history_select_commit": "Choisissez un commit pour voir ses modifications.", + "history_select_file": "Choisissez un fichier pour voir son diff.", + "host_index_parse_failed": "Impossible d'analyser la liste des hôtes : {error}", + "host_index_read_failed": "Impossible de lire la liste des hôtes : {error}", + "host_index_serialize_failed": "Impossible de sérialiser la liste des hôtes : {error}", + "host_index_write_failed": "Impossible d'écrire la liste des hôtes : {error}", + "keyring_access_failed": "Impossible d'accéder au trousseau du système : {error}", + "keyring_key_decode_failed": "Impossible de décoder la clé des tokens du trousseau : {error}", + "keyring_key_invalid": "La clé des tokens du trousseau n'est pas valide", + "keyring_key_read_failed": "Impossible de lire la clé des tokens du trousseau : {error}", + "keyring_key_store_failed": "Impossible d'enregistrer la clé des tokens dans le trousseau : {error}", + "keyring_read_failed": "Impossible de lire le trousseau du système : {error}", + "keyring_remove_failed": "Impossible de supprimer l'entrée du trousseau du système : {error}", + "keyring_store_failed": "Impossible d'enregistrer le token dans le trousseau du système : {error}", + "keyring_unavailable_no_fallback": "Le trousseau du système est indisponible et l'enregistrement dans un fichier chiffré est désactivé", + "network_http_blocked": "Le HTTP simple est bloqué tant que l'option Préférer HTTPS est activée dans vos préférences réseau.", + "network_https_blocked": "Les connexions HTTPS sont bloquées tant que l'option Préférer HTTPS est désactivée dans vos préférences réseau.", + "network_ssh_blocked": "L'accès SSH est bloqué tant que l'option Autoriser SSH est désactivée dans vos préférences réseau.", + "oauth_callback_accept_failed": "Impossible d'accepter la connexion entrante : {error}", + "oauth_callback_listen_failed": "Impossible d'ouvrir le serveur de retour de connexion : {error}", + "oauth_callback_timed_out": "Le retour de la connexion OAuth n'est pas arrivé à temps", + "oauth_code_expired": "Le code a expiré avant d'être validé. Relancez la connexion.", + "oauth_code_request_failed": "Impossible d'obtenir un code de connexion de {provider} : {error}", + "oauth_denied": "La connexion a été refusée sur {provider}.", + "oauth_http_client_failed": "Impossible de préparer le client HTTP : {error}", + "oauth_invalid_url": "URL non valide {url} : {error}", + "oauth_no_authorization_code": "Le retour de la connexion ne contient pas de code d'autorisation", + "oauth_no_client_id": "Le token {provider} a été enregistré sans son identifiant client ; reconnectez-vous", + "oauth_no_device_flow": "{provider} n'accepte pas la connexion par code", + "oauth_no_refresh_token": "Le token OAuth n'a pas de token de renouvellement", + "oauth_pkce_missing": "Le vérificateur PKCE n'est pas initialisé", + "oauth_port_in_use": "Le port {port} sert au retour de la connexion GitLab, mais il est déjà utilisé ({error}). Fermez le programme qui l'occupe, puis réessayez.", + "oauth_refresh_failed": "Le renouvellement du token a échoué : {error}", + "oauth_refused": "{provider} a refusé la connexion : {error}", + "oauth_token_exchange_failed": "L'échange du code contre un token a échoué : {error}", + "oauth_unexpected_answer": "Réponse inattendue de {provider} (HTTP {status})", + "oauth_unknown_error": "Erreur inconnue", + "oauth_verification_not_https": "{provider} a envoyé une page de vérification qui n'est pas en HTTPS", + "open_folder_failed": "Impossible d'ouvrir le dossier", + "open_terminal_failed": "Impossible d'ouvrir un terminal", + "preferences_not_found": "Le fichier ne contient pas de préférences GitSpace", + "preferences_parse_failed": "Impossible d'analyser les préférences : {error}", + "prefs_about_desc": "Version, licence et emplacement des fichiers de GitSpace.", + "prefs_account_oauth": "connexion OAuth", + "prefs_account_oauth_user": "{user} · connexion OAuth", + "prefs_account_token": "token d'accès personnel", + "prefs_accounts_desc": "Les tokens restent dans le trousseau du système et ne partent que vers leur propre hôte.", + "prefs_accounts_none": "Aucun compte connecté pour l'instant.", + "prefs_allow_ssh": "Autoriser SSH", + "prefs_allow_ssh_desc": "Désactivé : les remotes avec une URL SSH sont refusés.", + "prefs_browse": "Parcourir", + "prefs_browser_failed": "Impossible d'ouvrir le navigateur : {error}", + "prefs_cancel": "Annuler", + "prefs_cat_accounts": "Comptes", + "prefs_cat_git": "Git", + "prefs_cat_gitspace": "GitSpace", + "prefs_cat_network": "Réseau", + "prefs_client_ids_built_in": "Cette version a un identifiant client intégré (GITSPACE_GITHUB_CLIENT_ID ou GITSPACE_GITLAB_CLIENT_ID), utilisé à la place de celui saisi ici.", + "prefs_client_ids_desc": "Enregistrez une application OAuth chez le fournisseur et saisissez son identifiant client. GitHub : cochez « Enable Device Flow » ; l'URL de callback n'est pas utilisée. GitLab : décochez « Confidential » et indiquez l'URI de redirection http://127.0.0.1:9876/callback.", + "prefs_cloning_desc": "Où vont les nouveaux dépôts.", + "prefs_config_folder": "Dossier des réglages", + "prefs_connected": "connecté", + "prefs_connection_desc": "Le délai des transferts et les protocoles que GitSpace peut utiliser.", + "prefs_copy": "Copier", + "prefs_default_folder": "Dossier par défaut", + "prefs_default_folder_desc": "Les nouveaux dépôts sont clonés ici. Appuyez sur Entrée pour appliquer un chemin saisi.", + "prefs_disconnect": "Déconnecter", + "prefs_disconnect_failed": "Déconnexion impossible : {error}", + "prefs_encrypted_fallback": "Autoriser un fichier chiffré", + "prefs_encrypted_fallback_desc": "Enregistre aussi les tokens dans un fichier chiffré. Désactivé : un token n'est enregistré que si le trousseau du système fonctionne.", + "prefs_export": "Exporter…", + "prefs_export_failed": "Impossible d'exporter les préférences", + "prefs_exported": "Préférences enregistrées dans {path}.", + "prefs_fetch": "Fetch en arrière-plan", + "prefs_fetch_desc": "Récupère le remote du dépôt ouvert à intervalle régulier.", + "prefs_fetch_interval": "Intervalle", + "prefs_fetch_interval_desc": "Temps entre deux fetchs.", + "prefs_fetch_toggle_desc": "Pour le dépôt ouvert seulement.", + "prefs_file_desc": "Copier vos préférences sur un autre ordinateur, ou revenir aux valeurs par défaut.", + "prefs_git_desc": "Où cloner, et quand aller chercher les nouveautés.", + "prefs_github_client_id": "Identifiant client GitHub", + "prefs_github_desc": "GitHub affiche un code à saisir sur sa page de connexion.", + "prefs_github_enter_code": "Saisissez ce code sur {uri}.", + "prefs_github_requesting": "Demande d'un code à GitHub…", + "prefs_github_start": "Obtenir un code de connexion", + "prefs_github_waiting": "En attente de votre validation sur GitHub…", + "prefs_gitlab_client_id": "Identifiant client GitLab", + "prefs_gitlab_desc": "GitLab ouvre une fenêtre du navigateur pour la connexion.", + "prefs_gitlab_opening": "Ouverture du navigateur…", + "prefs_gitlab_start": "Se connecter dans le navigateur", + "prefs_http_proxy": "Proxy HTTP", + "prefs_http_proxy_desc": "Utilisé pour les remotes en http://.", + "prefs_https_proxy": "Proxy HTTPS", + "prefs_https_proxy_desc": "Utilisé pour les remotes en https://.", + "prefs_idle_timeout": "Délai d'inactivité", + "prefs_idle_timeout_desc": "Secondes sans données avant l'arrêt d'un transfert.", + "prefs_import": "Importer…", + "prefs_import_failed": "Impossible d'importer les préférences", + "prefs_imported": "Préférences importées.", + "prefs_language": "Langue de l'interface", + "prefs_language_desc": "S'applique tout de suite à tous les écrans.", + "prefs_language_english": "English", + "prefs_language_french": "Français", + "prefs_language_row_desc": "Système suit la langue de votre session.", + "prefs_language_system": "Système", + "prefs_licence": "Licence", + "prefs_logs_desc": "GitSpace écrit un fichier de journal par jour.", + "prefs_logs_folder": "Dossier des journaux", + "prefs_logs_kept": "Fichiers de journal conservés", + "prefs_logs_kept_desc": "Les plus anciens sont supprimés au prochain démarrage.", + "prefs_minutes": "{count} min", + "prefs_network_desc": "Comment GitSpace joint les serveurs distants.", + "prefs_no_client_id": "Saisissez d'abord un identifiant client OAuth, dans Identifiants des applications OAuth.", + "prefs_open": "Ouvrir", + "prefs_open_github": "Ouvrir github.com", + "prefs_open_link_failed": "Impossible d'ouvrir le lien", + "prefs_open_logs": "Ouvrir le dossier des journaux", + "prefs_pinned_desc": "Les branches épinglées restent en haut de l'onglet Branches.", + "prefs_pinned_none": "Aucune branche épinglée. Épinglez-en une depuis l'onglet Branches.", + "prefs_prefer_https": "Préférer HTTPS", + "prefs_prefer_https_desc": "Activé : les remotes en http:// sont refusés. Désactivé : les remotes en https:// sont refusés.", + "prefs_proxy_desc": "Laissez un champ vide pour une connexion directe.", + "prefs_proxy_example": "http://proxy.example.com:8080", + "prefs_reopen_last": "Rouvrir le dernier dépôt au démarrage", + "prefs_reopen_last_desc": "Désactivé : GitSpace démarre sur l'écran d'ajout de dépôt.", + "prefs_reset": "Rétablir les valeurs par défaut", + "prefs_reset_confirm": "Rétablir toutes les préférences par défaut ? C'est irréversible.", + "prefs_reset_yes": "Rétablir", + "prefs_scan_folder": "Lister les dépôts de ce dossier", + "prefs_scan_folder_desc": "Ajoute à la barre latérale chaque dépôt situé un niveau plus bas.", + "prefs_section_client_ids": "Identifiants des applications OAuth", + "prefs_section_cloning": "Clonage", + "prefs_section_connection": "Connexion", + "prefs_section_fetch": "Récupération automatique", + "prefs_section_file": "Fichier de préférences", + "prefs_section_github": "Se connecter à GitHub", + "prefs_section_gitlab": "Se connecter à GitLab", + "prefs_section_language": "Langue", + "prefs_section_logs": "Journaux", + "prefs_section_pinned": "Branches épinglées", + "prefs_section_proxy": "Proxy", + "prefs_section_startup": "Démarrage", + "prefs_section_storage": "Stockage des tokens", + "prefs_section_token": "Ajouter un token", + "prefs_signin_cancelled": "Connexion annulée.", + "prefs_signin_done": "Connecté.", + "prefs_signin_failed": "Échec de la connexion : {error}", + "prefs_signin_saving": "Enregistrement du token…", + "prefs_source_code": "Code source", + "prefs_startup_desc": "Ce que GitSpace affiche au démarrage.", + "prefs_storage_desc": "Où les tokens sont enregistrés quand le trousseau du système ne peut pas les garder.", + "prefs_token_checking": "Vérification du token…", + "prefs_token_desc": "Un token d'accès personnel, pour les serveurs auto-hébergés ou quand OAuth n'est pas disponible.", + "prefs_token_empty": "Saisissez un hôte et un token.", + "prefs_token_host": "Hôte, par ex. github.com ou gitlab.example.com", + "prefs_token_rejected": "Le token a été refusé : {error}", + "prefs_token_save": "Valider et enregistrer", + "prefs_token_saved": "Token vérifié et enregistré.", + "prefs_token_store_failed": "Impossible d'enregistrer le token : {error}", + "prefs_token_value": "Token d'accès personnel", + "prefs_unpin": "Retirer", + "prefs_version": "Version", + "remote_pull_diverged": "Ce pull demande plus qu'une avance rapide. Fusionnez ou rebasez à la main.", + "remote_pull_not_checked_out": "Le pull ne met à jour que la branche extraite, et {branch} n'est pas extraite.", + "remote_push_not_checked_out": "Le push n'envoie que la branche extraite, et {branch} n'est pas extraite.", + "repo_missing_detail": "{path} n'existe plus ou n'est pas un dépôt Git.", + "repo_missing_title": "Dépôt introuvable", + "repo_no_work_tree": "le dépôt n'a pas d'arbre de travail", + "retry": "Réessayer", + "sidebar_add": "+ Cloner ou ouvrir", + "sidebar_hint": "Ctrl+K rechercher · Alt+↑↓ dépôt", + "sidebar_missing": "absent", + "sidebar_open_folder": "Ouvrir le dossier", + "sidebar_open_terminal": "Ouvrir un terminal", + "sidebar_pin": "Épingler", + "sidebar_pinned": "ÉPINGLÉS", + "sidebar_recent": "RÉCENTS", + "sidebar_remove": "Retirer de la liste", + "sidebar_repositories": "Dépôts · {count}", + "sidebar_results": "{count} RÉSULTATS", + "sidebar_results_one": "1 RÉSULTAT", + "sidebar_search_close": "Fermer la recherche (Échap)", + "sidebar_search_hint": "↑↓ choisir · Entrée ouvrir · Échap fermer", + "sidebar_search_placeholder": "Rechercher un dépôt", + "sidebar_search_tip": "Rechercher (Ctrl+K)", + "sidebar_unpin": "Désépingler", + "startup_migration_failed": "Impossible de déplacer vos réglages vers le nouveau dossier", + "startup_migration_failed_detail": "GitSpace utilise l'ancien dossier pour l'instant. {error}", + "stash_list_changed": "La liste des stashs a changé ; actualisez et réessayez.", + "stashes_actions": "Actions du stash", + "stashes_applied": "Stash #{index} appliqué", + "stashes_applied_conflicts": "Stash #{index} appliqué avec des conflits", + "stashes_applied_dropped": "Stash #{index} appliqué et supprimé", + "stashes_applied_not_dropped": "Le stash a été appliqué mais pas supprimé : {error}", + "stashes_apply": "Appliquer", + "stashes_apply_and_drop": "Appliquer et supprimer", + "stashes_apply_drop_failed": "Impossible d'appliquer et de supprimer le stash", + "stashes_apply_failed": "Impossible d'appliquer le stash", + "stashes_close_contents": "Fermer le contenu", + "stashes_conflicts_kept": "L'application a laissé des conflits, le stash a donc été conservé. Résolvez-les, puis supprimez le stash.", + "stashes_create": "Mettre de côté", + "stashes_create_failed": "Impossible de mettre les modifications de côté", + "stashes_created": "Modifications mises de côté", + "stashes_detached": "sur une HEAD détachée", + "stashes_drop": "Supprimer…", + "stashes_drop_button": "Supprimer", + "stashes_drop_confirm": "Supprimer le stash #{index} « {message} » ? Cette action est définitive.", + "stashes_drop_failed": "Impossible de supprimer le stash", + "stashes_dropped": "Stash #{index} supprimé", + "stashes_empty_detail": "Les modifications mises de côté restent ici jusqu'à ce que vous les appliquiez ou les supprimiez.", + "stashes_empty_title": "Aucun stash", + "stashes_files": "{count} fichiers", + "stashes_include_untracked": "Inclure les fichiers non suivis", + "stashes_load_failed": "Impossible de lire les stashs : {error}", + "stashes_message_placeholder": "Message du stash…", + "stashes_nothing_to_stash": "Aucune modification à mettre de côté.", + "stashes_on_branch": "sur {branch}", + "stashes_one_file": "1 fichier", + "stashes_select_file": "Choisissez un fichier pour voir ses modifications.", + "stashes_show_contents": "Voir le contenu", + "stashes_will_stash_many": "{count} fichiers modifiés seront mis de côté, la copie de travail redevient propre.", + "stashes_will_stash_one": "1 fichier modifié sera mis de côté, la copie de travail redevient propre.", + "tab_branches": "Branches", + "tab_changes": "Modifications", + "tab_history": "Historique", + "tab_stashes": "Stashs", + "time_days_ago": "il y a {count} jours", + "time_hours_ago": "il y a {count} h", + "time_just_now": "à l'instant", + "time_minutes_ago": "il y a {count} min", + "time_yesterday": "hier", + "token_check_failed": "La vérification auprès de {provider} a échoué : {error}", + "token_empty": "Le token ne peut pas être vide", + "token_host_not_https": "L'hôte doit utiliser https : GitSpace n'envoie jamais de token en HTTP simple.", + "token_https_remotes_only": "GitSpace n'envoie un token enregistré qu'aux remotes en https://.", + "token_invalid_characters": "Le token contient des caractères non valides", + "token_invalid_host": "Hôte non valide « {host} » : {error}", + "token_oauth_serialize_failed": "Impossible de sérialiser le token OAuth : {error}", + "token_rejected": "{provider} a refusé le token ({status}).", + "token_remote_plain_http": "Ce remote utilise HTTP simple : GitSpace n'y envoie jamais de token. Utilisez une URL de remote en https://.", + "token_too_long": "Le token est trop long ({count} caractères au maximum)", + "token_too_short": "Le token est trop court ({count} caractères au minimum)", + "tokens_encrypt_failed": "Impossible de chiffrer les tokens : {error}", + "tokens_serialize_failed": "Impossible de sérialiser les tokens : {error}" +} diff --git a/src/main.rs b/src/main.rs index 4707a0b..5b3af1e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,11 +4,13 @@ mod auth; mod config; mod error; mod git; +mod i18n; mod logging; +mod paths; mod ui; +use colony_ui::fonts; use ui::app::GitSpaceApp; -use ui::fonts; fn main() { // Answered before logging starts and before any window opens: the release @@ -22,16 +24,28 @@ fn main() { return; } + // Before logging starts: logging reads the config and opens the logs folder. + let migration = paths::init_at_startup(); logging::init_tracing(); log_dev_feature_flags(); + let migration_error = log_migration(migration); - let result = iced::application("GitSpace", GitSpaceApp::update, GitSpaceApp::view) + let result = fonts::BYTES + .into_iter() + .fold( + iced::application( + move || GitSpaceApp::new(migration_error.clone()), + GitSpaceApp::update, + GitSpaceApp::view, + ), + |app, font| app.font(font), + ) + .title("GitSpace") .subscription(GitSpaceApp::subscription) .theme(GitSpaceApp::theme) - .font(fonts::FONT_REGULAR) - .default_font(fonts::DEFAULT_FONT) + .default_font(colony_ui::ui_font()) .window_size((1280.0, 800.0)) - .run_with(GitSpaceApp::new); + .run(); if let Err(err) = result { tracing::error!(target: "gitspace::main", error = %err, "echec du lancement de l'interface GitSpace"); @@ -41,6 +55,21 @@ fn main() { } } +/// Logs the outcome of the legacy folder move and returns the error to show, if any. +fn log_migration(outcome: paths::MigrationOutcome) -> Option { + match outcome { + paths::MigrationOutcome::NothingToDo => None, + paths::MigrationOutcome::Moved(files) => { + tracing::info!(target: "gitspace::paths", count = files.len(), files = ?files, "moved files from the legacy gitspace folders"); + None + } + paths::MigrationOutcome::Failed { error } => { + tracing::error!(target: "gitspace::paths", %error, "could not move files from the legacy gitspace folders; using them for this run"); + Some(error) + } + } +} + fn log_dev_feature_flags() { #[cfg(feature = "mock-providers")] tracing::warn!( diff --git a/src/paths.rs b/src/paths.rs new file mode 100644 index 0000000..0616dba --- /dev/null +++ b/src/paths.rs @@ -0,0 +1,412 @@ +//! Where GitSpace keeps its files, and the one-time move from the old `gitspace` folders. +//! +//! Older builds kept settings in `/gitspace/` and logs in +//! `/gitspace/logs/`. They now live under `Colony/GitSpace/`, the layout every +//! Colony program shares (see [`colony_ui::paths`]). + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +const PROGRAM: &str = "GitSpace"; +const LEGACY_DIR: &str = "gitspace"; +const LOGS_DIR: &str = "logs"; +const CONFIG_FILE: &str = "config.json"; + +/// Files moved from the legacy settings folder, in move order. `config.json` goes last, so +/// a `config.json` in the new folder means the move finished. +const CONFIG_FILES: [&str; 6] = [ + "token-hosts.json", + "token-salt.bin", + "token-local-key.bin", + "tokens.enc", + "config.json.bak", + CONFIG_FILE, +]; + +static EFFECTIVE: OnceLock<(PathBuf, PathBuf)> = OnceLock::new(); + +/// The settings folder, `Colony/GitSpace/` in the platform config directory. +pub fn config_dir() -> PathBuf { + colony_ui::paths::config_dir(PROGRAM).unwrap_or_else(|_| legacy_root(dirs::config_dir())) +} + +/// The data folder, `Colony/GitSpace/` in the platform data directory. +pub fn data_dir() -> PathBuf { + colony_ui::paths::data_dir(PROGRAM).unwrap_or_else(|_| legacy_root(dirs::data_dir())) +} + +fn legacy_root(base: Option) -> PathBuf { + base.unwrap_or_else(|| PathBuf::from(".")).join(LEGACY_DIR) +} + +/// The folders older builds used. +#[derive(Debug, Clone)] +pub struct LegacyDirs { + pub config: PathBuf, + pub data: PathBuf, +} + +pub fn legacy_dirs() -> Option { + Some(LegacyDirs { + config: dirs::config_dir()?.join(LEGACY_DIR), + data: dirs::data_dir()?.join(LEGACY_DIR), + }) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MigrationOutcome { + NothingToDo, + /// The new paths of the files that were moved. + Moved(Vec), + Failed { + error: String, + }, +} + +/// Moves the legacy files into `config` and `data`, once. +/// +/// Safe to run again after a crash: a file already at its destination with the same bytes +/// only has its source removed. A destination holding different bytes stops the move before +/// anything is touched; an error during the move puts the files already moved back. +pub fn migrate_legacy(legacy: &LegacyDirs, config: &Path, data: &Path) -> MigrationOutcome { + if config.join(CONFIG_FILE).exists() || !legacy.config.join(CONFIG_FILE).exists() { + return MigrationOutcome::NothingToDo; + } + + let mut pairs: Vec<(PathBuf, PathBuf)> = Vec::new(); + let legacy_logs = legacy.data.join(LOGS_DIR); + let logs = data.join(LOGS_DIR); + if let Ok(entries) = fs::read_dir(&legacy_logs) { + for entry in entries.filter_map(Result::ok) { + if entry.file_type().is_ok_and(|kind| kind.is_file()) { + pairs.push((entry.path(), logs.join(entry.file_name()))); + } + } + } + for name in CONFIG_FILES { + pairs.push((legacy.config.join(name), config.join(name))); + } + + let result = (|| -> io::Result> { + for (from, to) in &pairs { + if from.exists() && to.exists() && fs::read(from)? != fs::read(to)? { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!("{} already exists with different content", to.display()), + )); + } + } + fs::create_dir_all(config)?; + if legacy_logs.is_dir() { + fs::create_dir_all(&logs)?; + } + let mut moved: Vec<(&Path, &Path)> = Vec::new(); + for (from, to) in &pairs { + match move_file(from, to) { + Ok(true) => moved.push((from, to)), + Ok(false) => {} + Err(err) => return Err(roll_back(&moved, err)), + } + } + // Best effort: leaves the folder in place if something unexpected is still inside. + let _ = fs::remove_dir(&legacy_logs); + Ok(moved.into_iter().map(|(_, to)| to.to_path_buf()).collect()) + })(); + + match result { + Ok(moved) => MigrationOutcome::Moved(moved), + Err(err) => MigrationOutcome::Failed { + error: err.to_string(), + }, + } +} + +/// Moves one file. Returns `false` when there was nothing to move. +fn move_file(from: &Path, to: &Path) -> io::Result { + if !from.exists() { + return Ok(false); + } + if to.exists() { + if fs::read(from)? != fs::read(to)? { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!("{} already exists with different content", to.display()), + )); + } + fs::remove_file(from)?; + return Ok(true); + } + rename_or_copy(from, to)?; + Ok(true) +} + +fn rename_or_copy(from: &Path, to: &Path) -> io::Result<()> { + match fs::rename(from, to) { + Err(err) if err.kind() == io::ErrorKind::CrossesDevices => copy_then_remove(from, to), + other => other, + } +} + +/// Puts the files already moved back in the legacy folder, newest first, so this run can +/// read everything from there and the next start begins the move again. +fn roll_back(moved: &[(&Path, &Path)], err: io::Error) -> io::Error { + let mut message = err.to_string(); + for (from, to) in moved.iter().rev() { + if let Err(back) = rename_or_copy(to, from) { + message.push_str(&format!( + "; could not move {} back to {}: {back}", + to.display(), + from.display() + )); + } + } + io::Error::new(err.kind(), message) +} + +/// The cross-filesystem move: copy to a temporary name, sync, keep the mode, rename into +/// place, then remove the source. A crash leaves at most a stray temporary file, never a +/// half-written destination. +fn copy_then_remove(from: &Path, to: &Path) -> io::Result<()> { + let mut temp_name = to.file_name().unwrap_or_default().to_os_string(); + temp_name.push(".moving"); + let temp = to.with_file_name(temp_name); + fs::copy(from, &temp)?; + let file = fs::OpenOptions::new().write(true).open(&temp)?; + file.set_permissions(fs::metadata(from)?.permissions())?; + file.sync_all()?; + drop(file); + fs::rename(&temp, to)?; + fs::remove_file(from) +} + +/// Runs the legacy move and fixes the folders for this run. Call once, before anything +/// reads a setting. +pub fn init_at_startup() -> MigrationOutcome { + let (config, data) = (config_dir(), data_dir()); + let outcome = match legacy_dirs() { + Some(legacy) if legacy.config != config => migrate_legacy(&legacy, &config, &data), + _ => MigrationOutcome::NothingToDo, + }; + let dirs = match (&outcome, legacy_dirs()) { + (MigrationOutcome::Failed { .. }, Some(legacy)) => (legacy.config, legacy.data), + _ => (config, data), + }; + let _ = EFFECTIVE.set(dirs); + outcome +} + +/// The settings and data folders every module reads, as fixed by [`init_at_startup`]. +pub fn effective_dirs() -> (PathBuf, PathBuf) { + EFFECTIVE.get_or_init(|| (config_dir(), data_dir())).clone() +} + +#[cfg(test)] +mod tests { + use super::*; + + struct Fixture { + _root: tempfile::TempDir, + legacy: LegacyDirs, + config: PathBuf, + data: PathBuf, + } + + fn fixture() -> Fixture { + let root = tempfile::tempdir().expect("tempdir"); + let legacy = LegacyDirs { + config: root.path().join("old-config/gitspace"), + data: root.path().join("old-data/gitspace"), + }; + fs::create_dir_all(&legacy.config).expect("legacy config"); + fs::create_dir_all(legacy.data.join(LOGS_DIR)).expect("legacy logs"); + Fixture { + config: root.path().join("new-config/Colony/GitSpace"), + data: root.path().join("new-data/Colony/GitSpace"), + legacy, + _root: root, + } + } + + fn write(path: &Path, bytes: &[u8]) { + fs::create_dir_all(path.parent().unwrap()).expect("parent"); + fs::write(path, bytes).expect("write"); + } + + #[cfg(unix)] + fn set_mode(path: &Path, mode: u32) { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(mode)).expect("chmod"); + } + + #[cfg(unix)] + fn mode(path: &Path) -> u32 { + use std::os::unix::fs::PermissionsExt; + fs::metadata(path).expect("metadata").permissions().mode() & 0o777 + } + + #[test] + fn moves_every_known_file_and_keeps_secret_permissions() { + let f = fixture(); + for name in CONFIG_FILES { + write(&f.legacy.config.join(name), name.as_bytes()); + } + #[cfg(unix)] + for name in ["tokens.enc", "token-local-key.bin", "token-salt.bin"] { + set_mode(&f.legacy.config.join(name), 0o600); + } + let log = f.legacy.data.join(LOGS_DIR).join("gitspace.log.2026-11-24"); + write(&log, b"{\"level\":\"info\"}"); + + let outcome = migrate_legacy(&f.legacy, &f.config, &f.data); + + let MigrationOutcome::Moved(moved) = outcome else { + panic!("expected Moved, got {outcome:?}"); + }; + let new_log = f.data.join(LOGS_DIR).join("gitspace.log.2026-11-24"); + assert!(moved.contains(&new_log), "{moved:?}"); + assert_eq!(fs::read(&new_log).expect("log"), b"{\"level\":\"info\"}"); + assert!(!log.exists()); + for name in CONFIG_FILES { + let new = f.config.join(name); + assert!(moved.contains(&new), "{name} missing from {moved:?}"); + assert_eq!(fs::read(&new).expect("moved file"), name.as_bytes()); + assert!(!f.legacy.config.join(name).exists(), "{name} left behind"); + } + #[cfg(unix)] + assert_eq!(mode(&f.config.join("tokens.enc")), 0o600); + } + + #[test] + fn does_nothing_when_the_new_config_exists() { + let f = fixture(); + write(&f.legacy.config.join(CONFIG_FILE), b"old"); + write(&f.legacy.config.join("tokens.enc"), b"old tokens"); + write(&f.config.join(CONFIG_FILE), b"new"); + + assert_eq!( + migrate_legacy(&f.legacy, &f.config, &f.data), + MigrationOutcome::NothingToDo + ); + assert_eq!(fs::read(f.legacy.config.join(CONFIG_FILE)).unwrap(), b"old"); + assert!(f.legacy.config.join("tokens.enc").exists()); + assert!(!f.config.join("tokens.enc").exists()); + } + + #[test] + fn does_nothing_without_a_legacy_config() { + let f = fixture(); + write(&f.legacy.config.join("tokens.enc"), b"tokens"); + + assert_eq!( + migrate_legacy(&f.legacy, &f.config, &f.data), + MigrationOutcome::NothingToDo + ); + assert!(f.legacy.config.join("tokens.enc").exists()); + } + + #[test] + fn resumes_after_a_partial_move() { + let f = fixture(); + write(&f.legacy.config.join("tokens.enc"), b"tokens"); + write(&f.config.join("tokens.enc"), b"tokens"); + write(&f.legacy.config.join(CONFIG_FILE), b"{}"); + + let outcome = migrate_legacy(&f.legacy, &f.config, &f.data); + + assert!(matches!(outcome, MigrationOutcome::Moved(_)), "{outcome:?}"); + assert_eq!(fs::read(f.config.join("tokens.enc")).unwrap(), b"tokens"); + assert_eq!(fs::read(f.config.join(CONFIG_FILE)).unwrap(), b"{}"); + assert!(!f.legacy.config.join("tokens.enc").exists()); + assert!(!f.legacy.config.join(CONFIG_FILE).exists()); + } + + #[test] + fn refuses_to_overwrite_a_different_file() { + let f = fixture(); + write(&f.legacy.config.join(CONFIG_FILE), b"{}"); + write(&f.legacy.config.join("token-hosts.json"), b"[]"); + write(&f.legacy.config.join("tokens.enc"), b"old tokens"); + write(&f.config.join("tokens.enc"), b"other tokens"); + + let outcome = migrate_legacy(&f.legacy, &f.config, &f.data); + + assert!( + matches!(outcome, MigrationOutcome::Failed { .. }), + "{outcome:?}" + ); + assert_eq!( + fs::read(f.legacy.config.join("tokens.enc")).unwrap(), + b"old tokens" + ); + assert_eq!( + fs::read(f.config.join("tokens.enc")).unwrap(), + b"other tokens" + ); + assert!(f.legacy.config.join(CONFIG_FILE).exists()); + assert!(f.legacy.config.join("token-hosts.json").exists()); + assert!(!f.config.join("token-hosts.json").exists()); + } + + /// The failure comes after three files have moved: renaming a directory onto a dangling + /// symlink fails with ENOTDIR, while the pre-check sees no destination. + #[cfg(unix)] + #[test] + fn a_failure_midway_puts_every_moved_file_back() { + let f = fixture(); + let earlier = ["token-hosts.json", "token-salt.bin", "token-local-key.bin"]; + for name in earlier.into_iter().chain([CONFIG_FILE]) { + write(&f.legacy.config.join(name), name.as_bytes()); + } + fs::create_dir_all(f.legacy.config.join("tokens.enc")).unwrap(); + fs::create_dir_all(&f.config).unwrap(); + std::os::unix::fs::symlink(f.config.join("missing"), f.config.join("tokens.enc")).unwrap(); + let log = f.legacy.data.join(LOGS_DIR).join("gitspace.log.2026-11-24"); + write(&log, b"log"); + + let outcome = migrate_legacy(&f.legacy, &f.config, &f.data); + + assert!( + matches!(outcome, MigrationOutcome::Failed { .. }), + "{outcome:?}" + ); + for name in earlier.into_iter().chain([CONFIG_FILE]) { + assert_eq!( + fs::read(f.legacy.config.join(name)).unwrap(), + name.as_bytes(), + "{name} not back in the legacy folder" + ); + assert!( + !f.config.join(name).exists(), + "{name} left in the new folder" + ); + } + assert_eq!(fs::read(&log).unwrap(), b"log"); + assert!(!f + .data + .join(LOGS_DIR) + .join("gitspace.log.2026-11-24") + .exists()); + } + + /// `rename` cannot cross filesystems in a test, so the fallback is checked directly. + #[test] + fn the_cross_filesystem_copy_keeps_bytes_and_mode() { + let f = fixture(); + let from = f.legacy.config.join("tokens.enc"); + write(&from, b"secret"); + #[cfg(unix)] + set_mode(&from, 0o600); + let to = f.config.join("tokens.enc"); + fs::create_dir_all(&f.config).unwrap(); + + copy_then_remove(&from, &to).expect("copy"); + + assert_eq!(fs::read(&to).unwrap(), b"secret"); + assert!(!from.exists()); + assert!(!f.config.join("tokens.enc.moving").exists()); + #[cfg(unix)] + assert_eq!(mode(&to), 0o600); + } +} diff --git a/src/ui/add_repo.rs b/src/ui/add_repo.rs new file mode 100644 index 0000000..24863f5 --- /dev/null +++ b/src/ui/add_repo.rs @@ -0,0 +1,1336 @@ +//! The Add repository screen: search GitHub or GitLab, paste a URL, or pick a local +//! folder. Searches, clones and the folder check run in background tasks; `view` only +//! reads the panel's state. + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::time::Instant; + +use colony_ui::theme::Palette; +use colony_ui::Typography; +use iced::futures::{SinkExt, Stream}; +use iced::widget::Column; +use iced::widget::{button, column, container, progress_bar, row, scrollable, text, text_input}; +use iced::{Alignment, Border, Element, Length, Task}; +use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT}; +use reqwest::Client; +use reqwest::StatusCode; +use serde::Deserialize; +use url::Url; + +use crate::auth::AuthManager; +use crate::config::NetworkOptions; +use crate::error::AppError; +use crate::git::clone::{clone_repository, CloneProgress, CloneRequest}; +use crate::i18n::{t, tf}; +use crate::ui::changes::{field, horizontal_divider}; +use crate::ui::context::RepoContext; +use crate::ui::history::{avatar, avatar_accent, initials, relative_time}; +use crate::ui::widgets::button as gs_button; +use crate::ui::widgets::chip::{chip, Tone}; +use crate::ui::widgets::segmented::segmented; + +/// Where the repository comes from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Source { + GitHub, + GitLab, + Url, + LocalFolder, +} + +impl Source { + const ALL: [Source; 4] = [ + Source::GitHub, + Source::GitLab, + Source::Url, + Source::LocalFolder, + ]; + + fn label(self) -> &'static str { + match self { + Source::GitHub => t("add_repo_github"), + Source::GitLab => t("add_repo_gitlab"), + Source::Url => t("add_repo_url"), + Source::LocalFolder => t("add_repo_local_folder"), + } + } + + /// The host searched, for the sources that search one. + fn host(self) -> Option<&'static str> { + match self { + Source::GitHub => Some("github.com"), + Source::GitLab => Some("gitlab.com"), + Source::Url | Source::LocalFolder => None, + } + } +} + +/// A repository found by a search. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RemoteRepo { + /// "owner/name" on GitHub, "Group / Name" on GitLab. + pub name: String, + pub url: String, + pub description: Option, + /// Unknown for GitLab, whose short project listing leaves it out. + pub private: Option, + pub stars: u64, + /// Last update, in seconds since the epoch. + pub updated: Option, +} + +impl RemoteRepo { + /// The owner and the repository name, split at the last "/". + fn owner_and_name(&self) -> (&str, &str) { + match self.name.rsplit_once('/') { + Some((owner, name)) => (owner.trim(), name.trim()), + None => ("", self.name.as_str()), + } + } +} + +#[derive(Debug, Clone)] +pub enum Message { + SelectSource(Source), + QueryChanged(String), + /// Searches now, without waiting for the typing pause. + Search, + /// The typing pause of search `version` is over. + DebouncedSearch(u32), + SearchResult(u32, Result, AppError>), + SelectRepo(usize), + UrlChanged(String), + DestinationChanged(String), + ChooseDestination, + DestinationChosen(Option), + StartClone, + CloneProgress(CloneProgress), + CloneResult(Result<(), AppError>), + /// A display frame while the progress bar eases toward the clone's progress. + Frame, + RetryClone, + ChooseFolder, + FolderChosen(Option), + /// The picked folder, and whether it holds a repository. + FolderChecked(PathBuf, bool), + /// Opens Preferences → Accounts; `app.rs` routes it. + OpenAccounts, +} + +pub struct AddRepoPanel { + source: Source, + query: String, + /// The URL typed for the URL source. + url: String, + destination: String, + /// The folder the repository name is appended to: the default clone folder, or the + /// one picked with Browse. + base_destination: PathBuf, + results: Vec, + selected: Option, + search_status: Option, + progress: Option, + /// The ratio the bar shows while it eases toward the clone's progress. + shown_ratio: f32, + /// Bytes per second since the clone started. + speed: f64, + started: Option, + cloning: bool, + active_destination: Option, + last_request: Option, + network: NetworkOptions, + /// Each keystroke, search or source change bumps it; only the current version's pause + /// and result are applied. + search_version: u32, + checking_folder: bool, + folder_error: Option, +} + +impl AddRepoPanel { + pub fn new(default_destination: String, network: NetworkOptions) -> Self { + Self { + source: Source::GitHub, + query: String::new(), + url: String::new(), + base_destination: PathBuf::from(&default_destination), + destination: default_destination, + results: Vec::new(), + selected: None, + search_status: None, + progress: None, + shown_ratio: 0.0, + speed: 0.0, + started: None, + cloning: false, + active_destination: None, + last_request: None, + network, + search_version: 0, + checking_folder: false, + folder_error: None, + } + } + + /// Whether `version` is the search in progress, not one it replaced. + pub fn is_current_search(&self, version: u32) -> bool { + version == self.search_version + } + + pub fn set_default_destination(&mut self, destination: String) { + self.base_destination = PathBuf::from(destination); + self.refresh_destination(); + } + + /// Whether the progress bar still has to ease toward the clone's progress. + pub fn is_easing(&self) -> bool { + self.cloning + && colony_ui::effects_enabled() + && self.shown_ratio != progress_ratio(self.progress.as_ref()) + } + + pub fn set_network_preferences(&mut self, network: NetworkOptions) { + self.network = network; + } + + /// Handles `message`; the path is set once a repository was cloned or a folder opened. + pub fn update( + &mut self, + message: Message, + auth: &AuthManager, + ) -> (Task, Option) { + match message { + Message::SelectSource(source) => { + self.source = source; + self.results.clear(); + self.selected = None; + self.search_status = None; + self.folder_error = None; + // Drops the search still running on the previous source. + self.search_version += 1; + self.refresh_destination(); + } + Message::QueryChanged(query) => { + self.query = query; + self.search_status = None; + self.search_version += 1; + let version = self.search_version; + let pause = Task::perform( + async move { + tokio::time::sleep(std::time::Duration::from_millis(250)).await; + version + }, + Message::DebouncedSearch, + ); + return (pause, None); + } + Message::Search => return (self.start_search(auth), None), + Message::DebouncedSearch(version) => { + if self.is_current_search(version) { + return (self.start_search(auth), None); + } + } + Message::SearchResult(version, result) => self.apply_search_result(version, result), + Message::SelectRepo(index) => { + if index < self.results.len() { + self.selected = Some(index); + self.refresh_destination(); + } + } + Message::UrlChanged(url) => { + self.url = url; + self.refresh_destination(); + } + Message::DestinationChanged(destination) => self.destination = destination, + Message::ChooseDestination => { + let start = self.base_destination.display().to_string(); + return ( + pick_folder(Some(start)).map(Message::DestinationChosen), + None, + ); + } + Message::DestinationChosen(Some(folder)) => { + self.base_destination = PathBuf::from(folder); + self.refresh_destination(); + } + Message::DestinationChosen(None) | Message::FolderChosen(None) => {} + Message::StartClone => { + let Some(url) = self.clone_url() else { + return (Task::none(), None); + }; + // The token is resolved inside the clone task. + let request = CloneRequest { + url: url.trim().to_string(), + destination: PathBuf::from(self.destination.trim()), + token: None, + network: self.network.clone(), + }; + return (self.begin_clone(request, auth), None); + } + Message::CloneProgress(progress) => { + if let Some(started) = self.started { + let seconds = started.elapsed().as_secs_f64(); + if seconds > 0.0 { + self.speed = progress.received_bytes as f64 / seconds; + } + } + self.progress = Some(progress); + } + Message::Frame => self.ease_progress(), + Message::CloneResult(result) => { + self.cloning = false; + self.progress = None; + let destination = self.active_destination.take(); + if result.is_ok() { + return (Task::none(), destination); + } + } + Message::RetryClone => { + if let (false, Some(request)) = (self.cloning, self.last_request.clone()) { + return (self.begin_clone(request, auth), None); + } + } + Message::ChooseFolder => { + return (pick_folder(None).map(Message::FolderChosen), None); + } + Message::FolderChosen(Some(folder)) => { + self.checking_folder = true; + self.folder_error = None; + let path = PathBuf::from(folder); + let check = Task::perform( + async move { + let candidate = path.clone(); + let is_repo = + tokio::task::spawn_blocking(move || is_repository(&candidate)) + .await + .unwrap_or(false); + (path, is_repo) + }, + |(path, is_repo)| Message::FolderChecked(path, is_repo), + ); + return (check, None); + } + Message::FolderChecked(path, is_repo) => { + return (Task::none(), self.apply_folder_check(path, is_repo)); + } + // Handled by `app.rs` before it reaches the panel. + Message::OpenAccounts => {} + } + (Task::none(), None) + } + + /// Moves the bar a fifth of the way to the clone's progress; snaps when close, or back + /// when a new phase restarts at 0. + fn ease_progress(&mut self) { + let target = progress_ratio(self.progress.as_ref()); + let gap = target - self.shown_ratio; + self.shown_ratio = if gap < 0.002 { + target + } else { + self.shown_ratio + gap * 0.2 + }; + } + + /// Returns the folder to open when it holds a repository; otherwise says why not. + fn apply_folder_check(&mut self, path: PathBuf, is_repo: bool) -> Option { + self.checking_folder = false; + if is_repo { + return Some(path); + } + self.folder_error = Some(tf( + "add_repo_not_a_repo", + &[("path", &path.display().to_string())], + )); + None + } + + /// The URL "Clone" uses: the selected result, or the typed URL. + fn clone_url(&self) -> Option<&str> { + let url = match self.source { + Source::GitHub | Source::GitLab => &self.results.get(self.selected?)?.url, + Source::Url => &self.url, + Source::LocalFolder => return None, + }; + (!url.trim().is_empty()).then_some(url.as_str()) + } + + /// Sets the destination to the base folder plus the name of the repository to clone. + fn refresh_destination(&mut self) { + let base = &self.base_destination; + self.destination = match self.clone_url().and_then(repo_name_from_url) { + Some(name) => base.join(name), + None => base.clone(), + } + .display() + .to_string(); + } + + /// Searches the current query under a new version. The token is read in the task: the + /// keyring can block. + fn start_search(&mut self, auth: &AuthManager) -> Task { + let query = self.query.trim().to_string(); + let Some(host) = self.source.host() else { + return Task::none(); + }; + if query.len() < 2 { + return Task::none(); + } + self.search_version += 1; + let version = self.search_version; + let source = self.source; + let network = self.network.clone(); + let auth = auth.clone(); + self.search_status = Some(t("add_repo_searching").to_string()); + + Task::perform( + async move { + let host_url = format!("https://{host}"); + let token = tokio::task::spawn_blocking(move || auth.resolve_for_url(&host_url)) + .await + .ok() + .flatten(); + search_repositories(source, &query, token.as_deref(), network).await + }, + move |result| Message::SearchResult(version, result), + ) + } + + /// Applies a search result, unless it answers a replaced search. + fn apply_search_result(&mut self, version: u32, result: Result, AppError>) { + if !self.is_current_search(version) { + return; + } + match result { + Ok(results) => { + self.search_status = results + .is_empty() + .then(|| t("add_repo_no_results").to_string()); + self.selected = (!results.is_empty()).then_some(0); + self.results = results; + self.refresh_destination(); + } + Err(err) => self.search_status = Some(err.user_message()), + } + } + + fn begin_clone(&mut self, request: CloneRequest, auth: &AuthManager) -> Task { + self.last_request = Some(request.clone()); + self.active_destination = Some(request.destination.clone()); + self.progress = None; + self.shown_ratio = 0.0; + self.speed = 0.0; + self.started = Some(Instant::now()); + self.cloning = true; + Task::run( + clone_with_progress(request, auth.clone()), + std::convert::identity, + ) + } + + // ----------------------------------------------------------------------- + // View + // ----------------------------------------------------------------------- + + /// The screen; `is_connected(host)` tells whether an account is signed in there. + pub fn view(&self, is_connected: impl Fn(&str) -> bool) -> Element<'_, Message> { + let typo = Typography::current(); + let labels: Vec = Source::ALL.iter().map(|s| s.label().to_string()).collect(); + let selected = Source::ALL + .iter() + .position(|&source| source == self.source) + .unwrap_or(0); + let mut content = column![ + text(t("add_repo_title")) + .size(typo.sz(19)) + .font(typo.bold) + .color(Palette::TEXT_PRIMARY()), + segmented(&labels, selected, |index| Message::SelectSource( + Source::ALL[index] + )), + ] + .spacing(14); + + content = match self.source { + Source::GitHub | Source::GitLab => { + let signed_in = self.source.host().is_some_and(is_connected); + content.push(self.search_view(signed_in)) + } + Source::Url => content.push(field( + text_input(t("add_repo_url_placeholder"), &self.url).on_input(Message::UrlChanged), + None, + )), + Source::LocalFolder => content.push(self.folder_view()), + }; + if self.source != Source::LocalFolder { + content = content.push(self.destination_row()); + if self.cloning { + content = content.push(self.progress_view()); + } + } + container(content.padding([22, 28])) + .width(Length::Fill) + .height(Length::Fill) + .into() + } + + /// The search field, the signed-out line, then the results. + fn search_view(&self, signed_in: bool) -> Element<'_, Message> { + let placeholder = if self.source == Source::GitHub { + t("add_repo_search_github") + } else { + t("add_repo_search_gitlab") + }; + let mut body = column![field( + text_input(placeholder, &self.query) + .on_input(Message::QueryChanged) + .on_submit(Message::Search), + None, + )] + .spacing(10); + if !signed_in { + body = body.push( + row![ + dim_line(t("add_repo_signed_out").to_string()), + gs_button::ghost(t("add_repo_connect"), Some(Message::OpenAccounts)), + ] + .spacing(8) + .align_y(Alignment::Center), + ); + } + if let Some(status) = &self.search_status { + body = body.push(dim_line(status.clone())); + } + if !self.results.is_empty() { + body = body.push(self.results_view()); + } + body.height(Length::Fill).into() + } + + /// One row per result, separated by rules, in a bordered box. + fn results_view(&self) -> Element<'_, Message> { + let now = chrono::Utc::now().timestamp(); + let mut rows = Column::new(); + for (index, repo) in self.results.iter().enumerate() { + if index > 0 { + rows = rows.push(horizontal_divider()); + } + rows = rows.push(self.result_row(index, repo, now)); + } + container(scrollable(rows)) + .style(|_| container::Style { + border: Border::default() + .rounded(10) + .width(1) + .color(Palette::DIVIDER()), + ..Default::default() + }) + .into() + } + + /// Owner initials, "owner / name" over the description, visibility, stars and date. + fn result_row<'a>(&self, index: usize, repo: &'a RemoteRepo, now: i64) -> Element<'a, Message> { + let typo = Typography::current(); + let (owner, name) = repo.owner_and_name(); + let mut title = row![].spacing(0); + if !owner.is_empty() { + title = title.push( + text(format!("{owner} / ")) + .size(typo.sz(13)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + ); + } + title = title.push( + text(name.to_string()) + .size(typo.sz(13)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()), + ); + let mut details = column![title].spacing(2).width(Length::Fill); + if let Some(description) = repo.description.as_deref().filter(|d| !d.is_empty()) { + details = details.push( + container( + text(description.to_string()) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()) + .wrapping(text::Wrapping::None), + ) + .width(Length::Fill) + .clip(true), + ); + } + let mut line = row![ + avatar(&initials(owner), avatar_accent(owner), 28.0), + details + ] + .spacing(12) + .align_y(Alignment::Center); + if let Some(private) = repo.private { + let label = if private { + t("add_repo_private") + } else { + t("add_repo_public") + }; + line = line.push(chip(label, Tone::Neutral)); + } + let mut meta = vec![format!("★ {}", repo.stars)]; + if let Some(updated) = repo.updated { + meta.push(relative_time(updated, now)); + } + line = line.push(dim_line(meta.join(" · "))); + + let is_selected = self.selected == Some(index); + button(line) + .padding([10, 14]) + .width(Length::Fill) + .on_press(Message::SelectRepo(index)) + .style(move |_, status| { + let lit = is_selected || matches!(status, button::Status::Hovered); + button::Style { + background: lit.then(|| Palette::BG_CARD_HOVER().into()), + text_color: Palette::TEXT_PRIMARY(), + ..Default::default() + } + }) + .into() + } + + /// The folder picker, with the reason a folder was refused. + fn folder_view(&self) -> Element<'_, Message> { + let mut body = column![ + dim_line(t("add_repo_folder_hint").to_string()), + gs_button::primary( + t("add_repo_choose_folder"), + (!self.checking_folder).then_some(Message::ChooseFolder), + ), + ] + .spacing(10); + if let Some(error) = &self.folder_error { + let typo = Typography::current(); + body = body.push( + text(error.clone()) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::ERROR()), + ); + } + body.into() + } + + /// "In", the destination field, Browse and Clone. + fn destination_row(&self) -> Element<'_, Message> { + let can_clone = + !self.cloning && self.clone_url().is_some() && !self.destination.trim().is_empty(); + container( + row![ + dim_line(t("add_repo_in").to_string()), + field( + text_input("", &self.destination).on_input(Message::DestinationChanged), + None, + ), + gs_button::secondary( + t("add_repo_browse"), + (!self.cloning).then_some(Message::ChooseDestination), + ), + gs_button::primary( + t("add_repo_clone"), + can_clone.then_some(Message::StartClone) + ), + ] + .spacing(8) + .align_y(Alignment::Center), + ) + .padding(12) + .width(Length::Fill) + .style(|_| container::Style { + background: Some(Palette::BG_SIDEBAR().into()), + border: Border::default().rounded(10), + ..Default::default() + }) + .into() + } + + /// The bar and "Receiving objects · a / b · size · speed", then the delta count. + fn progress_view(&self) -> Element<'_, Message> { + let label = match &self.progress { + None => t("add_repo_starting").to_string(), + Some(p) if is_resolving(p) => tf( + "add_repo_resolving", + &[ + ("done", &p.indexed_deltas.to_string()), + ("total", &p.total_deltas.to_string()), + ], + ), + Some(p) => tf( + "add_repo_receiving", + &[ + ("done", &p.received_objects.to_string()), + ("total", &p.total_objects.to_string()), + ("size", &format_size(p.received_bytes as f64)), + ( + "speed", + &tf("add_repo_per_second", &[("size", &format_size(self.speed))]), + ), + ], + ), + }; + let ratio = if colony_ui::effects_enabled() { + self.shown_ratio + } else { + progress_ratio(self.progress.as_ref()) + }; + let bar = progress_bar(0.0..=1.0, ratio) + .girth(6) + .style(|_| progress_bar::Style { + background: Palette::BG_CARD_HOVER().into(), + bar: Palette::ACCENT().into(), + border: Border::default().rounded(3), + }); + column![bar, dim_line(label)].spacing(6).into() + } +} + +/// Receiving is done and the deltas are being resolved. +fn is_resolving(p: &CloneProgress) -> bool { + p.total_deltas > 0 && p.received_objects >= p.total_objects +} + +/// How far the current clone phase is, from 0 to 1. +fn progress_ratio(progress: Option<&CloneProgress>) -> f32 { + match progress { + None => 0.0, + Some(p) if is_resolving(p) => p.indexed_deltas as f32 / p.total_deltas as f32, + Some(p) => p.received_objects as f32 / p.total_objects.max(1) as f32, + } +} + +fn dim_line<'a>(label: String) -> Element<'a, Message> { + let typo = Typography::current(); + text(label) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()) + .into() +} + +/// "812 KB", "18.4 MB", "1.2 GB", with the locale's decimal mark. +fn format_size(bytes: f64) -> String { + const KB: f64 = 1024.0; + let (value, key) = if bytes >= KB * KB * KB { + (bytes / (KB * KB * KB), "add_repo_size_gb") + } else if bytes >= KB * KB { + (bytes / (KB * KB), "add_repo_size_mb") + } else { + (bytes / KB, "add_repo_size_kb") + }; + let value = format!("{value:.1}").replace('.', t("add_repo_decimal_mark")); + tf(key, &[("value", &value)]) +} + +/// Whether `path` holds a Git repository. Blocking: run it off the UI thread. +fn is_repository(path: &Path) -> bool { + RepoContext::from_path(path).is_some() +} + +/// Opens the native folder picker off the UI thread, in `start` when given. +fn pick_folder(start: Option) -> Task> { + Task::perform( + async move { + tokio::task::spawn_blocking(move || { + let mut dialog = rfd::FileDialog::new(); + if let Some(start) = start { + dialog = dialog.set_directory(start); + } + dialog.pick_folder().map(|p| p.display().to_string()) + }) + .await + .ok() + .flatten() + }, + std::convert::identity, + ) +} + +// --------------------------------------------------------------------------- +// Fonctions utilitaires (extraction du nom de dépôt depuis une URL) +// --------------------------------------------------------------------------- + +/// Extrait le nom du dépôt depuis une URL (HTTPS ou SSH). +fn repo_name_from_url(repo_url: &str) -> Option { + let trimmed = repo_url.trim().trim_end_matches('/'); + if let Ok(url) = Url::parse(trimmed) { + if let Some(segment) = url + .path_segments() + .and_then(|mut segments| segments.rfind(|s| !s.is_empty())) + { + let name = segment.trim_end_matches(".git"); + if !name.is_empty() { + return Some(name.to_string()); + } + } + } + + let mut candidate = trimmed; + if let Some(idx) = trimmed.rfind(':') { + candidate = &trimmed[idx + 1..]; + } + + if let Some(idx) = candidate.rfind('/') { + candidate = &candidate[idx + 1..]; + } + + let name = candidate.trim_end_matches(".git"); + if name.is_empty() { + None + } else { + Some(name.to_string()) + } +} + +// --------------------------------------------------------------------------- +// Fonctions réseau — identiques à l'original +// --------------------------------------------------------------------------- + +/// Lance la recherche sur le fournisseur approprié. +async fn search_repositories( + source: Source, + query: &str, + token: Option<&str>, + network: NetworkOptions, +) -> Result, AppError> { + match source { + Source::GitLab => search_gitlab(query, token, &network).await, + _ => search_github(query, token, &network).await, + } +} + +/// Construit un client HTTP avec les en-têtes nécessaires (auth, proxy, timeout). +/// Le token part en `Authorization: Bearer`, que GitHub et GitLab acceptent pour un token +/// OAuth comme pour un jeton d'accès personnel. +async fn client_with_headers( + token: Option<&str>, + header: Option<(&'static str, &'static str)>, + network: &NetworkOptions, +) -> Result { + let mut headers = HeaderMap::new(); + headers.insert( + USER_AGENT, + HeaderValue::from_str("gitspace-ui/0.1") + .map_err(|err| AppError::Validation(err.to_string()))?, + ); + if let Some(token) = token { + let auth_value = HeaderValue::from_str(&format!("Bearer {token}")) + .map_err(|err| AppError::Validation(err.to_string()))?; + headers.insert(AUTHORIZATION, auth_value); + } + if let Some((key, value)) = header { + headers.insert( + key, + HeaderValue::from_str(value).map_err(|err| AppError::Validation(err.to_string()))?, + ); + } + let mut builder = + Client::builder() + .default_headers(headers) + .timeout(std::time::Duration::from_secs( + network.network_timeout_secs.max(1), + )); + + if !network.http_proxy.is_empty() { + builder = builder.proxy( + reqwest::Proxy::http(&network.http_proxy) + .map_err(|err| AppError::Validation(err.to_string()))?, + ); + } + + if !network.https_proxy.is_empty() { + builder = builder.proxy( + reqwest::Proxy::https(&network.https_proxy) + .map_err(|err| AppError::Validation(err.to_string()))?, + ); + } + + builder.build().map_err(AppError::from) +} + +/// Vérifie que l'URL respecte la politique HTTPS configurée. +fn enforce_https_policy(url: &str, network: &NetworkOptions) -> Result<(), AppError> { + if url.starts_with("https://") && !network.use_https { + return Err(AppError::Validation(t("network_https_blocked").to_string())); + } + + if url.starts_with("http://") && network.use_https { + return Err(AppError::Validation(t("network_http_blocked").to_string())); + } + + Ok(()) +} + +// --- Structures de désérialisation GitHub --- + +#[derive(Debug, Deserialize)] +struct GithubRepoItem { + full_name: String, + html_url: String, + #[serde(default)] + description: Option, + #[serde(default)] + private: bool, + #[serde(default)] + stargazers_count: u64, + #[serde(default)] + updated_at: Option, +} + +#[derive(Debug, Deserialize)] +struct GithubSearchResponse { + items: Vec, +} + +/// Recherche GitHub : d'abord les dépôts du compte connecté et de ses organisations qui +/// correspondent à la requête, puis la recherche publique. +async fn search_github( + query: &str, + token: Option<&str>, + network: &NetworkOptions, +) -> Result, AppError> { + let query = query.trim(); + if query.is_empty() { + return Ok(Vec::new()); + } + + let client = client_with_headers(token, None, network).await?; + let mut unique = HashSet::new(); + + let mut parts = Vec::new(); + if token.is_some() { + parts.push( + fetch_github_repos( + &client, + "https://api.github.com/user/repos", + &[ + ("visibility", "all"), + ("affiliation", "owner,collaborator,organization_member"), + ], + network, + ) + .await + .map(|repos| { + repos + .into_iter() + .filter(|repo| matches_query(repo, query)) + .collect() + }), + ); + } + parts.push(search_github_public(&client, query, network).await); + // Une requête refusée (limite de débit, réseau) ne masque pas les résultats des autres. + let repositories = merge_partial_results(parts)?; + + let results = repositories + .into_iter() + .filter(|repo| unique.insert(repo.full_name.clone())) + .map(|item| RemoteRepo { + name: item.full_name, + url: item.html_url, + description: item.description, + private: Some(item.private), + stars: item.stargazers_count, + updated: item.updated_at.as_deref().and_then(timestamp), + }) + .collect(); + + Ok(results) +} + +// --- Structure de désérialisation GitLab --- + +#[derive(Debug, Deserialize)] +struct GitlabProject { + name_with_namespace: String, + http_url_to_repo: String, + #[serde(default)] + description: Option, + #[serde(default)] + star_count: u64, + #[serde(default)] + last_activity_at: Option, + /// "public", "internal" or "private". + #[serde(default)] + visibility: Option, +} + +impl GitlabProject { + fn into_repo(self) -> RemoteRepo { + RemoteRepo { + name: self.name_with_namespace, + url: self.http_url_to_repo, + description: self.description, + // Without a token GitLab sends no visibility and lists only public projects. + // Internal projects need a GitLab account, so they show as private. + private: Some(self.visibility.is_some_and(|v| v != "public")), + stars: self.star_count, + updated: self.last_activity_at.as_deref().and_then(timestamp), + } + } +} + +/// Recherche les projets GitLab correspondant à la requête. +async fn search_gitlab( + query: &str, + token: Option<&str>, + network: &NetworkOptions, +) -> Result, AppError> { + let base_url = "https://gitlab.com/api/v4/projects"; + enforce_https_policy(base_url, network)?; + let client = client_with_headers(token, Some(("Accept", "application/json")), network).await?; + + let mut all_projects = Vec::new(); + let per_page = 100; + + for page in 1..=10 { + let response = client + .get(base_url) + .query(&[ + ("search", query), + ("per_page", &per_page.to_string()), + ("page", &page.to_string()), + ]) + .send() + .await + .map_err(AppError::from)?; + + if !response.status().is_success() { + if page == 1 { + // error_for_status() renvoie Err quand le statut n'est pas un succès + match response.error_for_status() { + Err(err) => return Err(AppError::from(err)), + Ok(_) => { + return Err(AppError::Network( + t("add_repo_gitlab_unexpected").to_string(), + )) + } + } + } + break; + } + + let projects: Vec = response.json().await.map_err(AppError::from)?; + let count = projects.len(); + all_projects.extend(projects); + + if count < per_page { + break; + } + } + + Ok(all_projects + .into_iter() + .map(GitlabProject::into_repo) + .collect()) +} + +/// Vrai quand la requête apparaît dans "owner/name" ou la description, sans tenir compte de la +/// casse. +fn matches_query(repo: &GithubRepoItem, query: &str) -> bool { + let query = query.to_lowercase(); + repo.full_name.to_lowercase().contains(&query) + || repo + .description + .as_deref() + .is_some_and(|description| description.to_lowercase().contains(&query)) +} + +/// Recherche publique GitHub, première page de 100 résultats. +async fn search_github_public( + client: &Client, + query: &str, + network: &NetworkOptions, +) -> Result, AppError> { + let url = "https://api.github.com/search/repositories"; + enforce_https_policy(url, network)?; + let response: GithubSearchResponse = client + .get(url) + .query(&[("q", query), ("per_page", "100")]) + .send() + .await? + .error_for_status()? + .json() + .await?; + Ok(response.items) +} + +/// Réunit les résultats de plusieurs requêtes : les réponses obtenues sont gardées, et la +/// première erreur n'est renvoyée que si aucune requête n'a abouti. +fn merge_partial_results( + parts: impl IntoIterator, AppError>>, +) -> Result, AppError> { + let mut items = Vec::new(); + let mut first_error = None; + let mut any_ok = false; + for part in parts { + match part { + Ok(part) => { + any_ok = true; + items.extend(part); + } + Err(err) => { + first_error.get_or_insert(err); + } + } + } + match first_error { + Some(err) if !any_ok => Err(err), + _ => Ok(items), + } +} + +/// Seconds since the epoch of an RFC 3339 date, as both APIs send them. +fn timestamp(date: &str) -> Option { + chrono::DateTime::parse_from_rfc3339(date) + .ok() + .map(|date| date.timestamp()) +} + +/// Récupère les dépôts GitHub depuis une URL paginée. +async fn fetch_github_repos( + client: &Client, + base_url: &str, + params: &[(&str, &str)], + network: &NetworkOptions, +) -> Result, AppError> { + enforce_https_policy(base_url, network)?; + let mut all_repos = Vec::new(); + let per_page = 100; + + for page in 1..=10 { + let mut query_params: Vec<(&str, String)> = + params.iter().map(|(k, v)| (*k, (*v).to_string())).collect(); + query_params.push(("per_page", per_page.to_string())); + query_params.push(("page", page.to_string())); + + let response = client + .get(base_url) + .query(&query_params) + .send() + .await + .map_err(AppError::from)?; + + if response.status() == StatusCode::NOT_FOUND { + break; + } + + let response = response.error_for_status().map_err(AppError::from)?; + let mut repos: Vec = response.json().await.map_err(AppError::from)?; + let count = repos.len(); + all_repos.append(&mut repos); + + if count < per_page { + break; + } + } + + Ok(all_repos) +} + +/// Clone bloquant lancé dans un thread dédié, qui envoie sa progression puis son résultat. +/// Le token de l'URL est résolu dans ce thread quand la requête n'en porte pas. +fn clone_with_progress( + mut request: CloneRequest, + auth: AuthManager, +) -> impl Stream { + iced::stream::channel(16, async move |mut output| { + let mut progress = output.clone(); + let result = tokio::task::spawn_blocking(move || { + if request.token.is_none() { + request.token = auth.resolve_for_url(&request.url); + } + // shortcut: an update is dropped when the UI is 16 behind; the next one replaces it. + clone_repository(request, move |update| { + let _ = progress.try_send(Message::CloneProgress(update)); + }) + }) + .await + .unwrap_or_else(|err| { + Err(AppError::Network(tf( + "add_repo_clone_interrupted", + &[("error", &err.to_string())], + ))) + }); + let _ = output.send(Message::CloneResult(result)).await; + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn repo(name: &str) -> RemoteRepo { + RemoteRepo { + name: name.to_string(), + url: format!("https://example.com/{name}.git"), + description: None, + private: None, + stars: 0, + updated: None, + } + } + + fn panel(base: &str) -> AddRepoPanel { + AddRepoPanel::new(base.to_string(), NetworkOptions::default()) + } + + #[test] + fn a_result_for_a_replaced_search_is_dropped() { + let mut panel = panel(""); + panel.search_version = 3; + + panel.apply_search_result(2, Ok(vec![repo("old")])); + assert!(panel.results.is_empty()); + assert_eq!(panel.search_status, None); + + panel.apply_search_result(3, Ok(vec![repo("new")])); + assert_eq!(panel.results, vec![repo("new")]); + assert_eq!(panel.selected, Some(0)); + } + + #[test] + fn gitlab_rows_carry_the_project_visibility() { + let projects: Vec = serde_json::from_str( + r#"[ + {"name_with_namespace": "a / pub", "http_url_to_repo": "u", "visibility": "public"}, + {"name_with_namespace": "a / int", "http_url_to_repo": "u", "visibility": "internal"}, + {"name_with_namespace": "a / priv", "http_url_to_repo": "u", "visibility": "private"}, + {"name_with_namespace": "a / anon", "http_url_to_repo": "u"} + ]"#, + ) + .unwrap(); + let private: Vec<_> = projects + .into_iter() + .map(|p| p.into_repo().private) + .collect(); + assert_eq!( + private, + vec![Some(false), Some(true), Some(true), Some(false)] + ); + } + + #[test] + fn the_progress_bar_eases_toward_the_clone_progress() { + let mut panel = panel(""); + panel.cloning = true; + panel.progress = Some(CloneProgress { + received_objects: 10, + total_objects: 10, + ..CloneProgress::default() + }); + + panel.ease_progress(); + assert!(panel.shown_ratio > 0.0 && panel.shown_ratio < 1.0); + + for _ in 0..100 { + panel.ease_progress(); + } + assert_eq!(panel.shown_ratio, 1.0); + + // Resolving deltas starts again from 0: the bar jumps back instead of sliding down. + panel.progress = Some(CloneProgress { + received_objects: 10, + total_objects: 10, + total_deltas: 4, + indexed_deltas: 0, + received_bytes: 0, + }); + panel.ease_progress(); + assert_eq!(panel.shown_ratio, 0.0); + } + + #[test] + fn partial_results_survive_a_failed_request() { + let merged = merge_partial_results([ + Ok(vec![1, 2]), + Err(AppError::Network("rate limited".into())), + Ok(vec![3]), + ]); + assert_eq!(merged.unwrap(), vec![1, 2, 3]); + } + + #[test] + fn the_first_error_is_returned_when_every_request_fails() { + let merged: Result, _> = merge_partial_results([ + Err(AppError::Network("first".into())), + Err(AppError::Network("second".into())), + ]); + assert!(matches!(merged, Err(AppError::Network(msg)) if msg == "first")); + } + + #[test] + fn own_repositories_are_filtered_on_name_and_description() { + let item = |full_name: &str, description: Option<&str>| GithubRepoItem { + full_name: full_name.to_string(), + html_url: String::new(), + description: description.map(str::to_string), + private: false, + stargazers_count: 0, + updated_at: None, + }; + assert!(matches_query( + &item("Project-Colony/Colony-Camera", None), + "colony" + )); + assert!(matches_query( + &item("MotherSphere/Raven", Some("A COLONY tool")), + "colony" + )); + assert!(!matches_query( + &item("MotherSphere/Raven", Some("Reverse")), + "colony" + )); + } + + #[test] + fn destination_appends_the_repo_name() { + let base = Path::new("/home/me/Repositories"); + let mut panel = panel(&base.display().to_string()); + assert_eq!(panel.destination, base.display().to_string()); + + // A search result picked on GitHub. + panel.apply_search_result(panel.search_version, Ok(vec![repo("owner/Colony")])); + assert_eq!(panel.destination, base.join("Colony").display().to_string()); + + // A pasted SSH URL. + panel.source = Source::Url; + panel.url = "git@gitlab.com:group/GitSpace.git".into(); + panel.refresh_destination(); + assert_eq!( + panel.destination, + base.join("GitSpace").display().to_string() + ); + + // A new default folder from the preferences keeps the name appended. + panel.set_default_destination("/srv/git".into()); + assert_eq!( + panel.destination, + Path::new("/srv/git").join("GitSpace").display().to_string() + ); + } + + #[test] + fn local_folder_that_is_not_a_repo_is_refused() { + let plain = tempfile::tempdir().unwrap(); + let repository = tempfile::tempdir().unwrap(); + git2::Repository::init(repository.path()).unwrap(); + assert!(!is_repository(plain.path())); + assert!(is_repository(repository.path())); + + let mut panel = panel(""); + panel.source = Source::LocalFolder; + let opened = panel.apply_folder_check(plain.path().to_path_buf(), false); + assert_eq!(opened, None); + assert!(panel.folder_error.is_some()); + + let opened = panel.apply_folder_check(repository.path().to_path_buf(), true); + assert_eq!(opened.as_deref(), Some(repository.path())); + } +} diff --git a/src/ui/app.rs b/src/ui/app.rs index d23381a..ee68b3c 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -1,82 +1,148 @@ -//! Application principale GitSpace — architecture Elm pour Iced 0.13. -//! -//! Centralise le modèle, les messages, le dispatch update/view, -//! les subscriptions (auto-fetch, notifications, clavier) et le thème. +//! The GitSpace application on iced 0.14: the model, the messages, `update` and `view`, +//! and the subscriptions (auto-fetch, toasts, keyboard, window focus). -use std::time::Duration; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{Duration, Instant}; +use colony_ui::theme::Palette; +use iced::keyboard::key::{Code, Named, Physical}; +use iced::keyboard::{Key, Modifiers}; use iced::widget::{column, container, row}; use iced::{Element, Length, Subscription, Task}; use crate::auth::AuthManager; -use crate::config::{AppConfig, LoggingOptions, Preferences}; +use crate::config::{AppConfig, Preferences}; use crate::error::logs_directory; +use crate::git::discover::discover_repositories; +use crate::git::status::{quick_status, QuickStatus}; +use crate::i18n::{t, tf}; use crate::ui::{ - auth::AuthPanel, + add_repo::{self, AddRepoPanel}, branches::{self, BranchPanel}, - clone::{self, ClonePanel}, + changes::{self, ChangesPanel}, context::RepoContext, - history::HistoryPanel, - layout::{self, LayoutMessage, MainTab}, - notifications::{Notification, NotificationAction, NotificationCenter}, - preferences::PreferencesPanel, - recent::RecentList, - repo_overview::{self, RepoOverviewPanel}, - stage::{self, StagePanel}, - theme::Theme, + history::{self, HistoryPanel}, + preferences::{self, PreferencesPage}, + repo_header::{self, RepoHeader, RepoTab, TabCounts}, + sidebar::{self, Sidebar}, + stashes::{self, StashesPanel}, + widgets::toast::{Toast, ToastAction, Toasts}, }; +/// Quick-status scans run at the same time, at most. +const STATUS_SCANS: usize = 4; + +/// Status refreshes share one scan limit; a result older than the last one applied is dropped. +struct StatusRefresh { + limit: Arc, + started: u64, + applied: u64, +} + +impl Default for StatusRefresh { + fn default() -> Self { + Self { + limit: Arc::new(tokio::sync::Semaphore::new(STATUS_SCANS)), + started: 0, + applied: 0, + } + } +} + +impl StatusRefresh { + /// Numbers a new refresh and hands it the shared limit. + fn start(&mut self) -> (u64, Arc) { + self.started += 1; + (self.started, self.limit.clone()) + } + + /// Whether the result of refresh `generation` is newer than the one on screen. + fn accept(&mut self, generation: u64) -> bool { + if generation <= self.applied { + return false; + } + self.applied = generation; + true + } +} + +/// The panel that changed the repository, which [`GitSpaceApp::reload_other_panels`] skips. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Origin { + Header, + Changes, + Branches, + History, + Stashes, +} + // ─── Message principal ───────────────────────────────────────────────────── /// Message racine de l'application, enveloppe tous les sous-messages. #[derive(Debug, Clone)] pub enum Message { - // Layout / navigation - Layout(LayoutMessage), + Sidebar(sidebar::Message), // Panneaux - Clone(crate::ui::clone::Message), - Recent(crate::ui::recent::Message), - RepoOverview(crate::ui::repo_overview::Message), - Stage(crate::ui::stage::Message), + AddRepo(add_repo::Message), + RepoHeader(repo_header::Message), + Changes(changes::Message), History(crate::ui::history::Message), Branches(crate::ui::branches::Message), - Auth(crate::ui::auth::Message), - Preferences(crate::ui::preferences::Message), + Stashes(stashes::Message), + Preferences(preferences::Message), - // Notifications - Notification(crate::ui::notifications::Message), + // Toasts + ToastDismissed(u64), + ToastAction(u64, ToastAction), // Chargement async du contexte d'un depot RepoContextLoaded(String, Option), - // Tick de nettoyage notifications - NotificationTick, + /// Removes expired toasts and redraws fading ones. + ToastTick, // Auto-fetch timer tick AutoFetchTick, - /// Ctrl+N (Cmd+N on macOS): show the tab at position N of the tab strip. + /// Ctrl+N (Cmd+N on macOS): show repository tab N, counted from 0. TabShortcut(usize), + + /// Closes the search, a menu or Preferences, the first one open. + Escape, + /// F2: rename the selected branch while Branches is shown. + RenameBranch, + + /// The window gained focus: the repositories may have changed outside GitSpace. + WindowFocused, + + /// Repositories found in the default clone folder. + CloneFolderScanned(Vec), } // ─── Modele principal ────────────────────────────────────────────────────── /// Etat global de l'application GitSpace. pub struct GitSpaceApp { - theme: Theme, - active_tab: MainTab, - tab_order: Vec, + active_tab: RepoTab, + /// The Add repository screen is shown in place of the open repository. + adding: bool, + + sidebar: Sidebar, + /// Quick status of each listed repository, by path, from the last background scan. + statuses: HashMap, + status_refresh: StatusRefresh, // Panneaux - clone_panel: ClonePanel, - recent_list: RecentList, - repo_overview: RepoOverviewPanel, - stage_panel: StagePanel, + add_repo: AddRepoPanel, + repo_header: RepoHeader, + changes_panel: ChangesPanel, history_panel: HistoryPanel, branches_panel: BranchPanel, - auth_panel: AuthPanel, - preferences_panel: PreferencesPanel, + stashes_panel: StashesPanel, + preferences: PreferencesPage, // Etat global config: AppConfig, @@ -84,49 +150,65 @@ pub struct GitSpaceApp { /// Dernier depot demande : seul son resultat de chargement est applique. pending_repo: Option, auth_manager: AuthManager, - notifications: NotificationCenter, + toasts: Toasts, } impl GitSpaceApp { /// Construit l'etat initial et retourne les taches de demarrage. - pub fn new() -> (Self, Task) { + /// + /// `migration_error` is set when the files of an older build could not be moved. + pub fn new(migration_error: Option) -> (Self, Task) { let config = AppConfig::load(); let preferences = config.preferences().clone(); - let logging = *config.logging(); let default_clone_path = preferences.default_clone_path().to_string(); - let theme = Theme::from_mode(preferences.theme_mode()); + preferences.standard.apply(); + colony_ui::i18n::set_locale(preferences.language().locale()); let auth_manager = AuthManager::with_encrypted_fallback(preferences.allow_encrypted_tokens()); - let last_repo = config - .recent_repos() - .first() - .map(|entry| entry.path.clone()); + let last_repo = startup_target( + preferences.reopen_last_repo(), + config.last_repo().map(|entry| entry.path.as_str()), + |path| !std::path::Path::new(path).exists(), + ); let mut app = Self { - clone_panel: ClonePanel::new(default_clone_path, preferences.network().clone()), - recent_list: RecentList::new(), - repo_overview: RepoOverviewPanel::new(preferences.network().clone()), - history_panel: HistoryPanel::new(), + sidebar: Sidebar::default(), + statuses: HashMap::new(), + status_refresh: StatusRefresh::default(), + add_repo: AddRepoPanel::new(default_clone_path, preferences.network().clone()), + repo_header: RepoHeader::new(preferences.network().clone()), + history_panel: HistoryPanel::default(), branches_panel: BranchPanel::new(preferences.pinned_branches().to_vec()), - stage_panel: StagePanel::new(), - auth_panel: AuthPanel::new(auth_manager.clone()), - preferences_panel: PreferencesPanel::new(preferences, logging), - theme, + changes_panel: ChangesPanel::default(), + stashes_panel: StashesPanel::default(), + preferences: PreferencesPage::new(auth_manager.clone()), config, current_repo: None, pending_repo: None, auth_manager, - active_tab: MainTab::Clone, - tab_order: MainTab::ALL.to_vec(), - notifications: NotificationCenter::new(), + active_tab: RepoTab::Changes, + adding: false, + toasts: Toasts::default(), }; - let accounts = app.auth_panel.refresh_accounts().map(Message::Auth); + if let Some(error) = migration_error { + app.toasts.push(Toast::error( + t("startup_migration_failed"), + tf("startup_migration_failed_detail", &[("error", &error)]), + )); + } + + let accounts = app + .preferences + .accounts + .refresh_accounts() + .map(accounts_message); let repo = match last_repo { Some(path) => app.load_repo_context_async(path), None => Task::none(), }; - (app, Task::batch([accounts, repo])) + let scans = Task::batch([app.refresh_statuses(), app.rescan_clone_folder()]); + (app, Task::batch([accounts, repo, scans])) } // ─── Update ──────────────────────────────────────────────────────── @@ -134,134 +216,118 @@ impl GitSpaceApp { /// Dispatch principal des messages. pub fn update(&mut self, message: Message) -> Task { match message { - // ── Layout / navigation ──────────────────────────────────── - Message::Layout(layout_msg) => { - match layout_msg { - LayoutMessage::TabSelected(tab) => { - self.active_tab = tab; - } - LayoutMessage::HeaderClicked => { - self.preferences_panel.toggle(); - } - LayoutMessage::OpenFileManager => { - if let Some(repo) = &self.current_repo { - if let Err(err) = repo_overview::open_folder(repo.path()) { - self.notifications.push(Notification::error( - "Impossible d'ouvrir le dossier", - format!("{} : {err}", repo.path()), - )); - } - } - } - LayoutMessage::CopyPath => { - if let Some(repo) = &self.current_repo { - return iced::clipboard::write(repo.path().to_string()); - } - } - } + Message::Sidebar(msg) => self.update_sidebar(msg), + + // ── Add repository ───────────────────────────────────────── + Message::AddRepo(add_repo::Message::OpenAccounts) => { + self.preferences.open_accounts(); Task::none() } - - // ── Clone ────────────────────────────────────────────────── - Message::Clone(msg) => { + Message::AddRepo(msg) => { self.notify_clone_failure(&msg); - let (task, cloned_path) = self.clone_panel.update(msg, &self.auth_manager); - let load_task = if let Some(path) = cloned_path { - self.load_repo_context_async(path.to_string_lossy().to_string()) - } else { - Task::none() + let (task, added) = self.add_repo.update(msg, &self.auth_manager); + let load_task = match added { + Some(path) => { + // A cloned or opened repository shows on Changes. + self.active_tab = RepoTab::Changes; + self.load_repo_context_async(path.to_string_lossy().into_owned()) + } + None => Task::none(), }; - Task::batch([task.map(Message::Clone), load_task]) + Task::batch([task.map(Message::AddRepo), load_task]) } - // ── Recent ───────────────────────────────────────────────── - Message::Recent(msg) => { - let (task, selected) = self.recent_list.update(msg); - let load_task = if let Some(path) = selected { - self.load_repo_context_async(path) + // ── Repository header ────────────────────────────────────── + Message::RepoHeader(repo_header::Message::SelectTab(tab)) => { + self.active_tab = tab; + Task::none() + } + Message::RepoHeader(msg) => { + let finished = matches!(msg, repo_header::Message::ActionFinished { .. }); + let succeeded = remote_action_succeeded( + &msg, + self.current_repo.as_ref().map(RepoContext::path), + ); + let (task, toast) = self.repo_header.update(msg, &self.auth_manager); + if let Some(toast) = toast { + self.toasts.push(toast); + } + let reload = match succeeded { + // A pull moves HEAD and the working tree. + Some(repo_header::RemoteAction::Pull) => { + self.reload_other_panels(Origin::Header) + } + // A fetch or a push leaves HEAD and the working tree alone. Branches reloads + // for its upstream counts; History keeps its selection. + Some(_) => self.reload_branches(), + None => Task::none(), + }; + let statuses = if finished { + self.refresh_statuses() } else { Task::none() }; - Task::batch([task.map(Message::Recent), load_task]) + Task::batch([task.map(Message::RepoHeader), reload, statuses]) } - // ── Repo overview ────────────────────────────────────────── - Message::RepoOverview(msg) => { - self.notify_auto_fetch_failure(&msg); - let mut pulled = false; - if let repo_overview::Message::ActionFinished { - path, - action, - auto: false, - result, - } = &msg - { - let current = self.current_repo.as_ref().map(|repo| repo.path()); - if current != Some(&**path) { - // The panel only shows results for the open repository. - let detail = match result { - Ok(msg) => msg.clone(), - Err(err) => format!("Échec : {err}"), - }; - self.notifications.push(Notification::error( - format!("{} sur {path}", action.label()), - detail, - )); - } else { - pulled = - matches!(action, repo_overview::RemoteAction::Pull) && result.is_ok(); - } + // ── Changes ──────────────────────────────────────────────── + Message::Changes(msg) => { + // A commit moves HEAD: the other panels show the old state until reloaded. + let changed = matches!(&msg, changes::Message::Committed(_, Ok(_))); + let acted = changed || matches!(&msg, changes::Message::ActionDone(_, _, Ok(_))); + let (task, toast) = self.changes_panel.update(msg); + if let Some(toast) = toast { + self.toasts.push(toast); } - let task = self - .repo_overview - .update(msg, self.current_repo.as_ref(), &self.auth_manager) - .map(Message::RepoOverview); - if pulled { - Task::batch([task, self.reload_other_panels(MainTab::RepoOverview)]) + let task = task.map(Message::Changes); + let reload = if changed { + self.reload_other_panels(Origin::Changes) } else { - task - } - } - - // ── Stage ────────────────────────────────────────────────── - Message::Stage(msg) => { - // A commit moves HEAD: the other panels show the old state until reloaded. - let changed = matches!(&msg, stage::Message::Committed(_, Ok(_))); - let task = self - .stage_panel - .update(msg, self.current_repo.as_ref()) - .map(Message::Stage); - if changed { - Task::batch([task, self.reload_other_panels(MainTab::Stage)]) + Task::none() + }; + // A discard or stage also changes what a new stash would take. + let statuses = if acted { + Task::batch([self.refresh_statuses(), self.reload_stashes()]) } else { - task - } + Task::none() + }; + Task::batch([task, reload, statuses]) } // ── History ──────────────────────────────────────────────── Message::History(msg) => { - let task = self.history_panel.update(msg, self.current_repo.as_ref()); - task.map(Message::History) + // A checkout moves HEAD and a new branch adds a ref: every panel reloads. + let changed = matches!(&msg, history::Message::ActionDone(_, _, Ok(_))); + let (task, toast) = self.history_panel.update(msg); + if let Some(toast) = toast { + self.toasts.push(toast); + } + let mut tasks = vec![task.map(Message::History)]; + if changed { + tasks.push(self.reload_other_panels(Origin::History)); + tasks.push(self.refresh_statuses()); + } + Task::batch(tasks) } // ── Branches ─────────────────────────────────────────────── Message::Branches(msg) => { // Checkout, merge and rebase change the working tree and HEAD. - let changed = matches!( - &msg, - branches::Message::ActionDone(_, Ok(_)) | branches::Message::MergeDone(_, _) - ); - let mut tasks = vec![self - .branches_panel - .update(msg, self.current_repo.as_ref()) - .map(Message::Branches)]; + // A conflicted merge or rebase ends as Ok too: the tree still changed. + let changed = matches!(&msg, branches::Message::ActionDone(_, _, Ok(_))); + let (task, toast) = self.branches_panel.update(msg); + if let Some(toast) = toast { + self.toasts.push(toast); + } + let mut tasks = vec![task.map(Message::Branches)]; if changed { - tasks.push(self.reload_other_panels(MainTab::Branches)); + tasks.push(self.reload_other_panels(Origin::Branches)); + tasks.push(self.refresh_statuses()); } // Gerer la demande de navigation vers l'historique d'une branche if let Some(branch) = self.branches_panel.take_history_request() { - self.active_tab = MainTab::History; + self.active_tab = RepoTab::History; if let Some(repo) = &self.current_repo { tasks.push( self.history_panel @@ -276,37 +342,62 @@ impl GitSpaceApp { let mut prefs = self.config.preferences().clone(); prefs.set_pinned_branches(pinned); self.config.set_preferences(prefs); - // Sinon une validation ulterieure des preferences restaurerait l'ancienne liste. - self.preferences_panel - .set_preferences(self.config.preferences().clone()); self.save_config(); } Task::batch(tasks) } - // ── Auth ─────────────────────────────────────────────────── - Message::Auth(msg) => { - let task = self.auth_panel.update(msg); - task.map(Message::Auth) + // ── Stashes ──────────────────────────────────────────────── + Message::Stashes(msg) => { + let changed = stash_job_finished(&msg); + let (task, toast) = self.stashes_panel.update(msg); + if let Some(toast) = toast { + self.toasts.push(toast); + } + let mut tasks = vec![task.map(Message::Stashes)]; + if changed { + tasks.push(self.reload_other_panels(Origin::Stashes)); + tasks.push(self.refresh_statuses()); + } + Task::batch(tasks) } // ── Preferences ──────────────────────────────────────────── + // Every change applies and saves at once: there is no Save button. Message::Preferences(msg) => { - let panel_task = self.preferences_panel.update(msg); - let extra_task = self.handle_preferences_changes(); - Task::batch([panel_task.map(Message::Preferences), extra_task]) + let mut prefs = self.config.preferences().clone(); + let mut logging = *self.config.logging(); + let (task, toast) = self.preferences.update(msg, &mut prefs, &mut logging); + if let Some(toast) = toast { + self.toasts.push(toast); + } + let logging_changed = logging != *self.config.logging(); + self.config.set_logging(logging); + let applied = if prefs != *self.config.preferences() { + self.apply_preferences(prefs) + } else { + if logging_changed { + self.save_config(); + } + Task::none() + }; + Task::batch([task.map(Message::Preferences), applied]) } - // ── Notifications ────────────────────────────────────────── - Message::Notification(msg) => { - let actions = self.notifications.update(msg); - self.handle_notification_actions(actions) + // ── Toasts ───────────────────────────────────────────────── + Message::ToastDismissed(id) => { + self.toasts.dismiss(id); + Task::none() } - Message::NotificationTick => { - self.notifications - .update(crate::ui::notifications::Message::Tick); + Message::ToastAction(id, action) => { + self.toasts.dismiss(id); + self.handle_toast_action(action) + } + + Message::ToastTick => { + self.toasts.expire(Instant::now()); Task::none() } @@ -318,56 +409,292 @@ impl GitSpaceApp { } self.pending_repo = None; let Some(repo) = context else { - self.notifications.push(Notification::error( - "Impossible d'ouvrir le dépôt", - format!("{path} n'est pas un dépôt Git lisible."), + // The repository open until now stays open. + self.toasts.push(Toast::error( + t("repo_missing_title"), + tf("repo_missing_detail", &[("path", &path)]), )); - return Task::none(); + return self.refresh_statuses(); }; - if self.config.touch_recent(std::path::Path::new(&path)) { + if self.config.open_repo(&path, chrono::Utc::now().timestamp()) { self.save_config(); } + self.adding = false; let tasks = [ - self.repo_overview.refresh(&repo).map(Message::RepoOverview), - self.stage_panel.load(&repo).map(Message::Stage), + self.repo_header.load(&repo).map(Message::RepoHeader), + self.changes_panel.load(&repo).map(Message::Changes), self.branches_panel.load(&repo).map(Message::Branches), self.history_panel.load(&repo).map(Message::History), + self.stashes_panel.load(&repo).map(Message::Stashes), ]; self.current_repo = Some(repo); Task::batch(tasks) } // ── Auto-fetch ───────────────────────────────────────────── - Message::AutoFetchTick => self.maybe_start_auto_fetch(), - - Message::TabShortcut(index) => { - if let Some(tab) = self.tab_order.get(index) { + Message::AutoFetchTick => Task::batch([ + self.maybe_start_auto_fetch(), + self.refresh_statuses(), + self.reload_changes(), + ]), + + Message::TabShortcut(index) => match RepoTab::ALL.get(index) { + Some(tab) => { self.active_tab = *tab; + self.adding = false; + self.close_preferences() } + None => Task::none(), + }, + + Message::Escape => { + if self.sidebar.is_searching() { + self.sidebar.close_search(); + } else if self.sidebar.is_menu_open() { + self.sidebar.set_menu(None); + } else if self.preferences.is_open() { + return self.update(Message::Preferences(preferences::Message::Toggle)); + } + Task::none() + } + + Message::RenameBranch => { + if self.active_tab == RepoTab::Branches && !self.adding { + return self.update(Message::Branches(branches::Message::StartRename)); + } + Task::none() + } + + // A commit, a checkout or a fetch made elsewhere changes what every panel shows; + // History is left alone so that switching windows keeps its selection. + Message::WindowFocused => { + let panels = match self.current_repo.clone() { + Some(repo) => Task::batch([ + self.repo_header.load(&repo).map(Message::RepoHeader), + self.branches_panel.load(&repo).map(Message::Branches), + ]), + None => Task::none(), + }; + Task::batch([self.refresh_statuses(), self.reload_changes(), panels]) + } + + Message::CloneFolderScanned(paths) => { + if !self.config.merge_discovered(&paths) { + return Task::none(); + } + self.save_config(); + self.refresh_statuses() + } + } + } + + fn update_sidebar(&mut self, message: sidebar::Message) -> Task { + use sidebar::Message as Side; + match message { + Side::ToggleSearch => self + .sidebar + .toggle_search(self.config.repos()) + .map(Message::Sidebar), + Side::Query(query) => { + self.sidebar.set_query(query, self.config.repos()); + Task::none() + } + Side::MoveSelection(delta) => { + let target = self.sidebar.step(delta, self.config.repos()); + match target { + // While searching, Up/Down only move the cursor; Enter opens. + Some(path) if !self.sidebar.is_searching() => self.open_repo(&path), + _ => Task::none(), + } + } + Side::Activate => match self.sidebar.cursor() { + Some(path) => self.open_repo(&path), + None => Task::none(), + }, + Side::Select(path) => self.open_repo(&path), + Side::Pin(path, pinned) => { + self.sidebar.set_menu(None); + self.config.set_pinned(&path, pinned); + self.save_config(); Task::none() } + Side::Hide(path) => { + self.sidebar.set_menu(None); + self.config.hide_repo(&path); + self.save_config(); + Task::none() + } + Side::OpenFolder(path) => { + self.sidebar.set_menu(None); + if let Err(err) = repo_header::open_folder(&path) { + self.toasts.push(Toast::error( + t("open_folder_failed"), + format!("{path}: {err}"), + )); + } + Task::none() + } + Side::OpenTerminal(path) => { + self.sidebar.set_menu(None); + if let Err(err) = repo_header::open_terminal(&path) { + self.toasts.push(Toast::error( + t("open_terminal_failed"), + format!("{path}: {err}"), + )); + } + Task::none() + } + Side::ContextMenu(path) => { + self.sidebar.set_menu(path); + Task::none() + } + Side::AddRepository => { + self.adding = true; + self.close_preferences() + } + Side::TogglePreferences => { + self.update(Message::Preferences(preferences::Message::Toggle)) + } + Side::StatusesLoaded(generation, statuses) => { + if self.status_refresh.accept(generation) { + self.statuses.extend(statuses); + } + Task::none() + } + } + } + + /// Opens `path` from the sidebar; the search, any menu and Preferences close. + fn open_repo(&mut self, path: &str) -> Task { + self.adding = false; + self.sidebar.close_search(); + self.sidebar.set_menu(None); + let closed = self.close_preferences(); + let current = self.current_repo.as_ref().map(RepoContext::path); + if !needs_load(&mut self.pending_repo, current, path) { + self.sidebar.set_anchor(path); + return closed; + } + Task::batch([closed, self.load_repo_context_async(path.to_string())]) + } + + /// Closes Preferences, when open, through its own message so a typed clone folder is + /// still applied. + fn close_preferences(&mut self) -> Task { + if self.preferences.is_open() { + self.update(Message::Preferences(preferences::Message::Toggle)) + } else { + Task::none() + } + } + + /// Reads the quick status of every listed repository in the background, a few at a time. + fn refresh_statuses(&mut self) -> Task { + let paths: Vec = self + .config + .repos() + .iter() + .filter(|entry| !entry.hidden) + .map(|entry| entry.path.clone()) + .collect(); + if paths.is_empty() { + return Task::none(); + } + let (generation, limit) = self.status_refresh.start(); + Task::perform( + async move { + let mut scans = tokio::task::JoinSet::new(); + for path in paths { + let limit = limit.clone(); + scans.spawn(async move { + let _permit = limit.acquire_owned().await.ok()?; + let status = { + let path = path.clone(); + tokio::task::spawn_blocking(move || quick_status(&path)) + .await + .ok()? + }; + Some((path, status)) + }); + } + let mut statuses = HashMap::new(); + while let Some(scan) = scans.join_next().await { + if let Ok(Some((path, status))) = scan { + statuses.insert(path, status); + } + } + statuses + }, + move |statuses| { + Message::Sidebar(sidebar::Message::StatusesLoaded(generation, statuses)) + }, + ) + } + + /// Looks for repositories in the default clone folder, when that option is on. + fn rescan_clone_folder(&self) -> Task { + let preferences = self.config.preferences(); + if !preferences.scan_clone_folder() { + return Task::none(); + } + let root = PathBuf::from(preferences.default_clone_path()); + Task::perform( + async move { + tokio::task::spawn_blocking(move || { + discover_repositories(&root) + .into_iter() + .map(|path| path.to_string_lossy().into_owned()) + .collect() + }) + .await + .unwrap_or_default() + }, + Message::CloneFolderScanned, + ) + } + + /// Rereads the open repository's changes and stashes, which other programs may have + /// edited. + fn reload_changes(&mut self) -> Task { + let changes = match self.current_repo.clone() { + Some(repo) => self.changes_panel.load(&repo).map(Message::Changes), + None => Task::none(), + }; + Task::batch([changes, self.reload_stashes()]) + } + + fn reload_stashes(&mut self) -> Task { + match self.current_repo.clone() { + Some(repo) => self.stashes_panel.load(&repo).map(Message::Stashes), + None => Task::none(), + } + } + + fn reload_branches(&mut self) -> Task { + match self.current_repo.clone() { + Some(repo) => self.branches_panel.load(&repo).map(Message::Branches), + None => Task::none(), } } /// Reloads every repository panel except `origin` after it changed the repository. - fn reload_other_panels(&mut self, origin: MainTab) -> Task { + fn reload_other_panels(&mut self, origin: Origin) -> Task { let Some(repo) = self.current_repo.clone() else { return Task::none(); }; let mut tasks = Vec::new(); - if origin != MainTab::RepoOverview { - tasks.push( - self.repo_overview - .reload_repo_state(&repo) - .map(Message::RepoOverview), - ); + if origin != Origin::Header { + tasks.push(self.repo_header.load(&repo).map(Message::RepoHeader)); } - if origin != MainTab::Stage { - tasks.push(self.stage_panel.load(&repo).map(Message::Stage)); + if origin != Origin::Changes { + tasks.push(self.changes_panel.load(&repo).map(Message::Changes)); } - if origin != MainTab::Branches { + if origin != Origin::Branches { tasks.push(self.branches_panel.load(&repo).map(Message::Branches)); } + if origin != Origin::Stashes { + tasks.push(self.stashes_panel.load(&repo).map(Message::Stashes)); + } tasks.push(self.history_panel.load(&repo).map(Message::History)); Task::batch(tasks) } @@ -376,65 +703,66 @@ impl GitSpaceApp { /// Compose la vue complete de l'application. pub fn view(&self) -> Element<'_, Message> { - let theme = &self.theme; - - // Si le panneau de preferences est ouvert, afficher uniquement celui-ci - if self.preferences_panel.is_open() { - if let Some(prefs_view) = self.preferences_panel.view(theme) { - let overlay = self.notification_overlay(theme); - return column![prefs_view.map(Message::Preferences), overlay,].into(); + let sidebar = self + .sidebar + .view( + self.config.repos(), + &self.statuses, + self.current_repo.as_ref().map(RepoContext::path), + self.preferences.is_open(), + ) + .map(Message::Sidebar); + + // Preferences take the place of the content area while open; the sidebar stays. + let main_area: Element<'_, Message> = if self.preferences.is_open() { + self.preferences.view( + self.config.preferences(), + self.config.logging(), + Message::Preferences, + Message::Sidebar(sidebar::Message::TogglePreferences), + ) + } else { + match (&self.current_repo, self.adding) { + (Some(_), false) => { + let counts = TabCounts { + changes: self.changes_panel.count(), + stashes: self.stashes_panel.count(), + }; + let header = self + .repo_header + .view(self.active_tab, counts) + .map(Message::RepoHeader); + column![header, self.view_active_tab()] + .width(Length::Fill) + .height(Length::Fill) + .into() + } + (_, _) => self + .add_repo + .view(|host| self.preferences.accounts.is_connected(host)) + .map(Message::AddRepo), } - } - - // Header - let header = layout::view_header(theme).map(Message::Layout); - - // Sidebar - let sidebar = layout::view_sidebar(theme, self.active_tab, self.current_repo.as_ref()) - .map(Message::Layout); - - // Barre d'onglets - let tab_bar = - layout::view_tab_bar(theme, &self.tab_order, self.active_tab).map(Message::Layout); - - // Contenu de l'onglet actif - let content = self.view_active_tab(theme); - - // Overlay notifications - let notification_overlay = self.notification_overlay(theme); - - // Assemblage : header en haut, puis sidebar + (tabs + content) en dessous - let main_area = column![tab_bar, content,] - .width(Length::Fill) - .height(Length::Fill) - .padding(iced::Padding { - top: 0.0, - right: 16.0, - bottom: 16.0, - left: 16.0, - }); - - let body = row![sidebar, main_area,].height(Length::Fill); + }; - // Superposer les notifications en haut a droite - let page = column![header, body,].height(Length::Fill); + let toast_overlay = self.toast_overlay(); + let page = row![sidebar, main_area].height(Length::Fill); // Utiliser un container pour le fond + overlay notifications let base = container(page) .width(Length::Fill) .height(Length::Fill) - .style(move |_: &iced::Theme| container::Style { - background: Some(theme.palette.background.into()), + .style(|_: &iced::Theme| container::Style { + background: Some(Palette::BG_PRIMARY().into()), ..Default::default() }); - if self.notifications.is_empty() { + if self.toasts.is_empty() { base.into() } else { // Placer les notifications en overlay via une colonne empilee column![iced::widget::stack![ base, - container(notification_overlay) + container(toast_overlay) .width(Length::Fill) .align_x(iced::alignment::Horizontal::Right) .padding(iced::Padding { @@ -450,69 +778,92 @@ impl GitSpaceApp { } } - /// Rendu de l'onglet actif. - fn view_active_tab<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { + /// The panel of the selected repository tab. + fn view_active_tab(&self) -> Element<'_, Message> { match self.active_tab { - MainTab::Clone => self.clone_panel.view(theme).map(Message::Clone), - MainTab::Open => self - .recent_list - .view(theme, &self.config) - .map(Message::Recent), - MainTab::RepoOverview => self - .repo_overview - .view(theme, self.current_repo.as_ref()) - .map(Message::RepoOverview), - MainTab::Stage => self - .stage_panel - .view(theme, self.current_repo.as_ref()) - .map(Message::Stage), - MainTab::History => self - .history_panel - .view(theme, self.current_repo.as_ref()) - .map(Message::History), - MainTab::Branches => self - .branches_panel - .view(theme, self.current_repo.as_ref()) - .map(Message::Branches), - MainTab::Auth => self.auth_panel.view(theme).map(Message::Auth), + // The Changes columns run to the window edges, as in the mockup. + RepoTab::Changes => self.changes_panel.view().map(Message::Changes), + RepoTab::Stashes => self.stashes_panel.view().map(Message::Stashes), + RepoTab::History => self.history_panel.view().map(Message::History), + RepoTab::Branches => self.branches_panel.view().map(Message::Branches), } } - /// Overlay des notifications toast. - fn notification_overlay<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - self.notifications.view(theme).map(Message::Notification) + fn toast_overlay(&self) -> Element<'_, Message> { + self.toasts + .view(Message::ToastDismissed, Message::ToastAction) } // ─── Theme ───────────────────────────────────────────────────────── - /// Retourne le theme Iced natif derive de notre theme custom. + /// The iced theme for the built-in widgets, from the active colony-ui palette. pub fn theme(&self) -> iced::Theme { - self.theme.to_iced_theme() + let palette = iced::theme::Palette { + background: Palette::BG_PRIMARY(), + text: Palette::TEXT_PRIMARY(), + primary: Palette::ACCENT(), + success: Palette::SUCCESS(), + warning: Palette::WARNING(), + danger: Palette::ERROR(), + }; + iced::Theme::custom_with_fn("GitSpace".to_string(), palette, |palette| { + iced::theme::palette::Extended::generate(palette) + }) } // ─── Subscriptions ───────────────────────────────────────────────── - /// Abonnements actifs : tick notifications + timer auto-fetch. + /// Abonnements actifs : tick des toasts + timer auto-fetch. pub fn subscription(&self) -> Subscription { let mut subs = Vec::new(); - // Tick pour le dismiss automatique des notifications - if !self.notifications.is_empty() { - subs.push(iced::time::every(Duration::from_secs(1)).map(|_| Message::NotificationTick)); + // Expire toasts once a second; every frame while one fades out. + if self.toasts.is_fading(Instant::now()) { + subs.push(iced::window::frames().map(|_| Message::ToastTick)); + } else if !self.toasts.is_empty() { + subs.push(iced::time::every(Duration::from_secs(1)).map(|_| Message::ToastTick)); + } + + if self.add_repo.is_easing() { + subs.push(iced::window::frames().map(|_| Message::AddRepo(add_repo::Message::Frame))); } // Timer auto-fetch. Il est recree apres chaque operation du panneau, donc le prochain - // auto-fetch part un intervalle apres la derniere operation reseau ou le dernier chargement. + // auto-fetch part un intervalle apres la derniere operation reseau ou l'ouverture du depot. if self.config.preferences().auto_fetch_enabled() && self.current_repo.is_some() - && !self.repo_overview.is_busy() + && !self.repo_header.is_busy() { let interval = Duration::from_secs(self.config.preferences().auto_fetch_interval_minutes() * 60); subs.push(iced::time::every(interval).map(|_| Message::AutoFetchTick)); } - subs.push(iced::keyboard::on_key_press(tab_shortcut)); + // Every key press, with whether a widget took it: the search field takes Escape. + subs.push( + iced::event::listen_with(|event, status, _| match event { + iced::Event::Keyboard(iced::keyboard::Event::KeyPressed { + key, + physical_key, + modifiers, + .. + }) => Some(( + key, + physical_key, + modifiers, + status == iced::event::Status::Captured, + )), + _ => None, + }) + .with(self.sidebar.is_searching()) + .filter_map(|(searching, (key, physical, modifiers, captured))| { + shortcut(key, physical, modifiers, captured, searching) + }), + ); + + subs.push(iced::window::events().filter_map(|(_, event)| { + matches!(event, iced::window::Event::Focused).then_some(Message::WindowFocused) + })); Subscription::batch(subs) } @@ -522,10 +873,8 @@ impl GitSpaceApp { /// Sauvegarde la configuration et notifie l'utilisateur en cas d'echec. fn save_config(&mut self) { if let Err(err) = self.config.save() { - self.notifications.push(Notification::error( - "Erreur de sauvegarde", - format!("Impossible de sauvegarder la configuration : {err}"), - )); + self.toasts + .push(Toast::error(t("config_save_failed"), err.to_string())); } } @@ -533,6 +882,7 @@ impl GitSpaceApp { /// Les I/O git sont deplacees dans un thread bloquant pour ne pas /// bloquer le thread UI. fn load_repo_context_async(&mut self, path: String) -> Task { + self.sidebar.set_anchor(&path); self.pending_repo = Some(path.clone()); Task::perform( async move { @@ -547,103 +897,76 @@ impl GitSpaceApp { ) } - /// Applique les changements de preferences depuis le panneau preferences. - fn handle_preferences_changes(&mut self) -> Task { - let mut task = Task::none(); - if let Some(prefs) = self.preferences_panel.take_changes() { - task = self.apply_preferences(prefs); - } - if let Some(logging) = self.preferences_panel.take_logging_changes() { - self.apply_logging(logging); - } - task - } - /// Applique un jeu de preferences mis a jour a toute l'application. fn apply_preferences(&mut self, preferences: Preferences) -> Task { + let old = self.config.preferences(); + let rescan = old.scan_clone_folder() != preferences.scan_clone_folder() + || old.default_clone_path() != preferences.default_clone_path(); + let storage_changed = old.allow_encrypted_tokens() != preferences.allow_encrypted_tokens(); self.config.set_preferences(preferences.clone()); - self.theme = Theme::from_mode(preferences.theme_mode()); + // An import or a reset changes these too. + preferences.standard.apply(); + colony_ui::i18n::set_locale(preferences.language().locale()); // Propager aux panneaux - self.clone_panel + self.add_repo .set_default_destination(preferences.default_clone_path().to_string()); - self.clone_panel + self.add_repo .set_network_preferences(preferences.network().clone()); - self.repo_overview + self.repo_header .set_network_preferences(preferences.network().clone()); self.branches_panel .set_pinned_branches(preferences.pinned_branches().to_vec()); - self.auth_manager - .set_encrypted_fallback(preferences.allow_encrypted_tokens()); - let accounts = self - .auth_panel - .set_auth_manager(self.auth_manager.clone()) - .map(Message::Auth); - self.preferences_panel.set_preferences(preferences); - - self.save_config(); - accounts - } + let accounts = if storage_changed { + self.auth_manager + .set_encrypted_fallback(preferences.allow_encrypted_tokens()); + self.preferences + .accounts + .set_auth_manager(self.auth_manager.clone()) + .map(accounts_message) + } else { + Task::none() + }; - /// Applique les options de logging mises a jour. - fn apply_logging(&mut self, logging: LoggingOptions) { - self.config.set_logging(logging); self.save_config(); + let scan = if rescan { + self.rescan_clone_folder() + } else { + Task::none() + }; + Task::batch([accounts, scan]) } - /// Traite les actions declenchees depuis les notifications. - fn handle_notification_actions(&mut self, actions: Vec) -> Task { - let mut tasks = Vec::new(); - for action in actions { - match action { - NotificationAction::RetryClone => { - let (task, _) = self - .clone_panel - .update(clone::Message::RetryClone, &self.auth_manager); - tasks.push(task.map(Message::Clone)); - } - NotificationAction::CopyLogPath(path) => { - tasks.push(iced::clipboard::write(path.display().to_string())); - } + fn handle_toast_action(&mut self, action: ToastAction) -> Task { + match action { + ToastAction::Retry => { + let (task, _) = self + .add_repo + .update(add_repo::Message::RetryClone, &self.auth_manager); + task.map(Message::AddRepo) } + ToastAction::CopyLogPath(path) => iced::clipboard::write(path.display().to_string()), } - Task::batch(tasks) } /// Signale un échec de clonage ou de recherche, avec le chemin des logs. - fn notify_clone_failure(&mut self, message: &clone::Message) { + fn notify_clone_failure(&mut self, message: &add_repo::Message) { let (title, err, can_retry) = match message { - clone::Message::CloneResult(Err(err)) => ("Échec du clonage", err, true), - clone::Message::SearchResult(version, Err(err)) - if self.clone_panel.is_current_search(*version) => + add_repo::Message::CloneResult(Err(err)) => (t("add_repo_clone_failed"), err, true), + add_repo::Message::SearchResult(version, Err(err)) + if self.add_repo.is_current_search(*version) => { - ("Échec de la recherche", err, false) + (t("add_repo_search_failed"), err, false) } _ => return, }; - let mut notification = Notification::error(title, err.user_message()); + let body = format!("{}\n{}", err.user_message(), err.detail()); + let mut toast = Toast::error(title, body); if can_retry { - notification = notification.with_action(NotificationAction::RetryClone); - } - notification = notification.with_action(NotificationAction::CopyLogPath(logs_directory())); - notification.detail = Some(err.detail().to_string()); - self.notifications.push(notification); - } - - /// Signale l'echec d'un auto-fetch sur le depot courant. - fn notify_auto_fetch_failure(&mut self, message: &repo_overview::Message) { - if let repo_overview::Message::ActionFinished { - path, - auto: true, - result: Err(err), - .. - } = message - { - if self.current_repo.as_ref().map(RepoContext::path) == Some(&**path) { - self.notifications - .push(Notification::error("Auto-fetch echoue", err.clone())); - } + toast = toast.with_action(ToastAction::Retry); } + self.toasts + .push(toast.with_action(ToastAction::CopyLogPath(logs_directory()))); } /// Demarre l'auto-fetch du depot courant si l'option est active. @@ -654,37 +977,352 @@ impl GitSpaceApp { let Some(repo) = self.current_repo.as_ref() else { return Task::none(); }; - self.repo_overview + self.repo_header .auto_fetch(repo, &self.auth_manager) - .map(Message::RepoOverview) + .map(Message::RepoHeader) } } -/// Maps Ctrl+1 to Ctrl+9 (Cmd on macOS) to a tab position, counted from 0. -fn tab_shortcut(key: iced::keyboard::Key, modifiers: iced::keyboard::Modifiers) -> Option { - let iced::keyboard::Key::Character(c) = key else { +/// The window-wide shortcuts. A key a widget already `captured` does nothing, except +/// Escape while searching: the focused search field takes it before anyone else. +fn shortcut( + key: Key, + physical: Physical, + modifiers: Modifiers, + captured: bool, + searching: bool, +) -> Option { + if key == Key::Named(Named::Escape) { + return (!captured || searching).then_some(Message::Escape); + } + if captured { + return None; + } + if key == Key::Named(Named::F2) && modifiers.is_empty() { + return Some(Message::RenameBranch); + } + let side = |message| Some(Message::Sidebar(message)); + match key.as_ref() { + Key::Named(arrow @ (Named::ArrowUp | Named::ArrowDown)) + if modifiers == Modifiers::ALT || (searching && modifiers.is_empty()) => + { + side(sidebar::Message::MoveSelection( + if arrow == Named::ArrowUp { -1 } else { 1 }, + )) + } + Key::Character(c) if modifiers.command() && !modifiers.alt() && !modifiers.shift() => { + match c { + "k" => side(sidebar::Message::ToggleSearch), + "," => side(sidebar::Message::TogglePreferences), + _ => c + .parse::() + .ok() + .or_else(|| digit_key(physical)) + .filter(|digit| (1..=RepoTab::ALL.len()).contains(digit)) + .map(|digit| Message::TabShortcut(digit - 1)), + } + } + _ => None, + } +} + +/// The digit of a top-row key, whatever it types: on AZERTY the 1 key types "&". Keypad keys +/// need no fallback: with NumLock on they type their digit, and with it off they are named +/// keys such as End, which never reach this. +fn digit_key(physical: Physical) -> Option { + let Physical::Code(code) = physical else { return None; }; - let digit = c.parse::().ok().filter(|d| (1..=9).contains(d))?; - (modifiers.command() && !modifiers.alt() && !modifiers.shift()) - .then(|| Message::TabShortcut(digit - 1)) + match code { + Code::Digit1 => Some(1), + Code::Digit2 => Some(2), + Code::Digit3 => Some(3), + Code::Digit4 => Some(4), + _ => None, + } +} + +/// The fetch, pull or push that `msg` reports as succeeded on the open repository `current`: +/// the remote branches, and after a pull HEAD and the working tree, then differ from what the +/// panels show. +fn remote_action_succeeded( + msg: &repo_header::Message, + current: Option<&str>, +) -> Option { + match msg { + repo_header::Message::ActionFinished { + path, + action, + result: Ok(_), + } if current == Some(&**path) => Some(*action), + _ => None, + } +} + +fn accounts_message(message: preferences::accounts::Message) -> Message { + Message::Preferences(preferences::Message::Accounts(message)) +} + +/// Returns whether `path` must be loaded. Picking the open repository again drops a slower +/// load requested before it, so that result cannot replace the repository picked last. +fn needs_load(pending: &mut Option, current: Option<&str>, path: &str) -> bool { + if current != Some(path) { + return true; + } + *pending = None; + false +} + +/// The repository to open on Changes at startup; `None` shows Add repository. +fn startup_target( + reopen_last_repo: bool, + last_repo: Option<&str>, + is_missing: impl Fn(&str) -> bool, +) -> Option { + last_repo + .filter(|path| reopen_last_repo && !is_missing(path)) + .map(str::to_string) +} + +/// Any finished stash job may have changed the working tree: an Apply and drop that +/// left conflicts, or applied and then failed to drop, still returns an error. +fn stash_job_finished(msg: &stashes::Message) -> bool { + matches!(msg, stashes::Message::Done(..)) } #[cfg(test)] mod tests { use super::*; - use iced::keyboard::{Key, Modifiers}; + + fn name(message: Option) -> String { + message.map_or_else(|| "None".to_string(), |message| format!("{message:?}")) + } + + /// The application with nothing open and nothing read from or written to disk. + fn test_app(dir: &std::path::Path) -> GitSpaceApp { + let auth_manager = AuthManager::in_dir(dir); + GitSpaceApp { + active_tab: RepoTab::Changes, + adding: false, + sidebar: Sidebar::default(), + statuses: HashMap::new(), + status_refresh: StatusRefresh::default(), + add_repo: AddRepoPanel::new(String::new(), Default::default()), + repo_header: RepoHeader::new(Default::default()), + changes_panel: ChangesPanel::default(), + history_panel: HistoryPanel::default(), + branches_panel: BranchPanel::new(Vec::new()), + stashes_panel: StashesPanel::default(), + preferences: PreferencesPage::new(auth_manager.clone()), + config: AppConfig::default(), + current_repo: None, + pending_repo: None, + auth_manager, + toasts: Toasts::default(), + } + } + + #[test] + fn picking_a_repository_or_a_tab_closes_preferences() { + let dir = tempfile::tempdir().unwrap(); + let mut app = test_app(dir.path()); + let toggle = || Message::Preferences(preferences::Message::Toggle); + + let _ = app.update(toggle()); + assert!(app.preferences.is_open()); + let _ = app.update(Message::Sidebar(sidebar::Message::Select("/repo".into()))); + assert!(!app.preferences.is_open()); + + let _ = app.update(toggle()); + let _ = app.update(Message::TabShortcut(2)); + assert!(!app.preferences.is_open()); + assert_eq!(app.active_tab, RepoTab::Branches); + + // Ctrl+5 is no tab: Preferences stay. + let _ = app.update(toggle()); + let _ = app.update(Message::TabShortcut(4)); + assert!(app.preferences.is_open()); + } + + #[test] + fn only_a_remote_action_that_succeeded_here_reloads_panels() { + let finished = |path: &str, action, result| repo_header::Message::ActionFinished { + path: Arc::from(path), + action, + result, + }; + use repo_header::RemoteAction::{AutoFetch, Fetch, Pull, Push}; + for action in [Fetch, AutoFetch, Pull, Push] { + let done = finished("/r", action, Ok("done".into())); + assert_eq!(remote_action_succeeded(&done, Some("/r")), Some(action)); + assert_eq!(remote_action_succeeded(&done, Some("/other")), None); + assert_eq!(remote_action_succeeded(&done, None), None); + let failed = finished("/r", action, Err("offline".into())); + assert_eq!(remote_action_succeeded(&failed, Some("/r")), None); + } + } + + #[test] + fn a_fetch_or_a_push_keeps_the_history_selection() { + let dir = tempfile::tempdir().unwrap(); + git2::Repository::init(dir.path()).unwrap(); + let repo = RepoContext::from_path(dir.path()).unwrap(); + let mut app = test_app(dir.path()); + app.current_repo = Some(repo.clone()); + let _ = app.history_panel.load(&repo); + let _ = app + .history_panel + .update(history::Message::Select("abc".into())); + let finished = |action| { + Message::RepoHeader(repo_header::Message::ActionFinished { + path: repo.path_arc(), + action, + result: Ok("done".into()), + }) + }; + use repo_header::RemoteAction::{AutoFetch, Fetch, Pull, Push}; + for action in [Fetch, AutoFetch, Push] { + let _ = app.update(finished(action)); + assert_eq!(app.history_panel.selected(), Some("abc"), "{action:?}"); + } + // A pull moves HEAD: History reads the log again. + let _ = app.update(finished(Pull)); + assert_eq!(app.history_panel.selected(), None); + } #[test] - fn ctrl_digit_selects_a_tab_position() { + fn keyboard_map_covers_search_tabs_and_preferences() { let key = |c: &str| Key::Character(c.into()); - assert!(matches!( - tab_shortcut(key("3"), Modifiers::COMMAND), - Some(Message::TabShortcut(2)) - )); - assert!(tab_shortcut(key("3"), Modifiers::empty()).is_none()); - assert!(tab_shortcut(key("0"), Modifiers::COMMAND).is_none()); - assert!(tab_shortcut(key("a"), Modifiers::COMMAND).is_none()); - assert!(tab_shortcut(key("3"), Modifiers::COMMAND | Modifiers::SHIFT).is_none()); + let up = Key::Named(Named::ArrowUp); + let down = Key::Named(Named::ArrowDown); + let escape = Key::Named(Named::Escape); + let cmd = Modifiers::COMMAND; + let unknown = Physical::Unidentified(iced::keyboard::key::NativeCode::Unidentified); + let shortcut = |key, modifiers, captured, searching| { + shortcut(key, unknown, modifiers, captured, searching) + }; + let free = |key, modifiers| name(shortcut(key, modifiers, false, false)); + + assert_eq!(free(key("k"), cmd), "Sidebar(ToggleSearch)"); + assert_eq!(free(key(","), cmd), "Sidebar(TogglePreferences)"); + assert_eq!(free(key("1"), cmd), "TabShortcut(0)"); + assert_eq!(free(key("4"), cmd), "TabShortcut(3)"); + assert_eq!(free(key("5"), cmd), "None"); + let f2 = Key::Named(Named::F2); + assert_eq!(free(f2.clone(), Modifiers::empty()), "RenameBranch"); + // F2 inside a text field stays with the field. + assert_eq!(name(shortcut(f2, Modifiers::empty(), true, false)), "None"); + assert_eq!(free(key("3"), cmd | Modifiers::SHIFT), "None"); + assert_eq!(free(key("k"), Modifiers::empty()), "None"); + assert_eq!( + free(up.clone(), Modifiers::ALT), + "Sidebar(MoveSelection(-1))" + ); + assert_eq!( + free(down.clone(), Modifiers::ALT), + "Sidebar(MoveSelection(1))" + ); + // Plain arrows only move through the list while the search is open. + assert_eq!(free(down.clone(), Modifiers::empty()), "None"); + assert_eq!( + name(shortcut(down, Modifiers::empty(), false, true)), + "Sidebar(MoveSelection(1))" + ); + assert_eq!(free(escape.clone(), Modifiers::empty()), "Escape"); + + // Keys typed into a field reach nothing, but the search field's Escape closes it. + assert_eq!(name(shortcut(key("k"), cmd, true, false)), "None"); + assert_eq!( + name(shortcut(escape.clone(), Modifiers::empty(), true, false)), + "None" + ); + assert_eq!( + name(shortcut(escape, Modifiers::empty(), true, true)), + "Escape" + ); + } + + #[test] + fn tab_shortcuts_follow_the_digit_keys_on_any_layout() { + let azerty = |typed: &str, code| { + name(super::shortcut( + Key::Character(typed.into()), + Physical::Code(code), + Modifiers::COMMAND, + false, + false, + )) + }; + // AZERTY: the top-row keys type "&", "é", "\"" and "'" without Shift. + assert_eq!(azerty("&", Code::Digit1), "TabShortcut(0)"); + assert_eq!(azerty("é", Code::Digit2), "TabShortcut(1)"); + assert_eq!(azerty("\"", Code::Digit3), "TabShortcut(2)"); + assert_eq!(azerty("'", Code::Digit4), "TabShortcut(3)"); + assert_eq!(azerty("(", Code::Digit5), "None"); + // The keypad types its digit with NumLock on, and is a named key with it off. + assert_eq!(azerty("1", Code::Numpad1), "TabShortcut(0)"); + let end = super::shortcut( + Key::Named(Named::End), + Physical::Code(Code::Numpad1), + Modifiers::COMMAND, + false, + false, + ); + assert_eq!(name(end), "None"); + } + + #[test] + fn startup_target_prefers_the_last_repo() { + let none_missing = |_: &str| false; + let gone = |path: &str| path == "/gone"; + assert_eq!( + startup_target(true, Some("/repo"), none_missing), + Some("/repo".to_string()) + ); + // Turned off, nothing opened yet or the folder is missing: Add repository. + assert_eq!(startup_target(false, Some("/repo"), none_missing), None); + assert_eq!(startup_target(true, None, none_missing), None); + assert_eq!(startup_target(true, Some("/gone"), gone), None); + } + + #[test] + fn picking_the_open_repository_drops_a_slower_pending_load() { + // /a is open and a load of /b is still running. + let mut pending = Some("/b".to_string()); + assert!(!needs_load(&mut pending, Some("/a"), "/a")); + // RepoContextLoaded(/b) now fails the pending check and leaves /a open. + assert_eq!(pending, None); + + assert!(needs_load(&mut pending, Some("/a"), "/b")); + assert!(needs_load(&mut pending, None, "/a")); + } + + #[test] + fn a_failed_stash_job_still_reloads_the_other_panels() { + let done = + |result| stashes::Message::Done(Arc::from("/r"), "stashes_apply_drop_failed", result); + assert!(stash_job_finished(&done(Ok("applied".into())))); + // Apply and drop that kept conflicts: the tree changed, the result is Err. + assert!(stash_job_finished(&done(Err( + t("stashes_conflicts_kept").to_string() + )))); + assert!(!stash_job_finished(&stashes::Message::SelectFile( + "a.txt".into() + ))); + } + + #[test] + fn status_refreshes_share_one_limit_and_drop_older_results() { + let mut refresh = StatusRefresh::default(); + let (first, first_limit) = refresh.start(); + let (second, second_limit) = refresh.start(); + assert!(Arc::ptr_eq(&first_limit, &second_limit)); + assert_eq!(first_limit.available_permits(), STATUS_SCANS); + + // The refresh started after a commit lands first; the older one must not undo it. + assert!(refresh.accept(second)); + assert!(!refresh.accept(first)); + let (third, _) = refresh.start(); + assert!(refresh.accept(third)); } } diff --git a/src/ui/auth.rs b/src/ui/auth.rs deleted file mode 100644 index 031fe7b..0000000 --- a/src/ui/auth.rs +++ /dev/null @@ -1,833 +0,0 @@ -//! Panneau d'authentification avec flux OAuth et saisie manuelle de tokens. -//! -//! Gère la connexion à GitHub (device flow), à GitLab (OAuth2 PKCE) -//! ou via la saisie manuelle d'un jeton d'accès personnel. - -use std::sync::mpsc::{self, Receiver, Sender}; - -use iced::futures::{SinkExt, Stream}; -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; -use iced::{Alignment, Element, Length, Task}; - -use crate::auth::{AuthManager, DeviceFlow, OAuthProvider, OAuthResult}; -use crate::ui::theme::Theme; - -/// Identifiants client OAuth configurés au moment de la compilation. Quand ils sont définis, -/// ils remplacent l'identifiant saisi dans l'interface. -/// -/// GitHub (device flow) : une application OAuth sur https://github.com/settings/developers avec -/// « Enable Device Flow » coché ; l'URL de callback n'est pas utilisée. -/// GitLab (PKCE) : une application sur https://gitlab.com/-/user_settings/applications avec -/// « Confidential » décoché et l'URI de redirection http://127.0.0.1:9876/callback. -const GITHUB_CLIENT_ID: Option<&str> = option_env!("GITSPACE_GITHUB_CLIENT_ID"); -const GITLAB_CLIENT_ID: Option<&str> = option_env!("GITSPACE_GITLAB_CLIENT_ID"); - -/// Messages émis par le panneau d'authentification. -#[derive(Debug, Clone)] -pub enum Message { - /// Démarrer le flux OAuth GitHub. - StartGithubOAuth, - /// Démarrer le flux OAuth GitLab. - StartGitlabOAuth, - /// Étape d'une connexion GitHub, avec l'identifiant de la tentative. - GithubSignIn(u64, GithubSignInEvent), - /// Annuler la connexion GitHub en cours. - CancelGithubSignIn, - /// Copier le code GitHub dans le presse-papiers. - CopyGithubCode, - /// Ouvrir la page de vérification GitHub dans le navigateur. - OpenGithubVerification, - /// Résultat du flux OAuth GitLab. - GitlabOAuthResult(OAuthResult), - /// Le champ hôte manuel a changé. - ManualHostChanged(String), - /// Le champ token manuel a changé. - ManualTokenChanged(String), - /// Valider et enregistrer le token saisi manuellement. - ValidateAndSave, - /// Résultat de la validation du token manuel. - ValidationResult(Result<(), String>), - /// Identifiant client GitHub personnalisé modifié. - GithubClientIdChanged(String), - /// Identifiant client GitLab personnalisé modifié. - GitlabClientIdChanged(String), - /// Déconnecter un compte (par hôte). - Disconnect(String), - /// Résultat de la déconnexion d'un compte. - Disconnected(Result<(), String>), - /// Résultat de l'enregistrement d'un token OAuth reçu. - OAuthStored(OAuthService, Result<(), String>), - /// Comptes enregistrés relus : hôte et présence d'un token OAuth. - AccountsLoaded(Vec<(String, bool)>), -} - -/// Fournisseur d'une connexion OAuth. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum OAuthService { - GitHub, - GitLab, -} - -impl OAuthService { - fn label(self) -> &'static str { - match self { - Self::GitHub => "GitHub", - Self::GitLab => "GitLab", - } - } -} - -/// Étape envoyée par la tâche de fond d'une connexion GitHub. -#[derive(Debug, Clone)] -pub enum GithubSignInEvent { - /// GitHub a fourni le code à saisir sur la page de vérification. - Code { - user_code: String, - verification_uri: String, - }, - /// La connexion est terminée, acceptée, refusée, expirée ou annulée. - Finished(OAuthResult), -} - -/// Connexion GitHub en cours (device flow). -#[derive(Debug, Clone)] -struct GithubSignIn { - /// Identifiant de la tentative : les étapes d'une tentative annulée sont ignorées. - id: u64, - /// Code et page de vérification, une fois reçus de GitHub. - code: Option<(String, String)>, - /// Le supprimer arrête l'attente du jeton côté tâche de fond. - _cancel: Sender<()>, -} - -/// État du panneau d'authentification. -#[derive(Debug, Clone)] -pub struct AuthPanel { - /// Gestionnaire d'authentification partagé. - auth: AuthManager, - /// Message de statut pour GitHub. - github_status: Option, - /// Message de statut pour GitLab. - gitlab_status: Option, - /// Connexion GitHub en cours. - github_sign_in: Option, - /// Identifiant de la prochaine tentative de connexion GitHub. - next_github_sign_in: u64, - /// Indique si un flux OAuth GitLab est en cours. - gitlab_in_progress: bool, - /// Hôte saisi manuellement. - manual_host: String, - /// Token saisi manuellement. - manual_token: String, - /// Message de statut pour la saisie manuelle. - manual_status: Option, - /// Indique si une validation manuelle est en cours. - manual_validating: bool, - /// Identifiant client GitHub personnalisé. - custom_github_client_id: String, - /// Identifiant client GitLab personnalisé. - custom_gitlab_client_id: String, - /// Comptes enregistrés (hôte, OAuth), relus en tâche de fond après chaque changement. - accounts: Vec<(String, bool)>, - /// Erreur de la dernière déconnexion. - accounts_status: Option, -} - -impl AuthPanel { - /// Crée un nouveau panneau d'authentification. - pub fn new(auth: AuthManager) -> Self { - Self { - auth, - github_status: None, - gitlab_status: None, - github_sign_in: None, - next_github_sign_in: 0, - gitlab_in_progress: false, - manual_host: String::new(), - manual_token: String::new(), - manual_status: None, - manual_validating: false, - custom_github_client_id: String::new(), - custom_gitlab_client_id: String::new(), - accounts: Vec::new(), - accounts_status: None, - } - } - - /// Met à jour le gestionnaire d'authentification et relit les comptes. - pub fn set_auth_manager(&mut self, auth: AuthManager) -> Task { - self.auth = auth; - self.refresh_accounts() - } - - /// Relit les comptes enregistrés hors du thread UI : la liste des hôtes lit un fichier et - /// chaque test OAuth interroge le trousseau. - pub fn refresh_accounts(&self) -> Task { - let auth = self.auth.clone(); - Task::perform( - async move { - tokio::task::spawn_blocking(move || { - auth.known_hosts() - .into_iter() - .filter(|host| !host.starts_with("oauth:")) - .map(|host| { - let oauth = auth.has_oauth(&host); - (host, oauth) - }) - .collect() - }) - .await - .unwrap_or_default() - }, - Message::AccountsLoaded, - ) - } - - /// Message de statut de la connexion OAuth d'un fournisseur. - fn status_mut(&mut self, service: OAuthService) -> &mut Option { - match service { - OAuthService::GitHub => &mut self.github_status, - OAuthService::GitLab => &mut self.gitlab_status, - } - } - - /// Traite la fin d'une connexion OAuth : un token reçu est enregistré en tâche de fond. - fn finish_oauth(&mut self, service: OAuthService, result: OAuthResult) -> Task { - let status = match result { - OAuthResult::Success(token) => { - *self.status_mut(service) = Some("Enregistrement du token...".to_string()); - let auth = self.auth.clone(); - return Task::perform( - async move { - tokio::task::spawn_blocking(move || auth.store_oauth_token(&token)) - .await - .unwrap_or_else(|err| Err(err.to_string())) - }, - move |result| Message::OAuthStored(service, result), - ); - } - OAuthResult::Cancelled => "Connexion annulée".to_string(), - OAuthResult::Error(e) => format!("Erreur de connexion : {e}"), - }; - *self.status_mut(service) = Some(status); - Task::none() - } - - /// Traite un message et renvoie une tâche Iced. - pub fn update(&mut self, message: Message) -> Task { - match message { - Message::StartGithubOAuth => { - let client_id = if let Some(id) = GITHUB_CLIENT_ID { - id.to_string() - } else if !self.custom_github_client_id.trim().is_empty() { - self.custom_github_client_id.trim().to_string() - } else { - self.github_status = - Some("Veuillez configurer un identifiant client GitHub".to_string()); - return Task::none(); - }; - - let id = self.next_github_sign_in; - self.next_github_sign_in += 1; - let (cancel, cancelled) = mpsc::channel(); - self.github_status = None; - self.github_sign_in = Some(GithubSignIn { - id, - code: None, - _cancel: cancel, - }); - - Task::run( - github_device_flow(OAuthProvider::github(&client_id), cancelled), - move |event| Message::GithubSignIn(id, event), - ) - } - - Message::StartGitlabOAuth => { - let client_id = if let Some(id) = GITLAB_CLIENT_ID { - id.to_string() - } else if !self.custom_gitlab_client_id.trim().is_empty() { - self.custom_gitlab_client_id.trim().to_string() - } else { - self.gitlab_status = - Some("Veuillez configurer un identifiant client GitLab".to_string()); - return Task::none(); - }; - - self.gitlab_status = - Some("Ouverture du navigateur pour la connexion...".to_string()); - self.gitlab_in_progress = true; - - let auth = self.auth.clone(); - let provider = OAuthProvider::gitlab(&client_id); - - Task::perform( - tokio::task::spawn_blocking(move || auth.start_oauth(provider)), - |result| match result { - Ok(oauth_result) => Message::GitlabOAuthResult(oauth_result), - Err(err) => Message::GitlabOAuthResult(OAuthResult::Error(err.to_string())), - }, - ) - } - - Message::GithubSignIn(id, event) => { - if self.github_sign_in.as_ref().map(|sign_in| sign_in.id) != Some(id) { - return Task::none(); - } - let result = match event { - GithubSignInEvent::Code { - user_code, - verification_uri, - } => { - if let Some(sign_in) = &mut self.github_sign_in { - sign_in.code = Some((user_code, verification_uri)); - } - return Task::none(); - } - GithubSignInEvent::Finished(result) => result, - }; - self.github_sign_in = None; - self.finish_oauth(OAuthService::GitHub, result) - } - - Message::CancelGithubSignIn => { - // Supprimer la tentative ferme son canal d'annulation et arrête l'attente. - self.github_sign_in = None; - self.github_status = Some("Connexion annulée".to_string()); - Task::none() - } - - Message::CopyGithubCode => match self.github_code() { - Some((user_code, _)) => iced::clipboard::write(user_code.to_string()), - None => Task::none(), - }, - - Message::OpenGithubVerification => { - if let Some((_, verification_uri)) = self.github_code() { - if let Err(err) = webbrowser::open(verification_uri) { - self.github_status = - Some(format!("Impossible d'ouvrir le navigateur : {err}")); - } - } - Task::none() - } - - Message::GitlabOAuthResult(result) => { - self.gitlab_in_progress = false; - self.finish_oauth(OAuthService::GitLab, result) - } - - Message::OAuthStored(service, result) => { - *self.status_mut(service) = Some(match result { - Ok(()) => format!("Connexion {} réussie !", service.label()), - Err(e) => format!("Erreur de stockage du token : {e}"), - }); - self.refresh_accounts() - } - - Message::ManualHostChanged(value) => { - self.manual_host = value; - Task::none() - } - - Message::ManualTokenChanged(value) => { - self.manual_token = value; - Task::none() - } - - Message::ValidateAndSave => { - let host = self.manual_host.trim().to_string(); - let token = self.manual_token.trim().to_string(); - - if host.is_empty() || token.is_empty() { - self.manual_status = - Some("L'hôte et le token ne peuvent pas être vides".to_string()); - return Task::none(); - } - - self.manual_status = Some("Validation du token en cours...".to_string()); - self.manual_validating = true; - - let auth = self.auth.clone(); - - // Valider et stocker le token de manière asynchrone. - Task::perform( - async move { auth.validate_and_store(&host, &token).await }, - Message::ValidationResult, - ) - } - - Message::ValidationResult(result) => { - self.manual_validating = false; - match result { - Ok(()) => { - self.manual_status = Some("Token validé et enregistré !".to_string()); - self.manual_token.clear(); - return self.refresh_accounts(); - } - Err(e) => { - self.manual_status = Some(format!("Validation échouée : {e}")); - } - } - Task::none() - } - - Message::GithubClientIdChanged(value) => { - self.custom_github_client_id = value; - Task::none() - } - - Message::GitlabClientIdChanged(value) => { - self.custom_gitlab_client_id = value; - Task::none() - } - - Message::Disconnect(host) => { - self.accounts_status = None; - let auth = self.auth.clone(); - Task::perform( - async move { - tokio::task::spawn_blocking(move || { - // Supprimer le token OAuth ou le token simple selon le cas. - if auth.has_oauth(&host) { - auth.clear_oauth_token(&host) - } else { - auth.clear_token(&host) - } - }) - .await - .unwrap_or_else(|err| Err(err.to_string())) - }, - Message::Disconnected, - ) - } - - Message::Disconnected(result) => { - if let Err(e) = result { - self.accounts_status = Some(format!("Déconnexion échouée : {e}")); - } - self.refresh_accounts() - } - - Message::AccountsLoaded(accounts) => { - self.accounts = accounts; - Task::none() - } - } - } - - /// Construit la vue Iced du panneau d'authentification. - pub fn view<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - // En-tête du panneau. - let heading = text("Authentification") - .size(typo.heading) - .color(palette.text_primary); - - let description = - text("Connectez vos comptes de fournisseurs Git pour un acces fluide aux depots.") - .size(typo.body) - .color(palette.text_secondary); - - // Section des comptes connectés. - let accounts_section = self.view_connected_accounts(theme); - - // Section des boutons OAuth. - let oauth_section = self.view_oauth_section(theme); - - // Section de saisie manuelle. - let manual_section = self.view_manual_section(theme); - - let content = column![ - heading, - description, - Space::with_height(theme.spacing.lg), - accounts_section, - Space::with_height(theme.spacing.lg), - oauth_section, - Space::with_height(theme.spacing.lg), - manual_section, - ] - .spacing(theme.spacing.xs) - .width(Length::Fill); - - scrollable( - container(content) - .width(Length::Fill) - .padding(theme.spacing.md), - ) - .width(Length::Fill) - .height(Length::Fill) - .into() - } - - /// Construit la section des comptes connectés. - fn view_connected_accounts<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let title = text("Comptes connectes") - .size(typo.title) - .color(palette.text_primary); - - let subtitle = text("Vos fournisseurs Git authentifies") - .size(typo.label) - .color(palette.text_secondary); - - let mut items = column![].spacing(theme.spacing.xs); - - if self.accounts.is_empty() { - items = items.push( - text("Aucun compte connecte. Utilisez les boutons ci-dessous pour vous connecter.") - .size(typo.body) - .color(palette.text_secondary), - ); - } else { - for (host, has_oauth) in &self.accounts { - let auth_type = if *has_oauth { "OAuth" } else { "Token" }; - - // Icône selon le fournisseur. - let icon_str = if host.contains("github") { - "GitHub" - } else if host.contains("gitlab") { - "GitLab" - } else { - "Git" - }; - - let label = text(format!("{icon_str} - {host} ({auth_type})")) - .size(typo.body) - .color(palette.text_primary); - - let disconnect_btn = button( - text("Deconnecter") - .size(typo.label) - .color(palette.text_primary), - ) - .on_press(Message::Disconnect(host.to_string())); - - let account_row = row![label, Space::with_width(Length::Fill), disconnect_btn] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - items = items.push(account_row); - } - } - if let Some(status) = &self.accounts_status { - items = items.push( - text(status.as_str()) - .size(typo.label) - .color(palette.text_secondary), - ); - } - - column![title, subtitle, Space::with_height(theme.spacing.sm), items] - .spacing(theme.spacing.xs) - .into() - } - - /// Code GitHub en attente de saisie et sa page de vérification. - fn github_code(&self) -> Option<(&str, &str)> { - let (user_code, verification_uri) = self.github_sign_in.as_ref()?.code.as_ref()?; - Some((user_code, verification_uri)) - } - - /// Construit le bloc du code GitHub pendant une connexion. - fn view_github_sign_in<'a>(&'a self, theme: &'a Theme) -> Option> { - let sign_in = self.github_sign_in.as_ref()?; - let palette = &theme.palette; - let typo = &theme.typography; - let small_button = |label: &'a str, message: Message| { - button(text(label).size(typo.label).color(palette.text_primary)).on_press(message) - }; - - let content: Element<'a, Message> = match &sign_in.code { - None => row![ - text("Demande d'un code de connexion à GitHub...") - .size(typo.body) - .color(palette.text_secondary), - small_button("Annuler", Message::CancelGithubSignIn), - ] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center) - .into(), - Some((user_code, verification_uri)) => column![ - text(format!("Saisissez ce code sur {verification_uri} :")) - .size(typo.body) - .color(palette.text_secondary), - text(user_code.as_str()) - .size(typo.heading) - .color(palette.text_primary), - row![ - small_button("Copier le code", Message::CopyGithubCode), - small_button("Ouvrir dans le navigateur", Message::OpenGithubVerification), - small_button("Annuler", Message::CancelGithubSignIn), - ] - .spacing(theme.spacing.sm), - text("En attente de votre validation sur GitHub...") - .size(typo.label) - .color(palette.text_secondary), - ] - .spacing(theme.spacing.xs) - .into(), - }; - Some(content) - } - - /// Construit la section des boutons de connexion OAuth. - fn view_oauth_section<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let title = text("Connexion OAuth") - .size(typo.title) - .color(palette.text_primary); - - let description = text( - "GitHub affiche un code à saisir sur sa page de connexion. GitLab ouvre une fenêtre de navigateur.", - ) - .size(typo.body) - .color(palette.text_secondary); - - // Bouton GitHub OAuth. - let github_available = self.github_sign_in.is_none() - && (GITHUB_CLIENT_ID.is_some() || !self.custom_github_client_id.trim().is_empty()); - - let mut github_btn = button( - text("Connexion GitHub") - .size(typo.body) - .color(palette.text_primary), - ); - if github_available { - github_btn = github_btn.on_press(Message::StartGithubOAuth); - } - - // Bouton GitLab OAuth. - let gitlab_available = !self.gitlab_in_progress - && (GITLAB_CLIENT_ID.is_some() || !self.custom_gitlab_client_id.trim().is_empty()); - - let mut gitlab_btn = button( - text("Connexion GitLab") - .size(typo.body) - .color(palette.text_primary), - ); - if gitlab_available { - gitlab_btn = gitlab_btn.on_press(Message::StartGitlabOAuth); - } - - let oauth_buttons = row![github_btn, Space::with_width(theme.spacing.md), gitlab_btn] - .align_y(Alignment::Center); - - // Code GitHub puis messages de statut. - let mut status_col = column![].spacing(theme.spacing.xs); - if let Some(sign_in) = self.view_github_sign_in(theme) { - status_col = status_col.push(sign_in); - } - if let Some(status) = &self.github_status { - status_col = status_col.push( - text(format!("GitHub : {status}")) - .size(typo.label) - .color(palette.text_secondary), - ); - } - if let Some(status) = &self.gitlab_status { - status_col = status_col.push( - text(format!("GitLab : {status}")) - .size(typo.label) - .color(palette.text_secondary), - ); - } - - // Section de configuration des identifiants OAuth. - let oauth_config = self.view_oauth_config(theme); - - column![ - title, - description, - Space::with_height(theme.spacing.sm), - oauth_buttons, - status_col, - Space::with_height(theme.spacing.sm), - oauth_config, - ] - .spacing(theme.spacing.xs) - .into() - } - - /// Construit la sous-section de configuration des identifiants OAuth. - fn view_oauth_config<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let config_hint = text( - "Pour utiliser OAuth, enregistrez une application OAuth chez votre fournisseur et entrez l'identifiant client.\n\ - GitHub : cochez « Enable Device Flow » dans l'application ; l'URL de callback n'est pas utilisée.\n\ - GitLab : décochez « Confidential » et indiquez l'URI de redirection http://127.0.0.1:9876/callback", - ) - .size(typo.label) - .color(palette.text_secondary); - - let github_label = text("GitHub Client ID :") - .size(typo.label) - .color(palette.text_secondary); - - let github_input = text_input("Identifiant OAuth GitHub", &self.custom_github_client_id) - .on_input(Message::GithubClientIdChanged) - .width(Length::Fixed(280.0)); - - let github_row = row![github_label, github_input] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - let gitlab_label = text("GitLab Client ID :") - .size(typo.label) - .color(palette.text_secondary); - - let gitlab_input = text_input("Identifiant OAuth GitLab", &self.custom_gitlab_client_id) - .on_input(Message::GitlabClientIdChanged) - .width(Length::Fixed(280.0)); - - let gitlab_row = row![gitlab_label, gitlab_input] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - // Note sur les variables d'environnement. - let mut col = column![ - config_hint, - Space::with_height(theme.spacing.xs), - github_row, - gitlab_row - ] - .spacing(theme.spacing.xs); - - if GITHUB_CLIENT_ID.is_some() || GITLAB_CLIENT_ID.is_some() { - col = col.push( - text( - "Note : des identifiants OAuth integres sont configures via \ - GITSPACE_GITHUB_CLIENT_ID / GITSPACE_GITLAB_CLIENT_ID.", - ) - .size(typo.label) - .color(palette.text_secondary), - ); - } - - col.into() - } - - /// Construit la section de saisie manuelle de tokens. - fn view_manual_section<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let title = text("Saisie manuelle de token") - .size(typo.title) - .color(palette.text_primary); - - let description = text( - "Pour les utilisateurs avances : saisissez un jeton d'acces personnel.\n\ - Utile pour les instances auto-hebergees ou lorsque OAuth n'est pas disponible.", - ) - .size(typo.body) - .color(palette.text_secondary); - - // Champ hôte. - let host_label = text("Hote :").size(typo.body).color(palette.text_secondary); - - let host_input = text_input("ex. github.com ou gitlab.example.com", &self.manual_host) - .on_input(Message::ManualHostChanged) - .width(Length::Fixed(280.0)); - - let host_row = row![host_label, host_input] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - // Champ token (masqué). - let token_label = text("Token :") - .size(typo.body) - .color(palette.text_secondary); - - let token_input = text_input("Jeton d'acces personnel", &self.manual_token) - .on_input(Message::ManualTokenChanged) - .secure(true) - .width(Length::Fixed(300.0)); - - let token_row = row![token_label, token_input] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - // Bouton de validation. - let can_save = !self.manual_host.trim().is_empty() - && !self.manual_token.trim().is_empty() - && !self.manual_validating; - - let mut save_btn = button( - text("Valider et enregistrer") - .size(typo.body) - .color(palette.text_primary), - ); - if can_save { - save_btn = save_btn.on_press(Message::ValidateAndSave); - } - - // Message de statut. - let mut col = column![ - title, - description, - Space::with_height(theme.spacing.sm), - host_row, - token_row, - Space::with_height(theme.spacing.xs), - save_btn, - ] - .spacing(theme.spacing.xs); - - if let Some(status) = &self.manual_status { - col = col.push( - text(status.as_str()) - .size(typo.label) - .color(palette.text_secondary), - ); - } - - col.into() - } -} - -/// Connexion GitHub par device flow : demande un code, l'envoie à l'interface, puis attend que -/// l'utilisateur l'accepte ou le refuse, que le code expire ou que `cancelled` soit fermé. -fn github_device_flow( - provider: OAuthProvider, - cancelled: Receiver<()>, -) -> impl Stream { - iced::stream::channel(2, move |mut output| async move { - let flow = match tokio::task::spawn_blocking(move || DeviceFlow::start(provider)).await { - Ok(Ok(flow)) => flow, - Ok(Err(err)) => { - let _ = output - .send(GithubSignInEvent::Finished(OAuthResult::Error(err))) - .await; - return; - } - Err(err) => { - let _ = output - .send(GithubSignInEvent::Finished(OAuthResult::Error( - err.to_string(), - ))) - .await; - return; - } - }; - let _ = output - .send(GithubSignInEvent::Code { - user_code: flow.user_code().to_string(), - verification_uri: flow.verification_uri().to_string(), - }) - .await; - let result = tokio::task::spawn_blocking(move || flow.wait(&cancelled)) - .await - .unwrap_or_else(|err| OAuthResult::Error(err.to_string())); - let _ = output.send(GithubSignInEvent::Finished(result)).await; - }) -} diff --git a/src/ui/branches.rs b/src/ui/branches.rs index 2f8dcf5..8fad8a5 100644 --- a/src/ui/branches.rs +++ b/src/ui/branches.rs @@ -1,1166 +1,1572 @@ -// Panneau de gestion des branches pour l'interface Iced. -// Affiche les branches locales et distantes dans une arborescence, -// permet la creation, suppression, renommage, archivage et comparaison. -// Les appels git tournent en tache de fond ; view() ne lit que l'etat du panneau. +//! The Branches tab: the branch list grouped as local, then one group per remote, and the +//! selected branch with its relation card, its actions and its own commits. +//! Git reads and actions run in background tasks; `view` only reads the panel's state. -use std::collections::BTreeMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use chrono::Utc; -use git2::BranchType; -use iced::widget::{ - button, checkbox, column, container, horizontal_rule, row, scrollable, text, text_input, - Button, Space, -}; -use iced::{Element, Length, Task}; - -use crate::ui::theme::Theme; +use colony_ui::theme::Palette; +use colony_ui::widgets::icons; +use colony_ui::{fonts, Typography}; +use git2::Oid; +use iced::widget::{button, column, container, pick_list, row, scrollable, text, text_input}; +use iced::widget::{Column, Space}; +use iced::{Alignment, Border, Element, Length, Task}; use crate::git::branch::{ archive_branch, checkout_branch, create_branch, create_tracking_branch, delete_branch, - list_branches, rename_branch, BranchEntry, BranchKind, + head_commit, list_branch_overview, rename_branch, set_upstream, BranchKind, BranchOverview, }; -use crate::git::compare::{compare_branch_with_head, BranchComparison, DiffSummary}; -use crate::git::log::{commits_between_refs, latest_commit_for_branch, CommitInfo}; -use crate::git::merge::{detect_conflicts, merge_branch, MergeOutcome, MergeStrategy}; -use crate::git::repo_cache::with_cached_repo; -use crate::ui::context::RepoContext; -use crate::ui::stage::git_task; - -/// Nombre de jours sans commit avant qu'une branche soit consideree obsolete. +use crate::git::log::{commits_between_refs, read_commit_log, CommitFilter, CommitInfo}; +use crate::git::merge::{merge_branch, MergeStrategy}; +use crate::i18n::{t, tf}; +use crate::ui::changes::{field, horizontal_divider, item, question, vertical_divider}; +use crate::ui::context::{git_task, RepoContext}; +use crate::ui::history::relative_time; +use crate::ui::widgets::button as gs_button; +use crate::ui::widgets::ellipsis::ellipsis; +use crate::ui::widgets::menu::{self, Entry, MenuItem}; +use crate::ui::widgets::segmented::segmented; +use crate::ui::widgets::toast::Toast; + +/// Days without a commit before a branch counts as stale. const STALE_DAYS: i64 = 30; - -/// Nombre de branches distantes par page. +/// Remote branches per page of a remote group. const REMOTE_PAGE_SIZE: usize = 25; +/// Commits listed under "Commits only on ". +const OWN_COMMITS: usize = 30; +/// Commits listed under "Latest commits on " for the current branch. +const LATEST_COMMITS: usize = 10; +const LIST_WIDTH: f32 = 280.0; +const MORE_GLYPH: &str = "\u{f141}"; +const CURRENT_GLYPH: &str = "\u{f111}"; +const STAR_GLYPH: &str = "\u{f005}"; +const BRANCH_GLYPH: &str = "\u{e725}"; +const CLOUD_GLYPH: &str = "\u{f0c2}"; +const PREVIOUS_GLYPH: &str = "\u{f053}"; + +/// What can be done with a branch, in the order the screen shows it: the actions under the +/// relation card, then the "⋯" menu. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BranchAction { + Checkout, + Merge, + Rebase, + Rename, + Pin, + CopyName, + ChangeUpstream, + Archive, + Delete, +} -// --------------------------------------------------------------------------- -// Arborescence des branches -// --------------------------------------------------------------------------- - -/// Noeud d'arborescence utilise pour regrouper les branches par prefixe (ex. feature/). -#[derive(Default)] -struct BranchNode { - label: String, - children: BTreeMap, - branch: Option, +/// The actions that make sense for `branch`. The current branch cannot be checked out, +/// merged into itself, rebased onto itself or deleted; remote branches are only read. +pub fn available_actions(branch: &BranchOverview) -> Vec { + use BranchAction::*; + let local = branch.kind == BranchKind::Local; + let other = !branch.is_head; + [ + (Checkout, other), + (Merge, other), + (Rebase, other), + (Rename, local), + (Pin, true), + (CopyName, true), + (ChangeUpstream, local), + (Archive, local), + (Delete, local && other), + ] + .into_iter() + .filter_map(|(action, shown)| shown.then_some(action)) + .collect() } -impl BranchNode { - /// Insere une branche dans l'arbre en decoupant le nom par segments. - fn insert(&mut self, segments: &[&str], branch: BranchEntry) { - if segments.is_empty() { - self.branch = Some(branch); - return; +/// The line under the merge / rebase button saying what the chosen action will do. +pub fn action_note( + strategy: Option, + branch: &str, + current: &str, + ahead: usize, +) -> String { + let names = [("branch", branch), ("current", current)]; + match strategy { + Some(MergeStrategy::Merge) => { + let count = ahead.to_string(); + tf( + "branches_note_merge", + &[names[0], names[1], ("count", &count)], + ) } - - let Some((first, rest)) = segments.split_first() else { - return; - }; - let node = self.children.entry(first.to_string()).or_default(); - node.label = first.to_string(); - node.insert(rest, branch); + Some(MergeStrategy::Rebase) => tf("branches_note_rebase", &names), + None => String::new(), } } -/// Entree aplatie de l'arborescence, prete a etre affichee dans une liste. -struct FlatEntry { - /// Niveau d'indentation (0 = racine). - depth: usize, - /// Vrai si c'est un dossier (noeud intermediaire). - is_folder: bool, - /// Libelle affiche (segment du nom). - label: String, - /// Branche associee si c'est une feuille. - branch: Option, +/// The selected branch against the current one: commits it has that the current branch +/// lacks, and the reverse. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RelationCard { + pub ahead: usize, + pub behind: usize, + pub against: String, } -/// Aplatit recursivement un noeud en une liste de `FlatEntry`. -fn flatten_node(node: &BranchNode, depth: usize, out: &mut Vec) { - // Si le noeud a des enfants, c'est un dossier - if !node.children.is_empty() { - if depth > 0 || !node.label.is_empty() { - out.push(FlatEntry { - depth, - is_folder: true, - label: node.label.clone(), - branch: None, +impl RelationCard { + /// Another branch against the current one, or the current branch against its upstream; + /// `None` for a current branch without an upstream. + fn new(branch: &BranchOverview, current: &str) -> Option { + if !branch.is_head { + return Some(Self { + ahead: branch.ahead_of_head, + behind: branch.behind_head, + against: current.to_string(), }); } - for child in node.children.values() { - flatten_node(child, depth + 1, out); - } - } else if let Some(branch) = &node.branch { - // Feuille : branche concrete - out.push(FlatEntry { - depth, - is_folder: false, - label: node.label.clone(), - branch: Some(branch.clone()), - }); + branch.upstream.as_ref().map(|upstream| Self { + ahead: branch.upstream_ahead, + behind: branch.upstream_behind, + against: upstream.clone(), + }) } } -// --------------------------------------------------------------------------- -// Donnees chargees en tache de fond -// --------------------------------------------------------------------------- +/// The branch selected when none is: the first local branch other than the current one, in +/// list order with pinned branches first, or else the current branch. +fn initial_selection<'a>(branches: &'a [BranchOverview], pinned: &[String]) -> Option<&'a str> { + let local = |branch: &&BranchOverview| branch.kind == BranchKind::Local; + branches + .iter() + .filter(local) + .filter(|branch| !branch.is_head) + // min_by_key keeps the first of equal keys, so names stay in list order. + .min_by_key(|branch| !pinned.contains(&branch.name)) + .or_else(|| branches.iter().filter(local).find(|branch| branch.is_head)) + .map(|branch| branch.name.as_str()) +} -/// Branches, dernier commit de chacune et conflits en cours. -#[derive(Debug, Clone)] -pub struct BranchSnapshot { - branches: Vec, - commits: BTreeMap, - conflicts: Vec, +/// The remote branches of one remote, as its list group shows them. +#[derive(Debug)] +pub struct RemoteGroup<'a> { + pub remote: &'a str, + pub branches: Vec<&'a BranchOverview>, } -/// Comparaison de la branche selectionnee avec HEAD. -#[derive(Debug, Clone)] -pub struct Selection { - comparison: BranchComparison, - /// `Some(false)` si la branche locale a des commits absents de HEAD ; `None` si - /// inconnu ou branche distante. - merged: Option, +/// Groups remote branches by remote, keeping their order; remotes come in the order their +/// first branch does. +pub fn remote_groups<'a>(branches: &[&'a BranchOverview]) -> Vec> { + let mut groups: Vec> = Vec::new(); + for branch in branches.iter().filter(|b| b.kind == BranchKind::Remote) { + // shortcut: the remote is the name up to the first '/', wrong for a remote whose own name has one; read repo.remotes() if that shows up. + let remote = branch + .name + .split_once('/') + .map_or(branch.name.as_str(), |(remote, _)| remote); + match groups.iter_mut().find(|group| group.remote == remote) { + Some(group) => group.branches.push(branch), + None => groups.push(RemoteGroup { + remote, + branches: vec![branch], + }), + } + } + groups } -/// Resultat de "Comparer avec la branche courante". -#[derive(Debug, Clone)] -pub struct Comparison { - diff: Option, - commits: Vec, +/// A choice of the "Change upstream…" picker. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum UpstreamChoice { + None, + Branch(String), +} + +impl std::fmt::Display for UpstreamChoice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::None => f.write_str(t("branches_no_upstream_choice")), + Self::Branch(name) => f.write_str(name), + } + } } -/// Action destructive en attente de confirmation. +/// The band open under the detail header: a name to type, an upstream to pick, or a +/// question to confirm. All but `NewBranch` act on the selected branch. #[derive(Debug, Clone, PartialEq, Eq)] -enum Pending { - Delete(String), - Merge(String), - Rebase(String), +pub enum Band { + NewBranch(String), + Rename(String), + Upstream(UpstreamChoice), + Archive, + Delete, + Merge, + Rebase, } -// --------------------------------------------------------------------------- -// Messages -// --------------------------------------------------------------------------- +/// How a git action ended. +#[derive(Debug, Clone)] +pub enum Outcome { + /// The success message. + Done(String), + /// A merge or rebase stopped on these files. + Conflicts(Vec), +} -/// Ensemble des actions possibles depuis le panneau de branches. #[derive(Debug, Clone)] pub enum Message { - /// Le contenu du champ de creation a change. - NewBranchChanged(String), - /// Demande de creation de branche. - CreateBranch, - /// Selection d'une branche (par nom). - SelectBranch(String), - /// Basculer sur une branche. - Checkout(String), - /// Basculer et configurer le suivi distant. - CheckoutAndTrack(String), - /// Demander la suppression d'une branche locale. - DeleteBranch(String), - /// Archiver une branche sous forme de tag. - ArchiveBranch(String), - /// Renommer une branche (ancien nom, nouveau nom). - RenameBranch(String, String), - /// Le tampon de renommage a change. - RenameBufferChanged(String), - /// Demander la fusion de la branche selectionnee dans la branche courante. - MergeInto(String), - /// Demander le rebase de la branche courante sur la branche selectionnee - /// (`git rebase `). - RebaseCurrentOnto(String), - /// Executer l'action en attente de confirmation. - Confirm, - /// Abandonner l'action en attente de confirmation. - CancelConfirm, - /// Comparer la branche avec HEAD. - CompareWithCurrent(String), - /// Ouvrir la branche dans le panneau d'historique. - OpenInHistory(String), - /// Epingler / desepingler une branche. - TogglePin(String), - /// Basculer le filtre "branches obsoletes uniquement". + Filter(String), + /// Opens or closes the filter field's "⋯" menu. + FilterMenu(bool), ToggleStaleOnly, - /// Page precedente des branches distantes. - RemotePagePrev, - /// Page suivante des branches distantes. - RemotePageNext, - /// Resultat du chargement des branches. - Loaded(Arc, Result), - /// Details de la branche selectionnee (nom, resultat). - SelectionLoaded(Arc, String, Result), - /// Comparaison avec la branche courante (nom, resultat). - CompareLoaded(Arc, String, Result), - /// Fin d'une action git (message de statut ou erreur). - ActionDone(Arc, Result), - /// Fin d'une fusion ou d'un rebase. - MergeDone(Arc, Result), + /// Collapses or expands a remote's group. + ToggleRemote(String), + /// Shows a page of a remote's group. + RemotePage(String, usize), + Select(String), + /// Opens or closes the selected branch's "⋯" menu. + Menu(bool), + Open(Band), + CloseBand, + BandText(String), + UpstreamPicked(UpstreamChoice), + /// Runs the action of the open band. + Submit, + /// A segment of "Merge into" | "Rebase onto": asks to confirm it. + Strategy(usize), + Checkout, + TogglePin, + CopyName, + ViewInHistory, + /// F2: renames the selected branch. + StartRename, + /// A read of the branches and of HEAD, numbered so that only the latest one is shown. + Loaded(Arc, u64, Result), + /// The commits of a branch that the current one lacks, or the latest ones of the current + /// branch. + CommitsLoaded(Arc, String, Result, String>), + /// The key names the failure title. + ActionDone(Arc, &'static str, Result), } -// --------------------------------------------------------------------------- -// Panneau principal -// --------------------------------------------------------------------------- +/// The branches and the commit HEAD points at. +pub type BranchList = (Vec, Option); -/// Panneau de gestion des branches. pub struct BranchPanel { repo: Option>, - branches: Vec, - branch_commits: BTreeMap, - new_branch: String, - rename_buffer: String, - selected_branch: Option, - /// Details de la selection, `None` pendant le chargement ou apres une erreur. - selection: Option, - selection_loading: bool, - selected_error: Option, - compare_branch: Option, - compare_commits: Vec, - compare_diff: Option, - compare_error: Option, + branches: Vec, + /// The commit HEAD pointed at when `branches` was read. + head: Option, + loading: bool, error: Option, - status: Option, - conflict_files: Vec, + /// Number of the last branch read; older replies are dropped. + request: u64, + filter: String, + filter_menu: bool, stale_only: bool, - open_history_branch: Option, + collapsed: HashSet, + remote_pages: HashMap, + selected: Option, + commits: Vec, + commits_error: Option, + menu: bool, + strategy: MergeStrategy, + band: Option, + busy: bool, pinned_branches: Vec, pending_pinned: Option>, - remote_page: usize, - /// Une action git est en cours : les boutons d'action sont desactives. - busy: bool, - pending: Option, + open_history_branch: Option, } impl BranchPanel { - /// Cree un nouveau panneau avec les branches epinglees fournies. pub fn new(pinned_branches: Vec) -> Self { Self { repo: None, branches: Vec::new(), - branch_commits: BTreeMap::new(), - new_branch: String::new(), - rename_buffer: String::new(), - selected_branch: None, - selection: None, - selection_loading: false, - selected_error: None, - compare_branch: None, - compare_commits: Vec::new(), - compare_diff: None, - compare_error: None, + head: None, + loading: false, error: None, - status: None, - conflict_files: Vec::new(), + request: 0, + filter: String::new(), + filter_menu: false, stale_only: false, - open_history_branch: None, + collapsed: HashSet::new(), + remote_pages: HashMap::new(), + selected: None, + commits: Vec::new(), + commits_error: None, + menu: false, + strategy: MergeStrategy::Merge, + band: None, + busy: false, pinned_branches, pending_pinned: None, - remote_page: 0, - busy: false, - pending: None, + open_history_branch: None, } } - /// Oublie le depot precedent et charge les branches de `repo` en tache de fond. - /// Les branches epinglees sont conservees. + /// Reads the branches of `repo` in the background. Another repository starts from an + /// empty panel with the pinned branches kept. The open one keeps everything, an open band + /// and a running action included: the window regaining focus reloads it. pub fn load(&mut self, repo: &RepoContext) -> Task { - let pinned = std::mem::take(&mut self.pinned_branches); - *self = Self { - repo: Some(repo.path_arc()), - ..Self::new(pinned) - }; + if !self.is_current(repo.path()) { + let pinned = std::mem::take(&mut self.pinned_branches); + // Keep request numbers growing so a reply from before the reset is dropped. + let request = self.request; + *self = Self::new(pinned); + self.repo = Some(repo.path_arc()); + self.request = request; + } self.refresh() } - /// Met a jour les branches epinglees depuis l'exterieur. pub fn set_pinned_branches(&mut self, pinned_branches: Vec) { self.pinned_branches = pinned_branches; } - /// Recupere et consomme les changements d'epingles en attente. + /// The pinned branches after a pin or unpin, once. pub fn take_pinned_changes(&mut self) -> Option> { self.pending_pinned.take() } - /// Recupere et consomme la demande d'ouverture dans l'historique. + /// The branch to show in History, once. pub fn take_history_request(&mut self) -> Option { self.open_history_branch.take() } - // ----------------------------------------------------------------------- - // Mise a jour (logique) - // ----------------------------------------------------------------------- - - /// Traite un message. Les operations git tournent en tache de fond. - pub fn update(&mut self, message: Message, _repo: Option<&RepoContext>) -> Task { + /// Handles a message; the toast, if any, is for the application to show. + pub fn update(&mut self, message: Message) -> (Task, Option) { match message { - Message::NewBranchChanged(value) => { - self.new_branch = value; + Message::Filter(value) => self.filter = value, + Message::FilterMenu(open) => self.filter_menu = open, + Message::ToggleStaleOnly => { + self.filter_menu = false; + self.stale_only = !self.stale_only; } - - Message::CreateBranch => { - let name = self.new_branch.trim().to_string(); - if name.is_empty() { - self.status = None; - self.error = Some("Le nom de branche ne peut pas etre vide".to_string()); - } else { - // The name is repeated in the error message if creation fails. - self.new_branch.clear(); - return self.run(move |repo| { - create_branch(repo, &name, None) - .map(|()| format!("Branche {name} creee depuis HEAD")) - .map_err(|err| format!("Echec de la creation de branche : {err}")) - }); + Message::ToggleRemote(remote) => { + if !self.collapsed.remove(&remote) { + self.collapsed.insert(remote); } } - - Message::SelectBranch(name) => { - if let Some(branch) = self.branches.iter().find(|b| b.name == name).cloned() { - self.rename_buffer = branch.name.clone(); - self.selected_branch = Some(branch); - self.pending = None; - return self.load_selection(); - } + Message::RemotePage(remote, page) => { + self.remote_pages.insert(remote, page); } - - Message::Checkout(name) => { - return self.run(move |repo| { - checkout_branch(repo, &name) - .map(|()| format!("Basculement sur {name}")) - .map_err(|err| format!("Echec du checkout de {name} : {err}")) - }); - } - - Message::CheckoutAndTrack(name) => { - return self.run(move |repo| { - let local = create_tracking_branch(repo, &name).map_err(|e| e.to_string())?; - checkout_branch(repo, &local) - .map(|()| format!("Branche {local} creee et suivie depuis {name}")) - .map_err(|err| format!("Echec du checkout de {local} : {err}")) - }); - } - - Message::DeleteBranch(name) => { - self.pending = Some(Pending::Delete(name)); + Message::Select(name) => return (self.select(name), None), + Message::Menu(open) => self.menu = open, + Message::Open(band) => { + self.menu = false; + self.band = Some(band); } - - Message::ArchiveBranch(name) => { - return self.run(move |repo| { - archive_branch(repo, &name) - .map(|tag| format!("Branche {name} archivee sous le tag {tag}")) - .map_err(|err| err.to_string()) - }); - } - - Message::RenameBranch(old, new) => { - if !new.is_empty() && new != old { - return self.run(move |repo| { - rename_branch(repo, &old, &new) - .map(|()| format!("Branche {old} renommee en {new}")) - .map_err(|err| err.to_string()) - }); + Message::CloseBand => self.band = None, + Message::BandText(value) => { + if let Some(Band::NewBranch(name) | Band::Rename(name)) = &mut self.band { + *name = value; } } - - Message::RenameBufferChanged(value) => { - self.rename_buffer = value; - } - - Message::MergeInto(name) => { - self.pending = Some(Pending::Merge(name)); - } - - Message::RebaseCurrentOnto(name) => { - self.pending = Some(Pending::Rebase(name)); - } - - Message::CancelConfirm => { - self.pending = None; - } - - Message::Confirm => match self.pending.take() { - Some(Pending::Delete(name)) => { - return self.run(move |repo| { - delete_branch(repo, &name) - .map(|()| format!("Branche {name} supprimee")) - .map_err(|err| err.to_string()) - }); - } - Some(Pending::Merge(name)) => { - return self.run_merge(name, MergeStrategy::Merge); - } - Some(Pending::Rebase(name)) => { - return self.run_merge(name, MergeStrategy::Rebase); - } - None => {} - }, - - Message::CompareWithCurrent(name) => { - self.compare_branch = Some(name.clone()); - self.compare_error = None; - self.compare_diff = None; - self.compare_commits.clear(); - if let Some(repo) = self.repo.clone() { - return git_task( - repo, - { - let name = name.clone(); - move |repo| load_comparison(repo, &name) - }, - move |repo, result| Message::CompareLoaded(repo, name.clone(), result), - ); + Message::UpstreamPicked(choice) => { + if let Some(Band::Upstream(picked)) = &mut self.band { + *picked = choice; } } - - Message::OpenInHistory(name) => { - self.open_history_branch = Some(name); - } - - Message::TogglePin(name) => { - self.toggle_pin_by_name(&name); - } - - Message::ToggleStaleOnly => { - self.stale_only = !self.stale_only; - } - - Message::RemotePagePrev => { - self.remote_page = self.remote_page.saturating_sub(1); - } - - Message::RemotePageNext => { - // La borne superieure est verifiee lors du rendu - self.remote_page = self.remote_page.saturating_add(1); + Message::Submit => return (self.submit(), None), + Message::Strategy(index) => { + self.strategy = if index == 0 { + MergeStrategy::Merge + } else { + MergeStrategy::Rebase + }; + self.band = Some(match self.strategy { + MergeStrategy::Merge => Band::Merge, + MergeStrategy::Rebase => Band::Rebase, + }); } - - // -- Resultats des taches de fond -- - Message::Loaded(repo, result) => { - if self.is_current(&repo) { - match result { - Ok(snapshot) => return self.apply_snapshot(snapshot), - Err(err) => self.error = Some(err), + Message::Checkout => return (self.checkout(), None), + Message::TogglePin => { + self.menu = false; + if let Some(name) = self.selected.clone() { + match self.pinned_branches.iter().position(|n| *n == name) { + Some(at) => { + self.pinned_branches.remove(at); + } + None => self.pinned_branches.push(name), } + self.pending_pinned = Some(self.pinned_branches.clone()); } } - - Message::SelectionLoaded(repo, name, result) => { - let selected = self.selected_branch.as_ref().map(|b| b.name.as_str()); - if self.is_current(&repo) && selected == Some(name.as_str()) { - self.selection_loading = false; - match result { - Ok(selection) => self.selection = Some(selection), - Err(err) => { - self.selected_error = - Some(format!("Echec de la comparaison de branche : {err}")); - } - } + Message::CopyName => { + self.menu = false; + if let Some(name) = self.selected.clone() { + return (iced::clipboard::write(name), None); } } - - Message::CompareLoaded(repo, name, result) => { - if self.is_current(&repo) && self.compare_branch.as_deref() == Some(name.as_str()) { - match result { - Ok(comparison) => { - self.compare_diff = comparison.diff; - self.compare_commits = comparison.commits; - } - Err(err) => self.compare_error = Some(err), - } + Message::ViewInHistory => self.open_history_branch = self.selected.clone(), + Message::StartRename => { + let local = self + .selected_branch() + .filter(|branch| branch.kind == BranchKind::Local) + .map(|branch| branch.name.clone()); + if let Some(name) = local { + self.menu = false; + self.band = Some(Band::Rename(name)); } } - - Message::ActionDone(repo, result) => { - if self.is_current(&repo) { - self.busy = false; + Message::Loaded(repo, request, result) => { + if self.is_current(&repo) && request == self.request { + return (self.apply_list(result), None); + } + } + Message::CommitsLoaded(repo, name, result) => { + if self.is_current(&repo) && self.selected.as_ref() == Some(&name) { match result { - Ok(status) => self.status = Some(status), - Err(err) => self.error = Some(err), + Ok(commits) => self.commits = commits, + Err(err) => self.commits_error = Some(err), } - return self.refresh(); } } - - Message::MergeDone(repo, result) => { + Message::ActionDone(repo, failed, result) => { if self.is_current(&repo) { self.busy = false; - match result { - Ok(outcome) => self.handle_merge_outcome(outcome), - Err(err) => self.error = Some(err), - } - return self.refresh(); + let toast = match result { + Ok(Outcome::Done(message)) => Toast::success(message), + Ok(Outcome::Conflicts(files)) => Toast::error( + t("branches_conflicts"), + tf("branches_conflicts_detail", &[("files", &files.join(", "))]), + ), + Err(err) => Toast::error(t(failed), err), + }; + return (self.refresh(), Some(toast)); } } } - - Task::none() + (Task::none(), None) } - // ----------------------------------------------------------------------- - // Vue (rendu) - // ----------------------------------------------------------------------- - - /// Construit l'arbre de widgets Iced pour le panneau de branches. - pub fn view<'a>( - &'a self, - _theme: &'a Theme, - repo: Option<&'a RepoContext>, - ) -> Element<'a, Message> { - let mut main_col = column![].spacing(8).padding(8); - - // Titre et description - main_col = main_col - .push(text("Branch explorer").size(24)) - .push(text("Navigate branches, manage them, and perform git operations.").size(14)); - - // Sans depot ouvert, message d'aide - if repo.is_none() { - main_col = main_col - .push(text("Open a repository to browse and manage its branches.").size(14)); - return main_col.into(); - } - - // Erreur globale, au-dessus des controles ; effacee a la prochaine action - if let Some(error) = &self.error { - main_col = main_col.push(text(error.as_str()).size(14).style(text::danger)); - } - - // Conflits de fusion - if !self.conflict_files.is_empty() { - let msg = format!( - "Conflits de fusion detectes dans : {}", - self.conflict_files.join(", ") - ); - main_col = main_col.push(text(msg).size(14)); - } - - // Message de statut - if self.busy { - main_col = main_col.push(text("Operation en cours...").size(14)); - } else if let Some(status) = &self.status { - main_col = main_col.push(text(status.as_str()).size(14)); - } - - // Barre de creation - main_col = main_col.push(self.view_creation_bar()); - - // Case a cocher "branches obsoletes uniquement" - main_col = main_col.push( - checkbox("Show stale only", self.stale_only).on_toggle(|_| Message::ToggleStaleOnly), - ); - - // Disposition en deux colonnes : locales | distantes - let local_col = self.view_branch_tree(BranchKind::Local, "Local branches"); - let remote_col = self.view_branch_tree(BranchKind::Remote, "Remote branches"); - - let two_columns = row![ - container(local_col).width(Length::FillPortion(1)), - container(remote_col).width(Length::FillPortion(1)), - ] - .spacing(16); - - main_col = main_col.push(two_columns); - - // Panneau de details de la selection (sous la colonne gauche) - main_col = main_col - .push(horizontal_rule(1)) - .push(self.view_selection_panel()); - - // Panneau de comparaison - main_col = main_col - .push(horizontal_rule(1)) - .push(self.view_compare_panel()); - - main_col.into() + fn is_current(&self, repo: &str) -> bool { + self.repo.as_deref() == Some(repo) } - /// Bouton d'action, desactive pendant une action git. - fn action_button<'a>(&self, label: &'a str, message: Message) -> Button<'a, Message> { - button(text(label)).on_press_maybe((!self.busy).then_some(message)) + fn selected_branch(&self) -> Option<&BranchOverview> { + let name = self.selected.as_ref()?; + self.branches.iter().find(|branch| &branch.name == name) } - /// Barre de creation de branche (champ texte + bouton). - fn view_creation_bar(&self) -> Element<'_, Message> { - let input = text_input("feature/my-branch", &self.new_branch) - .on_input(Message::NewBranchChanged) - .on_submit(Message::CreateBranch); - - let create_btn = self.action_button("Create", Message::CreateBranch); - - container(row![text("New branch").size(14), input, create_btn].spacing(8)) - .padding(8) - .into() + /// The checked-out branch, or "HEAD" when none is. + fn current_name(&self) -> &str { + head_name(&self.branches) } - /// Construit la vue d'une colonne de branches (locales ou distantes). - fn view_branch_tree<'a>(&'a self, kind: BranchKind, heading: &'a str) -> Element<'a, Message> { - let mut col = column![].spacing(4); - col = col.push(text(heading).size(20)); - - // Filtrer et partitionner les branches visibles - let visible: Vec<&BranchEntry> = self - .branches - .iter() - .filter(|b| b.kind == kind && self.should_show_branch(b)) - .collect(); - - let (pinned, unpinned): (Vec<_>, Vec<_>) = - visible.into_iter().partition(|b| self.is_branch_pinned(b)); + fn is_pinned(&self, name: &str) -> bool { + self.pinned_branches.iter().any(|pinned| pinned == name) + } - // Pagination pour les branches distantes - let (page_branches, total_pages) = if kind == BranchKind::Remote { - let total = unpinned.len().div_ceil(REMOTE_PAGE_SIZE).max(1); - let page = self.remote_page.min(total.saturating_sub(1)); - let start = page * REMOTE_PAGE_SIZE; - let end = (start + REMOTE_PAGE_SIZE).min(unpinned.len()); - (&unpinned[start..end], total) - } else { - (&unpinned[..], 1usize) + fn refresh(&mut self) -> Task { + let Some(repo) = self.repo.clone() else { + return Task::none(); }; + self.request += 1; + self.loading = true; + let request = self.request; + git_task(repo, read_branches, move |repo, result| { + Message::Loaded(repo, request, result) + }) + } - // Construire l'arbre a partir des branches de la page - let mut root = BranchNode::default(); - for branch in page_branches { - let segments: Vec<&str> = branch.name.split('/').collect(); - root.insert(&segments, (*branch).clone()); - } - - // Branches epinglees - if !pinned.is_empty() { - col = col.push(text("Pinned").size(14)); - for branch in &pinned { - col = col.push(self.view_branch_button(branch)); + /// Takes the new list; when the selected branch is gone, or nothing is selected yet, the + /// selection moves to `initial_selection`. + fn apply_list(&mut self, result: Result) -> Task { + self.loading = false; + match result { + Ok((branches, head)) => { + self.error = None; + self.branches = branches; + self.head = head; + let name = match self.selected_branch() { + Some(branch) => Some(branch.name.clone()), + None => { + self.band = None; + self.menu = false; + initial_selection(&self.branches, &self.pinned_branches).map(str::to_string) + } + }; + self.selected = name; + // The tips may have moved: the own commits are read again. + self.load_commits() } - if !root.children.is_empty() { - col = col.push(horizontal_rule(1)); + Err(err) => { + self.error = Some(err); + Task::none() } } + } - if pinned.is_empty() && root.children.is_empty() { - col = col.push(text("No branches found.").size(14)); - return scrollable(col).into(); + fn select(&mut self, name: String) -> Task { + if self.selected.as_ref() != Some(&name) { + self.menu = false; + // A new branch name typed in the band does not belong to the old selection. + if !matches!(self.band, Some(Band::NewBranch(_))) { + self.band = None; + } } + self.selected = Some(name); + self.load_commits() + } - // Aplatir l'arbre et afficher - let mut flat: Vec = Vec::new(); - for child in root.children.values() { - flatten_node(child, 0, &mut flat); - } + /// Reads the commits listed under the selected branch. + fn load_commits(&mut self) -> Task { + self.commits.clear(); + self.commits_error = None; + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + let Some(branch) = self.selected_branch() else { + return Task::none(); + }; + let (name, is_head) = (branch.name.clone(), branch.is_head); + let job_name = name.clone(); + git_task( + repo, + move |repo| read_commits(repo, &job_name, is_head), + move |repo, result| Message::CommitsLoaded(repo, name.clone(), result), + ) + } - for entry in flat { - let indent = entry.depth as u16 * 16; - if entry.is_folder { - col = col.push( - row![ - Space::with_width(Length::Fixed(indent as f32)), - text(entry.label).size(14), - ] - .spacing(4), - ); - } else if let Some(branch) = &entry.branch { - col = col.push( - row![ - Space::with_width(Length::Fixed(indent as f32)), - self.view_branch_button(branch), - ] - .spacing(4), - ); - } + /// Checks out the selected branch. A remote branch is checked out through its local + /// branch, created to track it when there is none yet. + fn checkout(&mut self) -> Task { + let Some(branch) = self.selected_branch() else { + return Task::none(); + }; + let name = branch.name.clone(); + if branch.kind == BranchKind::Local { + let done = tf("branches_checked_out", &[("name", &name)]); + return self.run("branches_checkout_failed", move |repo| { + checkout_branch(repo, &name) + .map(|()| Outcome::Done(done)) + .map_err(|err| err.to_string()) + }); } - - // Pagination distante - if kind == BranchKind::Remote && total_pages > 1 { - let current_page = self.remote_page.min(total_pages.saturating_sub(1)); - let prev_btn = if current_page > 0 { - button(text("<")).on_press(Message::RemotePagePrev) - } else { - button(text("<")) - }; - let next_btn = if current_page + 1 < total_pages { - button(text(">")).on_press(Message::RemotePageNext) + let local = name.split_once('/').map_or(name.as_str(), |(_, rest)| rest); + let exists = self + .branches + .iter() + .any(|b| b.kind == BranchKind::Local && b.name == local); + let local = local.to_string(); + self.run("branches_checkout_failed", move |repo| { + let local = if exists { + local } else { - button(text(">")) + create_tracking_branch(repo, &name).map_err(|err| err.to_string())? }; - let page_label = text(format!("Page {}/{}", current_page + 1, total_pages)).size(14); - col = col.push(row![prev_btn, page_label, next_btn].spacing(8)); - } - - scrollable(col).into() + checkout_branch(repo, &local) + .map(|()| Outcome::Done(tf("branches_checked_out", &[("name", &local)]))) + .map_err(|err| err.to_string()) + }) } - /// Bouton pour une branche individuelle dans la liste. - fn view_branch_button<'a>(&self, branch: &BranchEntry) -> Element<'a, Message> { - let mut label = branch.name.clone(); - if branch.is_head { - label.push_str(" (HEAD)"); - } - - let is_stale = self.is_branch_stale(branch); - let branch_name = branch.name.clone(); - - let mut entry_row = row![].spacing(4); - entry_row = entry_row.push( - button(text(label).size(14)) - .on_press(Message::SelectBranch(branch_name)) - .padding(4), - ); - - if is_stale { - entry_row = entry_row.push(container(text("stale").size(11)).padding([2, 6])); + /// Runs the action of the open band. + fn submit(&mut self) -> Task { + if self.busy { + return Task::none(); } - - entry_row.into() - } - - /// Panneau affichant les details de la branche selectionnee. - fn view_selection_panel(&self) -> Element<'_, Message> { - let mut col = column![].spacing(6); - col = col.push(text("Selection details").size(20)); - - let Some(branch) = &self.selected_branch else { - col = col - .push(text("Select a branch to see its details and available actions.").size(14)); - return col.into(); + let Some(band) = self.band.take() else { + return Task::none(); }; - - // Erreur de selection - if let Some(error) = &self.selected_error { - col = col.push(text(error.as_str()).size(14)); + if let Band::NewBranch(name) = band { + let name = name.trim().to_string(); + if name.is_empty() { + self.band = Some(Band::NewBranch(name)); + return Task::none(); + } + let done = tf("branches_created", &[("name", &name)]); + self.selected = Some(name.clone()); + return self.run("branches_create_failed", move |repo| { + create_branch(repo, &name, None) + .map(|()| Outcome::Done(done)) + .map_err(|err| err.to_string()) + }); } - - // Nom et type de branche - col = col.push(text(&branch.name).size(16)); - let kind_label = match branch.kind { - BranchKind::Local => "Local branch", - BranchKind::Remote => "Remote branch", + let Some(name) = self.selected.clone() else { + return Task::none(); }; - col = col.push(text(kind_label).size(12)); - - // Informations de comparaison - if self.selection_loading { - col = col.push(text("Chargement...").size(12)); - } - if let Some(comparison) = self.selection.as_ref().map(|s| &s.comparison) { - if let Some(commit) = &comparison.commit { - col = col - .push(text(&commit.summary).size(14)) - .push(text(format!("by {}", commit.author)).size(12)); + let current = self.current_name().to_string(); + let head = self.head; + match band { + Band::NewBranch(_) => Task::none(), + Band::Rename(new) => { + let new = new.trim().to_string(); + if new.is_empty() || new == name { + return Task::none(); + } + let done = tf("branches_renamed", &[("old", &name), ("new", &new)]); + self.selected = Some(new.clone()); + self.run("branches_rename_failed", move |repo| { + rename_branch(repo, &name, &new) + .map(|()| Outcome::Done(done)) + .map_err(|err| err.to_string()) + }) } - if let Some(diff) = &comparison.diff { - col = col.push( - text(format!( - "{} files +{} / -{}", - diff.files_changed, diff.additions, diff.deletions - )) - .size(12), - ); + Band::Upstream(choice) => { + let upstream = match choice { + UpstreamChoice::None => None, + UpstreamChoice::Branch(upstream) => Some(upstream), + }; + let done = match &upstream { + Some(upstream) => tf( + "branches_upstream_set", + &[("branch", &name), ("upstream", upstream)], + ), + None => tf("branches_upstream_removed", &[("branch", &name)]), + }; + self.run("branches_upstream_failed", move |repo| { + set_upstream(repo, &name, upstream.as_deref()) + .map(|()| Outcome::Done(done)) + .map_err(|err| err.to_string()) + }) + } + Band::Archive => self.run("branches_archive_failed", move |repo| { + archive_branch(repo, &name) + .map(|tag| { + Outcome::Done(tf("branches_archived", &[("branch", &name), ("tag", &tag)])) + }) + .map_err(|err| err.to_string()) + }), + Band::Delete => { + let done = tf("branches_deleted", &[("name", &name)]); + let merged = self + .selected_branch() + .is_some_and(|branch| branch.merged_into_head); + self.run("branches_delete_failed", move |repo| { + ensure_unchanged(repo, ¤t, head, &name, merged)?; + delete_branch(repo, &name) + .map(|()| Outcome::Done(done)) + .map_err(|err| err.to_string()) + }) + } + Band::Merge | Band::Rebase => { + let (strategy, done, failed) = if band == Band::Merge { + ( + MergeStrategy::Merge, + "branches_merged_into", + "branches_merge_failed", + ) + } else { + ( + MergeStrategy::Rebase, + "branches_rebased", + "branches_rebase_failed", + ) + }; + let done = tf(done, &[("branch", &name), ("current", ¤t)]); + self.run(failed, move |repo| { + ensure_unchanged(repo, ¤t, head, &name, false)?; + let outcome = merge_branch(repo, &name, strategy)?; + Ok(if outcome.had_conflicts { + Outcome::Conflicts(outcome.conflicts) + } else { + Outcome::Done(done) + }) + }) } } + } - // Action en attente de confirmation - if let Some(pending) = &self.pending { - col = col.push(self.view_confirmation(pending)); + /// Runs a git action unless one is running; the list is read again when it ends. + fn run( + &mut self, + failed: &'static str, + job: impl FnOnce(&str) -> Result + Send + 'static, + ) -> Task { + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + if self.busy { + return Task::none(); } + self.busy = true; + git_task(repo, job, move |repo, result| { + Message::ActionDone(repo, failed, result) + }) + } - // Actions - col = col.push(text("Actions").size(14)); - - let branch_name = branch.name.clone(); - let is_pinned = self.is_branch_pinned(branch); - let pin_label = if is_pinned { "Unpin" } else { "Pin" }; - - col = col.push(button(text(pin_label)).on_press(Message::TogglePin(branch_name.clone()))); - - // Checkout - let mut checkout_row = row![].spacing(8); - checkout_row = checkout_row - .push(self.action_button("Checkout", Message::Checkout(branch_name.clone()))); - if branch.kind == BranchKind::Remote { - checkout_row = checkout_row.push(self.action_button( - "Checkout & Track", - Message::CheckoutAndTrack(branch_name.clone()), - )); - } - col = col.push(checkout_row); + pub fn view(&self) -> Element<'_, Message> { + let list = column![self.toolbar(), self.branch_list()] + .width(Length::Fixed(LIST_WIDTH)) + .height(Length::Fill); + row![list, vertical_divider(), self.detail_pane()] + .height(Length::Fill) + .into() + } - // Merge et Rebase - col = col.push( - row![ - self.action_button( - "Merge into current", - Message::MergeInto(branch_name.clone()) - ), - self.action_button( - "Rebaser la branche courante sur celle-ci", - Message::RebaseCurrentOnto(branch_name.clone()) - ), - ] - .spacing(8), + /// The filter field with its "⋯" (stale only), and "+ New". + fn toolbar(&self) -> Element<'_, Message> { + let stale = if self.stale_only { + t("branches_show_all") + } else { + t("branches_stale_only") + }; + let options = menu::popup( + gs_button::icon( + MORE_GLYPH, + Some(Message::FilterMenu(!self.filter_menu)), + t("branches_filter_options"), + ), + self.filter_menu, + vec![item(stale, Message::ToggleStaleOnly, false)], + Message::FilterMenu(false), ); - - // Comparer et Historique - col = col.push( - row![ - button(text("Compare with current")) - .on_press(Message::CompareWithCurrent(branch_name.clone())), - button(text("Open in History")) - .on_press(Message::OpenInHistory(branch_name.clone())), - ] - .spacing(8), + let filter = field( + text_input(t("branches_filter_placeholder"), &self.filter).on_input(Message::Filter), + Some(options), ); + let new = gs_button::secondary( + t("branches_new"), + Some(Message::Open(Band::NewBranch(String::new()))), + ); + container(row![filter, new].spacing(6).align_y(Alignment::Center)) + .padding([10, 10]) + .into() + } - // Actions specifiques aux branches locales - if branch.kind == BranchKind::Local { - let mut local_row = row![].spacing(8); - - if !branch.is_head { - // Attendre la verification de fusion avant de proposer la suppression - let mut delete_btn = - self.action_button("Delete", Message::DeleteBranch(branch_name.clone())); - if self.selection_loading { - delete_btn = delete_btn.on_press_maybe(None); - } - local_row = local_row.push(delete_btn); - } - - local_row = local_row - .push(self.action_button("Archive", Message::ArchiveBranch(branch_name.clone()))); - - col = col.push(local_row); - - // Renommage - let old_name = branch_name.clone(); - let new_name = self.rename_buffer.trim().to_string(); - let rename_btn = if !new_name.is_empty() && new_name != old_name { - self.action_button("Apply", Message::RenameBranch(old_name, new_name)) - } else { - button(text("Apply")) + fn branch_list(&self) -> Element<'_, Message> { + let now = chrono::Utc::now().timestamp(); + let query = self.filter.trim().to_lowercase(); + let visible: Vec<&BranchOverview> = self + .branches + .iter() + .filter(|branch| query.is_empty() || branch.name.to_lowercase().contains(&query)) + .filter(|branch| !self.stale_only || is_stale(branch, now)) + .collect(); + if visible.is_empty() { + let label = match &self.error { + Some(err) => tf("branches_load_failed", &[("error", err)]), + None if self.loading => t("changes_loading").to_string(), + None if !self.branches.is_empty() => t("branches_no_match").to_string(), + None => t("branches_empty").to_string(), }; - - col = col.push( - row![ - text("Rename:").size(14), - text_input("new name", &self.rename_buffer) - .on_input(Message::RenameBufferChanged), - rename_btn, - ] - .spacing(8), - ); + return note(label); } - col.into() - } - - /// Demande de confirmation d'une action destructive. - fn view_confirmation(&self, pending: &Pending) -> Element<'_, Message> { - let current = self.current_branch().unwrap_or("HEAD"); - let mut lines = column![].spacing(4); - match pending { - Pending::Delete(name) => { - lines = lines.push(text(format!("Supprimer la branche {name} ?")).size(14)); - if self.selection.as_ref().and_then(|s| s.merged) == Some(false) { - lines = lines.push( - text(format!( - "{name} n'est pas fusionnee dans {current} : ses commits \ - propres ne seront plus accessibles par une branche." - )) - .size(14) - .style(text::danger), - ); - } + let mut local: Vec<&BranchOverview> = visible + .iter() + .copied() + .filter(|branch| branch.kind == BranchKind::Local) + .collect(); + // Pinned branches first; the sort is stable, so names stay in order. + local.sort_by_key(|branch| !self.is_pinned(&branch.name)); + let mut rows = Column::new().padding([0, 6]).spacing(1); + if !local.is_empty() { + rows = rows.push(group_header( + tf( + "branches_local_group", + &[("count", &local.len().to_string())], + ), + None, + )); + for branch in local { + rows = rows.push(self.branch_row(branch)); } - Pending::Merge(name) => { - lines = lines.push(text(format!("Fusionner {name} dans {current} ?")).size(14)); + } + for group in remote_groups(&visible) { + let collapsed = self.collapsed.contains(group.remote); + let label = format!("{} · {}", group.remote.to_uppercase(), group.branches.len()); + rows = rows.push(group_header( + label, + Some((collapsed, Message::ToggleRemote(group.remote.to_string()))), + )); + if collapsed { + continue; } - Pending::Rebase(name) => { - lines = lines.push( - text(format!( - "Rebaser {current} sur {name} ? Les commits de {current} seront reecrits." - )) - .size(14), - ); + let pages = group.branches.len().div_ceil(REMOTE_PAGE_SIZE); + let page = self + .remote_pages + .get(group.remote) + .copied() + .unwrap_or(0) + .min(pages - 1); + for branch in group + .branches + .iter() + .skip(page * REMOTE_PAGE_SIZE) + .take(REMOTE_PAGE_SIZE) + { + rows = rows.push(self.branch_row(branch)); + } + if pages > 1 { + rows = rows.push(pager(group.remote, page, pages)); } } - lines = lines.push( - row![ - self.action_button("Confirmer", Message::Confirm), - button(text("Annuler")).on_press(Message::CancelConfirm), - ] - .spacing(8), - ); - container(lines).padding(8).into() + scrollable(rows.padding([0, 6])).height(Length::Fill).into() } - /// Panneau de comparaison avec la branche courante. - fn view_compare_panel(&self) -> Element<'_, Message> { - let mut col = column![].spacing(6); - col = col.push(text("Compare with current").size(20)); - - let Some(branch_name) = &self.compare_branch else { - col = col.push( - text("Select 'Compare with current' on a branch to see differences.").size(14), - ); - return col.into(); + /// The icon, the name, and on the right: "current", "✓ merged" or ↑↓ against the + /// current branch. + fn branch_row<'a>(&'a self, branch: &'a BranchOverview) -> Element<'a, Message> { + let typo = Typography::current(); + let (glyph, color) = if branch.is_head { + (CURRENT_GLYPH, Palette::SUCCESS()) + } else if self.is_pinned(&branch.name) { + (STAR_GLYPH, Palette::WARNING()) + } else if branch.kind == BranchKind::Remote { + (CLOUD_GLYPH, Palette::TEXT_DIMMER()) + } else { + (BRANCH_GLYPH, Palette::TEXT_DIMMER()) }; - - if let Some(error) = &self.compare_error { - col = col.push(text(error.as_str()).size(14)); - return col.into(); - } - - col = col.push(text(branch_name.as_str()).size(16)); - - if let Some(diff) = &self.compare_diff { - col = col.push( - text(format!( - "{} files changed +{} / -{}", - diff.files_changed, diff.additions, diff.deletions - )) - .size(14), + let small = |label: String, color| { + text(label) + .size(typo.sz(10)) + .font(typo.regular) + .color(color) + }; + let mut content = row![ + container( + text(glyph) + .size(typo.sz(10)) + .font(fonts::glyph_font()) + .color(color) + ) + .center_x(Length::Fixed(14.0)), + // The container keeps the badges at the right end of the row. + container(ellipsis( + branch.name.as_str(), + typo.sz(12), + typo.regular, + Palette::TEXT_PRIMARY(), + )) + .width(Length::Fill), + ] + .spacing(8) + .align_y(Alignment::Center); + if branch.is_head { + content = content.push(small( + t("branches_current").to_string(), + Palette::TEXT_DIMMER(), + )); + } else if branch.kind == BranchKind::Local && branch.merged_into_head { + content = content.push( + row![ + text(icons::CHECK) + .size(typo.sz(9)) + .font(fonts::glyph_font()) + .color(Palette::SUCCESS()), + small(t("branches_merged").to_string(), Palette::SUCCESS()), + ] + .spacing(4) + .align_y(Alignment::Center), ); + } else if branch.kind == BranchKind::Local { + if branch.ahead_of_head > 0 { + content = content.push(small( + format!("↑{}", branch.ahead_of_head), + Palette::SUCCESS(), + )); + } + if branch.behind_head > 0 { + content = content.push(small( + format!("↓{}", branch.behind_head), + Palette::WARNING(), + )); + } } + let selected = self.selected.as_ref() == Some(&branch.name); + button(content) + .on_press(Message::Select(branch.name.clone())) + .padding([6, 8]) + .width(Length::Fill) + .style(move |_, status| button::Style { + background: (selected + || matches!(status, button::Status::Hovered | button::Status::Pressed)) + .then(|| Palette::BG_CARD_HOVER().into()), + border: Border::default().rounded(6), + ..Default::default() + }) + .into() + } - col = col.push(text("Commits between current HEAD and branch").size(16)); - - if self.compare_commits.is_empty() { - col = col.push(text("No commits found in the selected range.").size(14)); - return col.into(); + fn detail_pane(&self) -> Element<'_, Message> { + let Some(branch) = self.selected_branch() else { + return column![self.bands(None), note(t("branches_select").to_string())].into(); + }; + let actions = available_actions(branch); + let current = self.current_name(); + let mut body = Column::new().spacing(14).padding([16, 18]); + if let Some(card) = RelationCard::new(branch, current) { + body = body.push(relation_card(&card)); } - - let mut commits_col = column![].spacing(4); - for commit in &self.compare_commits { - let short_id = short_id(&commit.id); - commits_col = commits_col.push( - column![ - text(&commit.summary).size(14), - text(format!("{} {}", short_id, commit.author)).size(12), - ] - .spacing(2), - ); + if actions.contains(&BranchAction::Checkout) { + let mut buttons = row![gs_button::primary( + t("branches_checkout"), + (!self.busy).then_some(Message::Checkout), + )] + .spacing(10) + .align_y(Alignment::Center); + if actions.contains(&BranchAction::Merge) { + let segments = [ + tf("branches_merge_into", &[("current", current)]), + tf("branches_rebase_onto", &[("current", current)]), + ]; + let chosen = usize::from(self.strategy == MergeStrategy::Rebase); + buttons = buttons.push(segmented(&segments, chosen, Message::Strategy)); + } + body = body.push(column![buttons, self.note_line(branch, current)].spacing(8)); } - - col = col.push(scrollable(commits_col).height(Length::Fixed(220.0))); - - col.into() + body = body.push(self.own_commits(branch, current)); + column![ + self.header(branch, &actions), + self.bands(Some(branch)), + horizontal_divider(), + scrollable(body).height(Length::Fill), + ] + .width(Length::Fill) + .height(Length::Fill) + .into() } - // ----------------------------------------------------------------------- - // Logique interne - // ----------------------------------------------------------------------- + fn note_line<'a>(&self, branch: &BranchOverview, current: &str) -> Element<'a, Message> { + let typo = Typography::current(); + let note = action_note( + Some(self.strategy), + &branch.name, + current, + branch.ahead_of_head, + ); + text(note) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIM()) + .into() + } - fn is_current(&self, repo: &str) -> bool { - self.repo.as_deref() == Some(repo) + /// The name, "tracks … · in sync · last commit …", and the "⋯" menu. + fn header<'a>( + &'a self, + branch: &'a BranchOverview, + actions: &[BranchAction], + ) -> Element<'a, Message> { + let typo = Typography::current(); + let more = menu::popup( + gs_button::icon( + MORE_GLYPH, + Some(Message::Menu(!self.menu)), + t("branches_actions"), + ), + self.menu, + self.menu_entries(branch, actions), + Message::Menu(false), + ); + column![ + row![ + text(branch.name.as_str()) + .size(typo.sz(15)) + .font(typo.bold) + .color(Palette::TEXT_PRIMARY()) + .width(Length::Fill), + more, + ] + .spacing(10) + .align_y(Alignment::Center), + text(subtitle(branch, chrono::Utc::now().timestamp())) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIM()), + ] + .spacing(6) + .padding([16, 18]) + .into() } - /// Relit les branches, leur dernier commit et les conflits en tache de fond. - fn refresh(&self) -> Task { - match self.repo.clone() { - Some(repo) => git_task(repo, read_snapshot, Message::Loaded), - None => Task::none(), + /// Rename (F2), Pin to top, Copy name, Change upstream…, then Archive as tag… and Delete…. + fn menu_entries( + &self, + branch: &BranchOverview, + actions: &[BranchAction], + ) -> Vec> { + let mut entries = Vec::new(); + for action in actions { + let entry = match action { + BranchAction::Checkout | BranchAction::Merge | BranchAction::Rebase => continue, + BranchAction::Rename => Entry::Item(MenuItem { + label: t("branches_rename").to_string(), + shortcut: Some("F2".to_string()), + on_select: Message::Open(Band::Rename(branch.name.clone())), + danger: false, + }), + BranchAction::Pin => { + let label = if self.is_pinned(&branch.name) { + t("branches_unpin") + } else { + t("branches_pin") + }; + item(label, Message::TogglePin, false) + } + BranchAction::CopyName => item(t("branches_copy_name"), Message::CopyName, false), + BranchAction::ChangeUpstream => { + let choice = branch + .upstream + .clone() + .map_or(UpstreamChoice::None, UpstreamChoice::Branch); + item( + t("branches_change_upstream"), + Message::Open(Band::Upstream(choice)), + false, + ) + } + BranchAction::Archive => { + entries.push(Entry::Separator); + item(t("branches_archive"), Message::Open(Band::Archive), false) + } + BranchAction::Delete => { + if !actions.contains(&BranchAction::Archive) { + entries.push(Entry::Separator); + } + item(t("branches_delete"), Message::Open(Band::Delete), true) + } + }; + entries.push(entry); } + entries } - /// Remplace la liste ; la selection est rechargee si la branche existe encore. - fn apply_snapshot(&mut self, snapshot: BranchSnapshot) -> Task { - self.branches = snapshot.branches; - self.branch_commits = snapshot.commits; - self.conflict_files = snapshot.conflicts; - - let still_listed = self.selected_branch.as_ref().and_then(|selected| { - self.branches - .iter() - .find(|b| b.name == selected.name && b.kind == selected.kind) - .cloned() - }); - match still_listed { - Some(branch) => { - self.selected_branch = Some(branch); - self.load_selection() + /// The open band: a name field, the upstream picker or a confirmation. + fn bands<'a>(&'a self, branch: Option<&'a BranchOverview>) -> Element<'a, Message> { + let typo = Typography::current(); + let Some(band) = &self.band else { + return Space::new().into(); + }; + let prompt = |label: String| -> Element<'a, Message> { + text(label) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY()) + .into() + }; + let current = self.current_name(); + let submit = (!self.busy).then_some(Message::Submit); + let name_field = |value: &'a String| -> Element<'a, Message> { + container(field( + text_input(t("branches_name_placeholder"), value) + .on_input(Message::BandText) + .on_submit_maybe( + (!self.busy && !value.trim().is_empty()).then_some(Message::Submit), + ), + None, + )) + .width(Length::Fixed(220.0)) + .into() + }; + let (lines, action) = match (band, branch) { + (Band::NewBranch(name), _) => ( + vec![ + prompt(tf("branches_new_prompt", &[("current", current)])), + name_field(name), + ], + gs_button::primary( + t("branches_create"), + submit.filter(|_| !name.trim().is_empty()), + ), + ), + (_, None) => return Space::new().into(), + (Band::Rename(name), Some(branch)) => ( + vec![ + prompt(tf("branches_rename_prompt", &[("branch", &branch.name)])), + name_field(name), + ], + gs_button::primary( + t("branches_rename_button"), + submit.filter(|_| !name.trim().is_empty() && name.trim() != branch.name), + ), + ), + (Band::Upstream(choice), Some(branch)) => { + let choices: Vec = std::iter::once(UpstreamChoice::None) + .chain( + self.branches + .iter() + .filter(|b| b.kind == BranchKind::Remote) + .map(|b| UpstreamChoice::Branch(b.name.clone())), + ) + .collect(); + ( + vec![ + prompt(tf("branches_upstream_prompt", &[("branch", &branch.name)])), + pick_list(choices, Some(choice.clone()), Message::UpstreamPicked) + .text_size(typo.sz(12)) + .font(typo.regular) + .into(), + ], + gs_button::primary(t("branches_apply"), submit), + ) } - None => { - self.selected_branch = None; - self.selection = None; - self.pending = None; - Task::none() + (Band::Archive, Some(branch)) => ( + vec![prompt(tf( + "branches_archive_confirm", + &[("branch", &branch.name)], + ))], + gs_button::primary(t("branches_archive_button"), submit), + ), + (Band::Delete, Some(branch)) => { + let key = if branch.merged_into_head { + "branches_delete_merged" + } else { + "branches_delete_unmerged" + }; + ( + vec![prompt(tf( + key, + &[("branch", &branch.name), ("current", current)], + ))], + gs_button::danger(t("branches_delete_button"), submit), + ) } - } - } - - /// Charge la comparaison de la branche selectionnee avec HEAD. - fn load_selection(&mut self) -> Task { - let (Some(repo), Some(branch)) = (self.repo.clone(), self.selected_branch.clone()) else { - return Task::none(); + (Band::Merge, Some(branch)) => ( + vec![prompt(tf( + "branches_merge_confirm", + &[("branch", &branch.name), ("current", current)], + ))], + gs_button::primary(t("branches_merge_button"), submit), + ), + (Band::Rebase, Some(branch)) => ( + vec![prompt(tf( + "branches_rebase_confirm", + &[("branch", &branch.name), ("current", current)], + ))], + gs_button::primary(t("branches_rebase_button"), submit), + ), }; - self.selection = None; - self.selected_error = None; - self.selection_loading = true; - let name = branch.name.clone(); - git_task( - repo, - move |repo| { - let comparison = - compare_branch_with_head(repo, &branch.name).map_err(|e| e.to_string())?; - let merged = (branch.kind == BranchKind::Local) - .then(|| merged_into_head(repo, &branch.name).ok()) - .flatten(); - Ok(Selection { comparison, merged }) - }, - move |repo, result| Message::SelectionLoaded(repo, name.clone(), result), - ) + question(lines, action, Message::CloseBand) } - /// Lance une action git si aucune n'est en cours, apres avoir efface l'erreur et le - /// statut precedents ; la liste est relue a la fin. - fn run( - &mut self, - job: impl FnOnce(&str) -> Result + Send + 'static, - ) -> Task { - match self.start() { - Some(repo) => git_task(repo, job, Message::ActionDone), - None => Task::none(), + /// "Commits only on ", or "Latest commits on " for the current branch, + /// with "View in History →", then the commits. + fn own_commits<'a>( + &'a self, + branch: &'a BranchOverview, + current: &str, + ) -> Element<'a, Message> { + let typo = Typography::current(); + let link = button( + text(t("branches_view_in_history")) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::ACCENT()), + ) + .padding(0) + .style(|_, _| button::Style::default()) + .on_press(Message::ViewInHistory); + let heading = if branch.is_head { + "branches_latest_commits" + } else { + "branches_commits_only_on" + }; + let heading = row![ + text(tf(heading, &[("branch", &branch.name)])) + .size(typo.sz(12)) + .font(typo.bold) + .color(Palette::TEXT_SECONDARY()) + .width(Length::Fill), + link, + ] + .align_y(Alignment::Center); + let mut list = Column::new().spacing(1); + if let Some(err) = &self.commits_error { + list = list.push(note_line(tf("branches_commits_failed", &[("error", err)]))); + } else if self.commits.is_empty() && !branch.is_head && branch.ahead_of_head == 0 { + list = list.push(note_line(tf( + "branches_no_own_commits", + &[("branch", &branch.name), ("current", current)], + ))); + } + let now = chrono::Utc::now().timestamp(); + for commit in &self.commits { + list = list.push( + row![ + text(commit.short_id.as_str()) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::ACCENT()), + container(ellipsis( + commit.summary.as_str(), + typo.sz(12), + typo.regular, + Palette::TEXT_PRIMARY(), + )) + .width(Length::Fill), + text(relative_time(commit.time.seconds(), now)) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()), + ] + .spacing(10) + .padding([5, 8]) + .align_y(Alignment::Center), + ); } + column![heading, list].spacing(8).into() } +} - /// Lance une fusion ou un rebase de la branche courante avec `branch`. - fn run_merge(&mut self, branch: String, strategy: MergeStrategy) -> Task { - match self.start() { - Some(repo) => git_task( - repo, - move |repo| merge_branch(repo, &branch, strategy), - Message::MergeDone, +/// "tracks origin/x · in sync with its upstream · last commit 1 h ago". +fn subtitle(branch: &BranchOverview, now: i64) -> String { + let mut parts = Vec::new(); + if branch.kind == BranchKind::Remote { + parts.push(t("branches_remote_branch").to_string()); + } else if let Some(upstream) = &branch.upstream { + parts.push(tf("branches_tracks", &[("upstream", upstream)])); + let (ahead, behind) = (branch.upstream_ahead, branch.upstream_behind); + parts.push(match (ahead, behind) { + (0, 0) => t("branches_in_sync").to_string(), + (ahead, 0) => tf("branches_upstream_ahead", &[("count", &ahead.to_string())]), + (0, behind) => tf( + "branches_upstream_behind", + &[("count", &behind.to_string())], ), - None => Task::none(), - } + (ahead, behind) => tf( + "branches_upstream_diverged", + &[ + ("ahead", &ahead.to_string()), + ("behind", &behind.to_string()), + ], + ), + }); + } else { + parts.push(t("branches_no_upstream").to_string()); } - - /// Marque le debut d'une action ; `None` si une action tourne deja ou sans depot. - fn start(&mut self) -> Option> { - if self.busy { - return None; - } - let repo = self.repo.clone()?; - self.busy = true; - self.status = None; - self.error = None; - Some(repo) + if let Some(time) = branch.last_commit_time { + parts.push(tf( + "branches_last_commit", + &[("when", &relative_time(time, now))], + )); } + parts.join(" · ") +} - /// Gere le resultat d'une operation de fusion. - fn handle_merge_outcome(&mut self, outcome: MergeOutcome) { - if outcome.had_conflicts { - self.conflict_files = outcome.conflicts; - self.status = Some( - "Conflits detectes. Resolvez-les dans votre repertoire de travail.".to_string(), - ); - } else { - self.conflict_files.clear(); - self.status = Some(outcome.message); - } - } +/// No commit for `STALE_DAYS`, or no commit at all. +fn is_stale(branch: &BranchOverview, now: i64) -> bool { + branch + .last_commit_time + .is_none_or(|time| now.saturating_sub(time) > STALE_DAYS * 24 * 60 * 60) +} - /// Nom de la branche locale courante. - fn current_branch(&self) -> Option<&str> { - self.branches - .iter() - .find(|b| b.is_head && b.kind == BranchKind::Local) - .map(|b| b.name.as_str()) +/// Big "N commits ahead" on the left, "N behind " on the right, a proportional +/// bar between. +fn relation_card<'a>(card: &RelationCard) -> Element<'a, Message> { + let typo = Typography::current(); + let side = |count: usize, label: String, color, align| { + column![ + text(count.to_string()) + .size(typo.sz(22)) + .font(typo.bold) + .color(color), + text(label) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIM()), + ] + .spacing(2) + .align_x(align) + }; + let ahead_label = if card.ahead == 1 { + t("branches_commit_ahead").to_string() + } else { + t("branches_commits_ahead").to_string() + }; + let segment = |portion: usize, color: iced::Color| -> Element<'a, Message> { + let portion = u16::try_from(portion).unwrap_or(u16::MAX); + container(Space::new().width(Length::Fill).height(6)) + .width(Length::FillPortion(portion)) + .style(move |_| container::Style { + background: Some(color.into()), + border: Border::default().rounded(3), + ..Default::default() + }) + .into() + }; + let mut bar = row![].spacing(2).width(Length::Fill); + if card.ahead == 0 && card.behind == 0 { + bar = bar.push(segment(1, Palette::BG_SELECTED())); } - - /// Epingle ou desepingle une branche par nom. - fn toggle_pin_by_name(&mut self, name: &str) { - if let Some(pos) = self.pinned_branches.iter().position(|n| n == name) { - self.pinned_branches.remove(pos); - } else { - self.pinned_branches.push(name.to_string()); - } - self.pending_pinned = Some(self.pinned_branches.clone()); + if card.ahead > 0 { + bar = bar.push(segment(card.ahead, Palette::SUCCESS())); } - - /// Verifie si une branche est consideree obsolete (pas de commit recent). - fn is_branch_stale(&self, branch: &BranchEntry) -> bool { - let Some(commit) = self.branch_commits.get(&branch_key(branch)) else { - return true; - }; - let age_seconds = Utc::now().timestamp().saturating_sub(commit.time.seconds()); - age_seconds > STALE_DAYS * 24 * 60 * 60 + if card.behind > 0 { + bar = bar.push(segment(card.behind, Palette::WARNING())); } + container( + row![ + side( + card.ahead, + ahead_label, + Palette::SUCCESS(), + Alignment::Start + ), + container(bar).width(Length::Fill).padding([0, 16]), + side( + card.behind, + tf("branches_behind", &[("branch", &card.against)]), + Palette::WARNING(), + Alignment::End, + ), + ] + .align_y(Alignment::Center), + ) + .padding([14, 16]) + .width(Length::Fill) + .style(|_| container::Style { + background: Some(Palette::BG_CARD().into()), + border: Border::default().rounded(8), + ..Default::default() + }) + .into() +} - /// Determine si une branche doit etre affichee selon les filtres actifs. - fn should_show_branch(&self, branch: &BranchEntry) -> bool { - !self.stale_only || self.is_branch_stale(branch) - } +/// "LOCAL · 3", or a remote's "ORIGIN · 4" with its collapse chevron. +fn group_header<'a>(label: String, toggle: Option<(bool, Message)>) -> Element<'a, Message> { + let typo = Typography::current(); + let mut content = row![text(label) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .width(Length::Fill)] + .align_y(Alignment::Center); + let Some((collapsed, on_press)) = toggle else { + return container(content).padding([10, 8]).into(); + }; + content = content.push( + text(if collapsed { + icons::CHEVRON_RIGHT + } else { + icons::CHEVRON_DOWN + }) + .size(typo.sz(9)) + .font(fonts::glyph_font()) + .color(Palette::TEXT_DIMMEST()), + ); + button(content) + .on_press(on_press) + .padding([10, 8]) + .width(Length::Fill) + .style(|_, _| button::Style::default()) + .into() +} - /// Verifie si une branche est epinglee. - fn is_branch_pinned(&self, branch: &BranchEntry) -> bool { - self.pinned_branches.iter().any(|name| name == &branch.name) - } +/// "‹ 2/3 ›" under a remote group longer than a page. +fn pager<'a>(remote: &str, page: usize, pages: usize) -> Element<'a, Message> { + let typo = Typography::current(); + let go = |to: usize| Message::RemotePage(remote.to_string(), to); + container( + row![ + gs_button::icon( + PREVIOUS_GLYPH, + (page > 0).then(|| go(page - 1)), + t("branches_previous_page"), + ), + text(format!("{}/{}", page + 1, pages)) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + gs_button::icon( + icons::CHEVRON_RIGHT, + (page + 1 < pages).then(|| go(page + 1)), + t("branches_next_page"), + ), + ] + .spacing(6) + .align_y(Alignment::Center), + ) + .center_x(Length::Fill) + .padding([4, 0]) + .into() } -// --------------------------------------------------------------------------- -// Lectures git (tache de fond) -// --------------------------------------------------------------------------- +/// The latest commits of the current branch, or the commits of another branch that the +/// current one lacks. +fn read_commits(repo: &str, branch: &str, is_head: bool) -> Result, String> { + let commits = if is_head { + let filter = CommitFilter { + branch: Some(branch.to_string()), + ..CommitFilter::default() + }; + read_commit_log(repo, &filter, LATEST_COMMITS, false) + } else { + commits_between_refs(repo, "HEAD", branch, OWN_COMMITS) + }; + commits.map_err(|err| err.to_string()) +} -/// Cle unique pour indexer les commits par branche. -fn branch_key(branch: &BranchEntry) -> String { - match branch.kind { - BranchKind::Local => format!("local:{}", branch.name), - BranchKind::Remote => format!("remote:{}", branch.name), - } +/// The checked-out branch, or "HEAD" when none is. +fn head_name(branches: &[BranchOverview]) -> &str { + branches + .iter() + .find(|branch| branch.is_head && branch.kind == BranchKind::Local) + .map_or("HEAD", |branch| branch.name.as_str()) } -/// Lit les branches, le dernier commit de chacune et les conflits en cours. -fn read_snapshot(repo: &str) -> Result { - let branches = - list_branches(repo).map_err(|err| format!("Echec de lecture des branches : {err}"))?; - let mut commits = BTreeMap::new(); - for branch in &branches { - let commit = latest_commit_for_branch(repo, &branch.name) - .map_err(|err| format!("Echec de lecture de l'historique de branche : {err}"))?; - if let Some(commit) = commit { - commits.insert(branch_key(branch), commit); - } - } - let conflicts = - detect_conflicts(repo).map_err(|err| format!("Echec de detection des conflits : {err}"))?; - Ok(BranchSnapshot { - branches, - commits, - conflicts, - }) +/// The branches and the commit HEAD points at, read in a background task. +fn read_branches(repo: &str) -> Result { + let branches = list_branch_overview(repo).map_err(|err| err.to_string())?; + let head = head_commit(repo).map_err(|err| err.to_string())?; + Ok((branches, head)) } -/// Charge l'ecart et les commits entre HEAD et `branch`. -fn load_comparison(repo: &str, branch: &str) -> Result { - let diff = compare_branch_with_head(repo, branch) - .map_err(|err| format!("Echec de la comparaison de branche : {err}"))? - .diff; - let commits = commits_between_refs(repo, "HEAD", branch, 50) - .map_err(|err| format!("Echec du chargement des commits de comparaison : {err}"))?; - Ok(Comparison { diff, commits }) +/// Fails when HEAD is no longer `current` at commit `head`, or when `branch` was shown as +/// merged into it and no longer is: the confirmation the user answered then describes another +/// state. The commit matters for a detached HEAD, whose name is always "HEAD". +fn ensure_unchanged( + repo: &str, + current: &str, + head: Option, + branch: &str, + merged: bool, +) -> Result<(), String> { + let (branches, now) = read_branches(repo)?; + let still_merged = branches.iter().any(|overview| { + overview.kind == BranchKind::Local && overview.name == branch && overview.merged_into_head + }); + if head_name(&branches) != current || now != head || (merged && !still_merged) { + return Err(t("branches_changed_outside").to_string()); + } + Ok(()) } -/// Vrai si chaque commit de la branche locale `name` est accessible depuis HEAD. -fn merged_into_head(repo_path: &str, name: &str) -> Result { - with_cached_repo(repo_path, |repo| { - let tip = repo - .find_branch(name, BranchType::Local)? - .get() - .peel_to_commit()? - .id(); - let head = repo.head()?.peel_to_commit()?.id(); - Ok(tip == head || repo.graph_descendant_of(head, tip)?) - }) +fn note<'a>(label: String) -> Element<'a, Message> { + container(note_line(label)) + .padding([12, 16]) + .width(Length::Fill) + .height(Length::Fill) + .into() } -/// Raccourcit un identifiant de commit a 7 caracteres. -fn short_id(id: &str) -> String { - id.chars().take(7).collect() +fn note_line<'a>(label: String) -> Element<'a, Message> { + let typo = Typography::current(); + text(label) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()) + .into() } #[cfg(test)] mod tests { use super::*; + fn overview(name: &str, kind: BranchKind, is_head: bool) -> BranchOverview { + BranchOverview { + name: name.to_string(), + kind, + is_head, + upstream: None, + upstream_ahead: 0, + upstream_behind: 0, + ahead_of_head: 0, + behind_head: 0, + merged_into_head: false, + last_commit_time: None, + } + } + #[test] - fn merged_check_sees_commits_missing_from_head() { + fn action_note_describes_merge_and_rebase() { + let merge = action_note(Some(MergeStrategy::Merge), "feature/badges", "main", 3); + assert_eq!( + merge, + tf( + "branches_note_merge", + &[ + ("branch", "feature/badges"), + ("current", "main"), + ("count", "3") + ] + ) + ); + assert!(merge.contains("feature/badges") && merge.contains("main")); + assert!(merge.contains('3')); + + let rebase = action_note(Some(MergeStrategy::Rebase), "feature/badges", "main", 3); + assert_eq!( + rebase, + tf( + "branches_note_rebase", + &[("branch", "feature/badges"), ("current", "main")] + ) + ); + assert!(rebase.contains("feature/badges") && rebase.contains("main")); + assert_ne!(merge, rebase); + + assert_eq!(action_note(None, "feature/badges", "main", 3), ""); + } + + #[test] + fn current_branch_hides_branch_actions() { + use BranchAction::*; + let current = overview("main", BranchKind::Local, true); + let actions = available_actions(¤t); + for hidden in [Checkout, Merge, Rebase, Delete] { + assert!( + !actions.contains(&hidden), + "{hidden:?} shown on the current branch" + ); + } + assert_eq!(actions, [Rename, Pin, CopyName, ChangeUpstream, Archive]); + + let other = overview("feature", BranchKind::Local, false); + assert_eq!( + available_actions(&other), + [ + Checkout, + Merge, + Rebase, + Rename, + Pin, + CopyName, + ChangeUpstream, + Archive, + Delete + ] + ); + + let remote = overview("origin/feature", BranchKind::Remote, false); + assert_eq!( + available_actions(&remote), + [Checkout, Merge, Rebase, Pin, CopyName] + ); + } + + #[test] + fn remote_groups_are_built_per_remote() { + let branches = [ + overview("main", BranchKind::Local, true), + overview("origin/HEAD", BranchKind::Remote, false), + overview("origin/main", BranchKind::Remote, false), + overview("upstream/main", BranchKind::Remote, false), + overview("origin/feature/x", BranchKind::Remote, false), + ]; + let refs: Vec<&BranchOverview> = branches.iter().collect(); + let groups = remote_groups(&refs); + let names: Vec<(&str, Vec<&str>)> = groups + .iter() + .map(|group| { + ( + group.remote, + group.branches.iter().map(|b| b.name.as_str()).collect(), + ) + }) + .collect(); + assert_eq!( + names, + [ + ( + "origin", + vec!["origin/HEAD", "origin/main", "origin/feature/x"] + ), + ("upstream", vec!["upstream/main"]), + ] + ); + assert!(remote_groups(&refs[..1]).is_empty()); + } + + #[test] + fn a_confirmed_action_stops_when_the_repository_changed() { let dir = tempfile::tempdir().unwrap(); - let repo = git2::Repository::init(dir.path()).unwrap(); - let sig = git2::Signature::now("Test", "test@example.com").unwrap(); + let mut init = git2::RepositoryInitOptions::new(); + init.initial_head("main"); + let repo = git2::Repository::init_opts(dir.path(), &init).unwrap(); + let sig = git2::Signature::now("Tester", "tester@example.com").unwrap(); let tree = repo .find_tree(repo.index().unwrap().write_tree().unwrap()) .unwrap(); @@ -1168,16 +1574,143 @@ mod tests { .commit(Some("HEAD"), &sig, &sig, "base", &tree, &[]) .unwrap(); let base = repo.find_commit(base).unwrap(); - repo.branch("merged", &base, false).unwrap(); - // A commit on `ahead` only, with HEAD left on the base commit. - let ahead = repo - .commit(None, &sig, &sig, "ahead", &tree, &[&base]) + for name in ["feature", "topic"] { + repo.branch(name, &base, false).unwrap(); + } + let path = dir.path().to_str().unwrap(); + let at_base = Some(base.id()); + assert_eq!( + ensure_unchanged(path, "main", at_base, "topic", true), + Ok(()) + ); + + // `git checkout feature` in a terminal: a band that says "into main" is stale. + repo.set_head("refs/heads/feature").unwrap(); + assert!(ensure_unchanged(path, "main", at_base, "topic", false).is_err()); + assert_eq!( + ensure_unchanged(path, "feature", at_base, "topic", true), + Ok(()) + ); + + // topic gets a commit of its own: it is no longer merged into feature. + let own = repo + .commit(Some("refs/heads/topic"), &sig, &sig, "own", &tree, &[&base]) .unwrap(); - repo.branch("ahead", &repo.find_commit(ahead).unwrap(), false) + assert!(ensure_unchanged(path, "feature", at_base, "topic", true).is_err()); + assert_eq!( + ensure_unchanged(path, "feature", at_base, "topic", false), + Ok(()) + ); + + // A detached HEAD is named "HEAD" on every commit: moving it is caught by its commit. + repo.set_head_detached(base.id()).unwrap(); + assert_eq!( + ensure_unchanged(path, "HEAD", at_base, "topic", false), + Ok(()) + ); + repo.set_head_detached(own).unwrap(); + assert!(ensure_unchanged(path, "HEAD", at_base, "topic", false).is_err()); + + // A commit made on feature in a terminal moves HEAD too. + repo.set_head("refs/heads/feature").unwrap(); + repo.commit(Some("HEAD"), &sig, &sig, "next", &tree, &[&base]) .unwrap(); + assert!(ensure_unchanged(path, "feature", at_base, "topic", false).is_err()); + } + + #[test] + fn the_tab_opens_on_another_local_branch() { + let main = overview("main", BranchKind::Local, true); + let remote = overview("origin/main", BranchKind::Remote, false); + let list = vec![ + overview("feature", BranchKind::Local, false), + main.clone(), + overview("topic", BranchKind::Local, false), + remote.clone(), + ]; + let mut panel = BranchPanel::new(Vec::new()); + panel.repo = Some("/repo".into()); + let _ = panel.update(Message::Loaded("/repo".into(), 0, Ok((list.clone(), None)))); + assert_eq!(panel.selected.as_deref(), Some("feature")); + + // Pinned branches come first in the list, so the first of them is picked. + assert_eq!(initial_selection(&list, &["topic".into()]), Some("topic")); + // With no other local branch, the current one. + assert_eq!(initial_selection(&[main, remote], &[]), Some("main")); + assert_eq!(initial_selection(&[], &[]), None); + } + #[test] + fn the_current_branch_compares_with_its_upstream() { + let mut main = overview("main", BranchKind::Local, true); + assert_eq!(RelationCard::new(&main, "main"), None); + main.upstream = Some("origin/main".into()); + (main.upstream_ahead, main.upstream_behind) = (2, 1); + let card = |ahead, behind, against: &str| RelationCard { + ahead, + behind, + against: against.into(), + }; + assert_eq!( + RelationCard::new(&main, "main"), + Some(card(2, 1, "origin/main")) + ); + + let mut feature = overview("feature", BranchKind::Local, false); + (feature.ahead_of_head, feature.behind_head) = (3, 1); + assert_eq!( + RelationCard::new(&feature, "main"), + Some(card(3, 1, "main")) + ); + } + + #[test] + fn the_current_branch_lists_its_latest_commits() { + let dir = tempfile::tempdir().unwrap(); + let mut init = git2::RepositoryInitOptions::new(); + init.initial_head("main"); + let repo = git2::Repository::init_opts(dir.path(), &init).unwrap(); + let sig = git2::Signature::now("Tester", "tester@example.com").unwrap(); + let tree = repo + .find_tree(repo.index().unwrap().write_tree().unwrap()) + .unwrap(); + let mut parents = Vec::new(); + for summary in ["one", "two", "three"] { + let parent: Vec<&git2::Commit> = parents.last().into_iter().collect(); + let id = repo + .commit(Some("HEAD"), &sig, &sig, summary, &tree, &parent) + .unwrap(); + parents.push(repo.find_commit(id).unwrap()); + } + repo.branch("feature", &parents[1], false).unwrap(); + repo.commit( + Some("refs/heads/feature"), + &sig, + &sig, + "own", + &tree, + &[&parents[1]], + ) + .unwrap(); let path = dir.path().to_str().unwrap(); - assert!(merged_into_head(path, "merged").unwrap()); - assert!(!merged_into_head(path, "ahead").unwrap()); + let summaries = |commits: Vec| -> Vec { + commits.into_iter().map(|commit| commit.summary).collect() + }; + + let latest = read_commits(path, "main", true).unwrap(); + assert_eq!(summaries(latest), ["three", "two", "one"]); + let own = read_commits(path, "feature", false).unwrap(); + assert_eq!(summaries(own), ["own"]); + } + + #[test] + fn stale_means_old_or_no_commit() { + let now = 1_764_072_000; + let mut branch = overview("old", BranchKind::Local, false); + assert!(is_stale(&branch, now)); + branch.last_commit_time = Some(now - 31 * 24 * 60 * 60); + assert!(is_stale(&branch, now)); + branch.last_commit_time = Some(now - 24 * 60 * 60); + assert!(!is_stale(&branch, now)); } } diff --git a/src/ui/changes.rs b/src/ui/changes.rs new file mode 100644 index 0000000..7f378cd --- /dev/null +++ b/src/ui/changes.rs @@ -0,0 +1,1220 @@ +//! The Changes tab: staged and unstaged files with their line counts, the diff of the +//! selected file, and the commit box. + +use std::collections::HashSet; +use std::path::Path; +use std::sync::Arc; + +use colony_ui::theme::{contrast_on, Palette}; +use colony_ui::widgets::icons; +use colony_ui::{fonts, Typography}; +use git2::{ObjectType, Repository}; +use iced::widget::{button, column, container, pick_list, row, scrollable, text, text_input}; +use iced::widget::{Column, Space}; +use iced::{Alignment, Border, Color, Element, Length, Task}; + +use crate::git::branch::{list_branches, restore_file_from_branch}; +use crate::git::commit::commit_index; +use crate::git::diff::diff_file; +use crate::git::status::{discard_file, read_changes, read_repo_status, ChangeKind, ChangedFile}; +use crate::i18n::{t, tf}; +use crate::ui::context::{git_task, RepoContext}; +use crate::ui::diff_view::{self, Diff}; +use crate::ui::widgets::button as gs_button; +use crate::ui::widgets::menu::{self, Entry, MenuItem}; +use crate::ui::widgets::toast::Toast; + +const MORE_GLYPH: &str = "\u{f141}"; +/// The summary length past which the counter turns to the warning colour. +const SUMMARY_SOFT_LIMIT: usize = 72; +/// Width of the file list. +const LIST_WIDTH: f32 = 270.0; + +/// Label key and text key of each commit message template. +const TEMPLATES: [(&str, &str); 3] = [ + ("changes_template_wip", "changes_template_wip_text"), + ("changes_template_feature", "changes_template_feature_text"), + ("changes_template_fix", "changes_template_fix_text"), +]; + +/// What the repository looks like to the Changes tab, read off the UI thread. +#[derive(Debug, Clone, Default)] +pub struct Snapshot { + staged: Vec, + unstaged: Vec, + branch: Option, + author: Option, + signoff_line: Option, + /// Local then remote branches, for "Restore from branch…". + branches: Vec, +} + +/// A step of "Restore from branch…". +#[derive(Debug, Clone)] +pub enum Restore { + /// Asks which branch to restore this file from. + Open(String), + Branch(String), + Confirm, + Cancel, +} + +#[derive(Debug, Clone)] +pub enum Message { + Loaded(Arc, Result), + /// Shows the diff of a file, staged or not. + Select(String, bool), + /// The patch of the file `(path, staged)`. + DiffLoaded( + Arc, + (String, bool), + Result, String>, + ), + /// Stages an unstaged file, or unstages a staged one. + Toggle(String, bool), + StageAll, + UnstageAll, + /// Asks to confirm discarding the changes of a file, or closes the question. + ConfirmDiscard(Option), + Discard(String), + Summary(String), + Description(String), + TemplateSelected(usize), + ToggleSignoff, + /// Opens or closes the commit box's "⋯" menu. + CommitMenu(bool), + Commit, + /// The new commit's short hash, or the error. + Committed(Arc, Result), + /// A stage, unstage, discard or restore ended; the key names the failure title. + ActionDone(Arc, &'static str, Result<(), String>), + /// Opens the "⋯" menu of the diff header for a file, or closes it. + FileMenu(Option), + RestoreFromBranch(Restore), + OpenFile(String), + CopyPath(String), +} + +#[derive(Default)] +pub struct ChangesPanel { + repo: Option>, + snapshot: Option, + /// Files listed in either group, each counted once. + count: usize, + selected: Option<(String, bool)>, + diff: Option, + busy: bool, + summary: String, + description: String, + signoff: bool, + file_menu: Option, + commit_menu: bool, + confirm_discard: Option, + /// The file and branch of a restore waiting for confirmation. + restore: Option<(String, Option)>, +} + +impl ChangesPanel { + /// Reads the changes of `repo` off the UI thread. Reloading the same repository keeps + /// the commit drafts and the selected file. + pub fn load(&mut self, repo: &RepoContext) -> Task { + if self.repo.as_deref() != Some(repo.path()) { + *self = Self { + repo: Some(repo.path_arc()), + ..Self::default() + }; + } + self.refresh() + } + + /// The number of changed files, shown on the Changes tab. + pub fn count(&self) -> usize { + self.count + } + + /// Handles a message; the toast, if any, is for the application to show. + pub fn update(&mut self, message: Message) -> (Task, Option) { + match message { + Message::Loaded(repo, result) => { + if !self.is_current(&repo) { + return (Task::none(), None); + } + match result { + Ok(snapshot) => (self.apply_snapshot(snapshot), None), + Err(err) => ( + Task::none(), + Some(Toast::error(t("changes_load_failed"), err)), + ), + } + } + Message::Select(path, staged) => { + self.file_menu = None; + self.selected = Some((path, staged)); + self.diff = Some(Diff::Loading); + (self.load_diff(), None) + } + Message::DiffLoaded(repo, key, result) => { + if self.is_current(&repo) && self.selected.as_ref() == Some(&key) { + self.diff = Some(Diff::loaded(result)); + } + (Task::none(), None) + } + Message::Toggle(path, staged) => { + let paths = self.with_old_paths(staged, |file| file.path == path); + (self.stage(paths, staged), None) + } + Message::StageAll => { + let paths = self.with_old_paths(false, |_| true); + (self.stage(paths, false), None) + } + Message::UnstageAll => { + let paths = self.with_old_paths(true, |_| true); + (self.stage(paths, true), None) + } + Message::ConfirmDiscard(path) => { + self.file_menu = None; + self.restore = None; + self.confirm_discard = path; + (Task::none(), None) + } + Message::Discard(path) => { + self.confirm_discard = None; + let task = self.run("changes_discard_failed", move |repo| { + discard_file(repo, &path).map_err(|err| err.to_string()) + }); + (task, None) + } + Message::Summary(summary) => { + self.summary = summary; + (Task::none(), None) + } + Message::Description(description) => { + self.description = description; + (Task::none(), None) + } + Message::TemplateSelected(index) => { + self.commit_menu = false; + if let Some((_, text_key)) = TEMPLATES.get(index) { + let (summary, description) = + t(text_key).split_once("\n\n").unwrap_or((t(text_key), "")); + self.summary = summary.to_string(); + self.description = description.to_string(); + } + (Task::none(), None) + } + Message::ToggleSignoff => { + self.commit_menu = false; + self.signoff = !self.signoff && self.signoff_line().is_some(); + (Task::none(), None) + } + Message::CommitMenu(open) => { + self.commit_menu = open; + (Task::none(), None) + } + Message::Commit => { + if !self.can_commit() { + return (Task::none(), None); + } + let message = commit_message( + &self.summary, + &self.description, + self.signoff.then(|| self.signoff_line()).flatten(), + ); + let Some(repo) = self.repo.clone() else { + return (Task::none(), None); + }; + self.busy = true; + let task = git_task( + repo, + move |repo| { + commit_index(repo, &message) + .map(|oid| oid.to_string()[..7].to_string()) + .map_err(|err| err.to_string()) + }, + Message::Committed, + ); + (task, None) + } + Message::Committed(repo, result) => { + if !self.is_current(&repo) { + return (Task::none(), None); + } + self.busy = false; + let toast = match result { + Ok(hash) => { + self.summary.clear(); + self.description.clear(); + Toast::success(tf("changes_committed", &[("hash", &hash)])) + } + Err(err) => Toast::error(t("changes_commit_failed"), err), + }; + (self.refresh(), Some(toast)) + } + Message::ActionDone(repo, failed, result) => { + if !self.is_current(&repo) { + return (Task::none(), None); + } + self.busy = false; + let toast = result.err().map(|err| Toast::error(t(failed), err)); + (self.refresh(), toast) + } + Message::FileMenu(path) => { + self.file_menu = path; + (Task::none(), None) + } + Message::RestoreFromBranch(step) => self.restore_step(step), + Message::OpenFile(path) => { + self.file_menu = None; + let toast = self.repo.as_deref().and_then(|repo| { + open::that_detached(Path::new(repo).join(&path)) + .err() + .map(|err| Toast::error(t("changes_open_file_failed"), err.to_string())) + }); + (Task::none(), toast) + } + Message::CopyPath(path) => { + self.file_menu = None; + let Some(repo) = self.repo.as_deref() else { + return (Task::none(), None); + }; + let full = Path::new(repo).join(path).to_string_lossy().into_owned(); + (iced::clipboard::write(full), None) + } + } + } + + fn restore_step(&mut self, step: Restore) -> (Task, Option) { + match step { + Restore::Open(path) => { + self.file_menu = None; + self.confirm_discard = None; + let branch = self.snapshot.as_ref().and_then(|s| s.branch.clone()); + self.restore = Some((path, branch)); + } + Restore::Branch(branch) => { + if let Some((_, chosen)) = &mut self.restore { + *chosen = Some(branch); + } + } + Restore::Cancel => self.restore = None, + Restore::Confirm => { + if let Some((path, Some(branch))) = self.restore.take() { + let task = self.run("changes_restore_failed", move |repo| { + restore_file_from_branch(repo, &branch, &path) + }); + return (task, None); + } + } + } + (Task::none(), None) + } + + fn is_current(&self, repo: &str) -> bool { + self.repo.as_deref() == Some(repo) + } + + fn signoff_line(&self) -> Option<&str> { + self.snapshot.as_ref()?.signoff_line.as_deref() + } + + fn staged(&self) -> &[ChangedFile] { + self.snapshot.as_ref().map_or(&[], |s| &s.staged) + } + + fn unstaged(&self) -> &[ChangedFile] { + self.snapshot.as_ref().map_or(&[], |s| &s.unstaged) + } + + /// A commit needs a summary and at least one staged file. + fn can_commit(&self) -> bool { + !self.busy && !self.summary.trim().is_empty() && !self.staged().is_empty() + } + + /// The paths of the matching files of one group, with the old path of a renamed one so + /// unstaging it also puts back the deletion. + fn with_old_paths(&self, staged: bool, keep: impl Fn(&ChangedFile) -> bool) -> Vec { + let files = if staged { + self.staged() + } else { + self.unstaged() + }; + files + .iter() + .filter(|file| keep(file)) + .flat_map(|file| std::iter::once(file.path.clone()).chain(file.old_path.clone())) + .collect() + } + + /// Stages `paths`, or unstages them when `staged` is true. + fn stage(&mut self, paths: Vec, staged: bool) -> Task { + if paths.is_empty() { + return Task::none(); + } + if staged { + self.run("changes_unstage_failed", move |repo| { + unstage_paths(repo, &paths).map_err(|err| err.to_string()) + }) + } else { + self.run("changes_stage_failed", move |repo| { + stage_paths(repo, &paths).map_err(|err| err.to_string()) + }) + } + } + + /// Runs a git action unless one is running; the changes are read again when it ends. + fn run( + &mut self, + failed: &'static str, + job: impl FnOnce(&str) -> Result<(), String> + Send + 'static, + ) -> Task { + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + if self.busy { + return Task::none(); + } + self.busy = true; + git_task(repo, job, move |repo, result| { + Message::ActionDone(repo, failed, result) + }) + } + + fn refresh(&self) -> Task { + match self.repo.clone() { + Some(repo) => git_task(repo, read_snapshot, Message::Loaded), + None => Task::none(), + } + } + + fn load_diff(&mut self) -> Task { + let (Some(repo), Some(key)) = (self.repo.clone(), self.selected.clone()) else { + return Task::none(); + }; + let (path, staged) = key.clone(); + git_task( + repo, + move |repo| { + diff_file(repo, &path, staged) + .map(|diff| diff.map(|diff| (diff.patch, diff.truncated))) + .map_err(|err| err.to_string()) + }, + move |repo, result| Message::DiffLoaded(repo, key.clone(), result), + ) + } + + /// Shows `snapshot`. The selected file stays selected, in the other group if it moved + /// there; with no selection left, the first file is selected. + fn apply_snapshot(&mut self, snapshot: Snapshot) -> Task { + if snapshot.signoff_line.is_none() { + self.signoff = false; + } + self.count = snapshot + .staged + .iter() + .chain(&snapshot.unstaged) + .map(|file| file.path.as_str()) + .collect::>() + .len(); + let listed = |path: &str, staged: bool| { + let files = if staged { + &snapshot.staged + } else { + &snapshot.unstaged + }; + files.iter().any(|file| file.path == path) + }; + let previous = self.selected.take(); + let selected = match previous.clone() { + Some((path, staged)) if listed(&path, staged) => Some((path, staged)), + Some((path, staged)) if listed(&path, !staged) => Some((path, !staged)), + _ => None, + } + .or_else(|| { + let first = |files: &[ChangedFile], staged| { + files.first().map(|file| (file.path.clone(), staged)) + }; + first(&snapshot.unstaged, false).or_else(|| first(&snapshot.staged, true)) + }); + self.snapshot = Some(snapshot); + // Reloading the shown file keeps its diff and scroll offset until the new one arrives. + if selected != previous { + self.diff = Some(Diff::Loading); + } + self.selected = selected; + if self.selected.is_some() { + self.load_diff() + } else { + self.diff = None; + Task::none() + } + } + + pub fn view(&self) -> Element<'_, Message> { + let Some(snapshot) = &self.snapshot else { + return Space::new().into(); + }; + if snapshot.staged.is_empty() && snapshot.unstaged.is_empty() { + return self.view_nothing(snapshot); + } + let list = scrollable( + column![ + self.group(true, &snapshot.staged), + self.group(false, &snapshot.unstaged), + ] + .padding([10, 8]), + ) + .height(Length::Fill); + let list = container(list) + .width(Length::Fixed(LIST_WIDTH)) + .height(Length::Fill); + + let right = column![ + self.diff_header(), + diff_view::pane(self.diff.as_ref(), t("changes_select_file")), + self.commit_box(snapshot) + ] + .width(Length::Fill) + .height(Length::Fill); + + row![list, vertical_divider(), right] + .height(Length::Fill) + .into() + } + + fn view_nothing(&self, snapshot: &Snapshot) -> Element<'_, Message> { + let typo = Typography::current(); + let branch = snapshot.branch.as_deref().unwrap_or("HEAD"); + container( + column![ + text(t("changes_nothing_title")) + .size(typo.sz(15)) + .font(typo.bold) + .color(Palette::TEXT_PRIMARY()), + text(tf("changes_nothing_detail", &[("branch", branch)])) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + ] + .spacing(6) + .align_x(Alignment::Center), + ) + .center(Length::Fill) + .into() + } + + /// "STAGED · n" or "UNSTAGED · n" with its "Unstage all" or "Stage all" link, then the files. + fn group<'a>(&'a self, staged: bool, files: &'a [ChangedFile]) -> Element<'a, Message> { + let typo = Typography::current(); + let count = files.len().to_string(); + let (title, link, all) = if staged { + ( + tf("changes_staged", &[("count", &count)]), + t("changes_unstage_all"), + Message::UnstageAll, + ) + } else { + ( + tf("changes_unstaged", &[("count", &count)]), + t("changes_stage_all"), + Message::StageAll, + ) + }; + let link = button( + text(link) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::ACCENT()), + ) + .padding(0) + .style(|_, _| button::Style::default()) + .on_press_maybe((!self.busy && !files.is_empty()).then_some(all)); + let header = row![ + text(title) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .width(Length::Fill), + link, + ] + .align_y(Alignment::Center) + .padding([4, 8]); + + let mut rows = Column::new().push(header).spacing(1); + for file in files { + rows = rows.push(self.file_row(file, staged)); + } + container(rows).padding([6, 0]).into() + } + + fn file_row<'a>(&'a self, file: &'a ChangedFile, staged: bool) -> Element<'a, Message> { + let typo = Typography::current(); + let size = typo.sz(12); + let selected = self.selected.as_ref().map(|(path, s)| (path.as_str(), *s)) + == Some((&file.path, staged)); + + let accent = Palette::ACCENT(); + let check = button( + text(if staged { icons::CHECK } else { "" }) + .size(typo.sz(9)) + .font(fonts::glyph_font()) + .color(contrast_on(accent)) + .center(), + ) + .width(16) + .height(16) + .padding(0) + .on_press_maybe((!self.busy).then(|| Message::Toggle(file.path.clone(), staged))) + .style(move |_, _| button::Style { + background: Some(if staged { accent } else { Color::TRANSPARENT }.into()), + border: Border::default().rounded(4).width(1).color(if staged { + accent + } else { + Palette::BG_SELECTED() + }), + ..Default::default() + }); + + let (letter, letter_color) = kind_letter(file.kind); + let (folder, name) = match file.path.rsplit_once('/') { + Some((folder, name)) => (folder, name), + None => ("", file.path.as_str()), + }; + let mut content = row![ + check, + text(letter) + .size(size) + .font(typo.bold) + .color(letter_color) + .width(14) + .center(), + text(name) + .size(size) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()), + text(folder) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .width(Length::Fill), + ] + .spacing(8) + .align_y(Alignment::Center); + if file.additions > 0 { + content = content.push( + text(format!("+{}", file.additions)) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::SUCCESS()), + ); + } + if file.deletions > 0 { + content = content.push( + text(format!("−{}", file.deletions)) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::ERROR()), + ); + } + + button(content) + .on_press(Message::Select(file.path.clone(), staged)) + .padding([6, 8]) + .width(Length::Fill) + .style(move |_, status| button::Style { + background: (selected + || matches!(status, button::Status::Hovered | button::Status::Pressed)) + .then(|| Palette::BG_CARD_HOVER().into()), + border: Border::default().rounded(6), + ..Default::default() + }) + .into() + } + + /// The selected file's path, its Stage or Unstage button and its "⋯" menu, then a + /// pending discard or restore question. + fn diff_header(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let mut header = column![]; + if let Some((path, staged)) = &self.selected { + let (label, toggle) = if *staged { + ( + t("changes_unstage_file"), + Message::Toggle(path.clone(), true), + ) + } else { + ( + t("changes_stage_file"), + Message::Toggle(path.clone(), false), + ) + }; + let mut entries = vec![ + item( + t("changes_restore_from_branch"), + Message::RestoreFromBranch(Restore::Open(path.clone())), + false, + ), + item( + t("changes_open_file"), + Message::OpenFile(path.clone()), + false, + ), + item( + t("changes_copy_path"), + Message::CopyPath(path.clone()), + false, + ), + ]; + // Discarding goes back to the index version, so only work tree changes can go. + if !*staged { + entries.push(Entry::Separator); + entries.push(item( + t("changes_discard"), + Message::ConfirmDiscard(Some(path.clone())), + true, + )); + } + let menu_open = self.file_menu.as_ref() == Some(path); + let more = menu::popup( + gs_button::icon( + MORE_GLYPH, + Some(Message::FileMenu((!menu_open).then(|| path.clone()))), + t("changes_file_actions"), + ), + menu_open, + entries, + Message::FileMenu(None), + ); + header = header.push( + row![ + text(path.as_str()) + .size(typo.sz(13)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()) + .width(Length::Fill), + gs_button::secondary(label, (!self.busy).then_some(toggle)), + more, + ] + .spacing(10) + .align_y(Alignment::Center) + .padding([10, 16]), + ); + } + if let Some(path) = &self.confirm_discard { + header = header.push(question( + vec![text(tf("changes_discard_confirm", &[("file", path)])) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY()) + .into()], + gs_button::danger( + t("changes_discard_button"), + (!self.busy).then(|| Message::Discard(path.clone())), + ), + Message::ConfirmDiscard(None), + )); + } + if let Some((path, branch)) = &self.restore { + let branches = self + .snapshot + .as_ref() + .map(|s| s.branches.clone()) + .unwrap_or_default(); + let prompt = |label: String| { + text(label) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY()) + }; + header = header.push(question( + vec![ + prompt(tf("changes_restore_prompt", &[("file", path)])).into(), + pick_list(branches, branch.clone(), |branch| { + Message::RestoreFromBranch(Restore::Branch(branch)) + }) + .text_size(typo.sz(12)) + .font(typo.regular) + .into(), + prompt(t("changes_restore_warning").to_string()).into(), + ], + gs_button::danger( + t("changes_restore_button"), + (!self.busy && branch.is_some()) + .then_some(Message::RestoreFromBranch(Restore::Confirm)), + ), + Message::RestoreFromBranch(Restore::Cancel), + )); + } + column![header, horizontal_divider()].into() + } + + fn commit_box<'a>(&'a self, snapshot: &'a Snapshot) -> Element<'a, Message> { + let typo = Typography::current(); + let length = self.summary.chars().count(); + let counter_color = if length > SUMMARY_SOFT_LIMIT { + Palette::WARNING() + } else { + Palette::TEXT_DIMMEST() + }; + let summary = field( + text_input(t("changes_summary_placeholder"), &self.summary) + .on_input(Message::Summary) + .on_submit_maybe(self.can_commit().then_some(Message::Commit)), + Some( + text(format!("{length} / {SUMMARY_SOFT_LIMIT}")) + .size(typo.sz(11)) + .font(typo.regular) + .color(counter_color) + .into(), + ), + ); + let description = field( + text_input(t("changes_description_placeholder"), &self.description) + .on_input(Message::Description), + None, + ); + + let staged = snapshot.staged.len(); + let mut info = vec![if staged == 1 { + t("changes_staged_one").to_string() + } else { + tf("changes_staged_many", &[("count", &staged.to_string())]) + }]; + if let Some(branch) = &snapshot.branch { + info.push(tf("changes_on_branch", &[("branch", branch)])); + } + if let Some(author) = &snapshot.author { + info.push(tf("changes_author", &[("name", author)])); + } + + let more = menu::popup( + gs_button::icon( + MORE_GLYPH, + Some(Message::CommitMenu(!self.commit_menu)), + t("changes_commit_options"), + ), + self.commit_menu, + self.commit_entries(), + Message::CommitMenu(false), + ); + let actions = row![ + text(info.join(" · ")) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .width(Length::Fill), + more, + gs_button::primary( + t("changes_commit"), + self.can_commit().then_some(Message::Commit) + ), + ] + .spacing(10) + .align_y(Alignment::Center); + + column![ + horizontal_divider(), + container(column![summary, description, actions].spacing(8)) + .padding([12, 14]) + .width(Length::Fill) + .style(|_| container::Style { + background: Some(Palette::BG_SIDEBAR().into()), + ..Default::default() + }), + ] + .into() + } + + /// The templates, then the sign-off toggle. + fn commit_entries(&self) -> Vec> { + let mut entries: Vec> = TEMPLATES + .iter() + .enumerate() + .map(|(index, (label, _))| { + item( + &tf("changes_template", &[("name", t(label))]), + Message::TemplateSelected(index), + false, + ) + }) + .collect(); + entries.push(Entry::Separator); + entries.push(match self.signoff_line() { + Some(_) => Entry::Item(MenuItem { + label: t("changes_signoff").to_string(), + shortcut: self.signoff.then(|| icons::CHECK.to_string()), + on_select: Message::ToggleSignoff, + danger: false, + }), + None => item( + t("changes_signoff_missing"), + Message::CommitMenu(false), + false, + ), + }); + entries + } +} + +/// Summary, blank line, description, blank line, sign-off; empty parts are left out. +fn commit_message(summary: &str, description: &str, signoff: Option<&str>) -> String { + [ + summary.trim(), + description.trim(), + signoff.unwrap_or_default(), + ] + .into_iter() + .filter(|part| !part.is_empty()) + .collect::>() + .join("\n\n") +} + +/// The change letter of a file and its colour. +fn kind_letter(kind: ChangeKind) -> (&'static str, Color) { + match kind { + ChangeKind::Added => ("A", Palette::SUCCESS()), + ChangeKind::Untracked => ("U", Palette::SUCCESS()), + ChangeKind::Modified => ("M", Palette::WARNING()), + ChangeKind::TypeChange => ("T", Palette::WARNING()), + ChangeKind::Deleted => ("D", Palette::ERROR()), + ChangeKind::Conflicted => ("C", Palette::ERROR()), + ChangeKind::Renamed => ("R", Palette::ACCENT_ICON()), + } +} + +pub(crate) fn item(label: &str, on_select: M, danger: bool) -> Entry { + Entry::Item(MenuItem { + label: label.to_string(), + shortcut: None, + on_select, + danger, + }) +} + +/// A confirmation band under a header: the question, Cancel, then the action. +pub(crate) fn question<'a, M: Clone + 'a>( + prompt: Vec>, + action: Element<'a, M>, + cancel: M, +) -> Element<'a, M> { + let mut band = iced::widget::Row::with_children(prompt) + .spacing(8) + .align_y(Alignment::Center); + band = band + .push(Space::new().width(Length::Fill)) + .push(gs_button::secondary(t("changes_cancel"), Some(cancel))) + .push(action); + container(band) + .padding([8, 16]) + .width(Length::Fill) + .style(|_| container::Style { + background: Some(Palette::BG_CARD().into()), + ..Default::default() + }) + .into() +} + +/// A text input on `bg_input`, with an optional trailing element inside the field. +pub(crate) fn field<'a, M: Clone + 'a>( + input: text_input::TextInput<'a, M>, + trailing: Option>, +) -> Element<'a, M> { + let typo = Typography::current(); + let input = input + .size(typo.sz(13)) + .font(typo.regular) + .padding(0) + .style(|_, _| text_input::Style { + background: Color::TRANSPARENT.into(), + border: Border::default(), + icon: Palette::TEXT_DIMMER(), + placeholder: Palette::TEXT_PLACEHOLDER(), + value: Palette::TEXT_PRIMARY(), + selection: Palette::ACCENT().scale_alpha(0.35), + }); + let mut content = row![input].spacing(8).align_y(Alignment::Center); + if let Some(trailing) = trailing { + content = content.push(trailing); + } + container(content) + .padding([8, 10]) + .width(Length::Fill) + .style(|_| container::Style { + background: Some(Palette::BG_INPUT().into()), + border: Border::default().rounded(6), + ..Default::default() + }) + .into() +} + +pub(crate) fn horizontal_divider<'a, M: 'a>() -> Element<'a, M> { + container(Space::new().width(Length::Fill).height(1)) + .style(|_| container::Style { + background: Some(Palette::DIVIDER().into()), + ..Default::default() + }) + .into() +} + +pub(crate) fn vertical_divider<'a, M: 'a>() -> Element<'a, M> { + container(Space::new().width(1).height(Length::Fill)) + .style(|_| container::Style { + background: Some(Palette::DIVIDER().into()), + ..Default::default() + }) + .into() +} + +/// Reads the changed files with their counts, the branch, the identity and the branch +/// names. No patch is built: only the selected file's is loaded. +fn read_snapshot(repo_path: &str) -> Result { + let changes = read_changes(repo_path).map_err(|err| err.to_string())?; + let branch = read_repo_status(repo_path).ok().and_then(|s| s.branch); + let signature = Repository::open(repo_path) + .and_then(|repo| repo.signature().map(|sig| sig.to_owned())) + .ok(); + let author = signature + .as_ref() + .and_then(|sig| sig.name().ok().map(str::to_string)); + let signoff_line = signature.as_ref().map(|sig| { + format!( + "Signed-off-by: {} <{}>", + sig.name().unwrap_or_default(), + sig.email().unwrap_or_default() + ) + }); + let branches = list_branches(repo_path) + .map(|branches| branches.into_iter().map(|branch| branch.name).collect()) + .unwrap_or_default(); + Ok(Snapshot { + staged: changes.staged, + unstaged: changes.unstaged, + branch, + author, + signoff_line, + branches, + }) +} + +/// Stages files of the repository: the content of each one that exists in the work tree, +/// otherwise its deletion. Paths are relative to the repository root, not to the process's +/// current folder. The index is written once. +fn stage_paths(repo_path: &str, paths: &[String]) -> Result<(), git2::Error> { + let repo = Repository::open(repo_path)?; + let workdir = repo + .workdir() + .ok_or_else(|| git2::Error::from_str(t("repo_no_work_tree")))?; + let mut index = repo.index()?; + for path in paths { + let path = Path::new(path); + // symlink_metadata: a dangling symlink is still a file to add. + if workdir.join(path).symlink_metadata().is_ok() { + index.add_path(path)?; + } else { + index.remove_path(path)?; + } + } + index.write() +} + +/// Puts the index entries of `paths` back to HEAD, or removes them before the first commit. +fn unstage_paths(repo_path: &str, paths: &[String]) -> Result<(), git2::Error> { + let repo = Repository::open(repo_path)?; + let head = match repo.head() { + Ok(head) => Some(head.peel(ObjectType::Commit)?), + Err(err) if err.code() == git2::ErrorCode::UnbornBranch => None, + Err(err) => return Err(err), + }; + repo.reset_default(head.as_ref(), paths.iter().map(Path::new)) +} + +#[cfg(test)] +mod tests { + use super::*; + use git2::Status; + + fn repo_with_identity() -> (tempfile::TempDir, Repository) { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + let mut config = repo.config().unwrap(); + config.set_str("user.name", "Test User").unwrap(); + config.set_str("user.email", "test@example.com").unwrap(); + (dir, repo) + } + + fn paths(names: &[&str]) -> Vec { + names.iter().map(|name| name.to_string()).collect() + } + + #[test] + fn stage_path_uses_the_repo_workdir() { + let (dir, repo) = repo_with_identity(); + let repo_path = dir.path().to_str().unwrap(); + + // Cargo runs tests from the crate root, which has a Cargo.toml and no notes file. + // Code that checked these names in the process's folder got both of them wrong. + let modified = "only-in-the-test-repo.txt"; + let deleted = "Cargo.toml"; + let workdir = dir.path(); + std::fs::write(workdir.join(modified), "one").unwrap(); + std::fs::write(workdir.join(deleted), "[package]").unwrap(); + stage_paths(repo_path, &paths(&[modified, deleted])).unwrap(); + commit_index(repo_path, "initial").unwrap(); + + std::fs::write(workdir.join(modified), "two").unwrap(); + std::fs::remove_file(workdir.join(deleted)).unwrap(); + stage_paths(repo_path, &paths(&[modified, deleted])).unwrap(); + + let status = |name| repo.status_file(Path::new(name)).unwrap(); + assert_eq!(status(modified), Status::INDEX_MODIFIED); + assert_eq!(status(deleted), Status::INDEX_DELETED); + + // Unstaging puts the HEAD version back in the index; the work tree keeps the change. + unstage_paths(repo_path, &paths(&[modified, deleted])).unwrap(); + assert_eq!(status(modified), Status::WT_MODIFIED); + assert_eq!(status(deleted), Status::WT_DELETED); + } + + #[test] + fn unstaging_before_the_first_commit_leaves_the_file_untracked() { + let (dir, repo) = repo_with_identity(); + let repo_path = dir.path().to_str().unwrap(); + std::fs::write(dir.path().join("new.txt"), "x").unwrap(); + stage_paths(repo_path, &paths(&["new.txt"])).unwrap(); + unstage_paths(repo_path, &paths(&["new.txt"])).unwrap(); + assert_eq!( + repo.status_file(Path::new("new.txt")).unwrap(), + Status::WT_NEW + ); + } + + #[test] + fn commit_message_joins_summary_description_and_signoff() { + let signoff = "Signed-off-by: Test User "; + assert_eq!( + commit_message(" feat: add X ", "Why X.\n", Some(signoff)), + format!("feat: add X\n\nWhy X.\n\n{signoff}") + ); + assert_eq!(commit_message("fix: y", " ", None), "fix: y"); + assert_eq!( + commit_message("fix: y", "", Some(signoff)), + format!("fix: y\n\n{signoff}") + ); + } + + fn changed_file(path: &str) -> ChangedFile { + ChangedFile { + path: path.to_string(), + old_path: None, + kind: ChangeKind::Modified, + additions: 1, + deletions: 0, + binary: false, + } + } + + #[test] + fn commit_disabled_without_summary_or_staged_files() { + let mut panel = ChangesPanel { + repo: Some("/repo".into()), + snapshot: Some(Snapshot::default()), + summary: "feat: add X".to_string(), + ..ChangesPanel::default() + }; + assert!(!panel.can_commit(), "nothing staged"); + + panel.snapshot = Some(Snapshot { + staged: vec![changed_file("a.txt")], + ..Snapshot::default() + }); + assert!(panel.can_commit()); + + panel.summary = " ".to_string(); + assert!(!panel.can_commit(), "blank summary"); + + panel.summary = "feat: add X".to_string(); + panel.busy = true; + assert!(!panel.can_commit(), "an action is running"); + } + + #[test] + fn a_reload_keeps_the_shown_diff_until_the_new_one_arrives() { + let snapshot = || Snapshot { + unstaged: vec![changed_file("a.txt"), changed_file("b.txt")], + ..Snapshot::default() + }; + let mut panel = ChangesPanel { + repo: Some("/repo".into()), + ..ChangesPanel::default() + }; + let _ = panel.apply_snapshot(snapshot()); + assert!(matches!(panel.diff, Some(Diff::Loading))); + + panel.diff = Some(Diff::Empty); + let _ = panel.apply_snapshot(snapshot()); + assert!( + matches!(panel.diff, Some(Diff::Empty)), + "same file selected" + ); + + panel.selected = Some(("gone.txt".to_string(), false)); + let _ = panel.apply_snapshot(snapshot()); + assert!(matches!(panel.diff, Some(Diff::Loading)), "selection moved"); + } + + #[test] + fn reloading_the_same_repository_keeps_the_drafts() { + let (dir, _repo) = repo_with_identity(); + let context = RepoContext::from_path(dir.path()).unwrap(); + let mut panel = ChangesPanel::default(); + let _ = panel.load(&context); + panel.summary = "feat: draft".to_string(); + panel.description = "body".to_string(); + let _ = panel.load(&context); + assert_eq!(panel.summary, "feat: draft"); + assert_eq!(panel.description, "body"); + + let other = tempfile::tempdir().unwrap(); + Repository::init(other.path()).unwrap(); + let _ = panel.load(&RepoContext::from_path(other.path()).unwrap()); + assert!(panel.summary.is_empty()); + } + + #[test] + fn snapshot_lists_changes_and_reads_the_identity() { + let (dir, _repo) = repo_with_identity(); + std::fs::write(dir.path().join("new.txt"), "x\ny\n").unwrap(); + + let snapshot = read_snapshot(dir.path().to_str().unwrap()).unwrap(); + assert!(snapshot.staged.is_empty()); + assert_eq!(snapshot.unstaged[0].path, "new.txt"); + assert_eq!(snapshot.unstaged[0].additions, 2); + assert_eq!(snapshot.author.as_deref(), Some("Test User")); + assert_eq!( + snapshot.signoff_line.as_deref(), + Some("Signed-off-by: Test User ") + ); + } + + #[test] + fn a_staged_file_stays_selected_in_its_new_group() { + let mut panel = ChangesPanel { + repo: Some("/repo".into()), + selected: Some(("a.txt".to_string(), false)), + ..ChangesPanel::default() + }; + let _ = panel.apply_snapshot(Snapshot { + staged: vec![changed_file("a.txt")], + unstaged: vec![changed_file("a.txt"), changed_file("b.txt")], + ..Snapshot::default() + }); + assert_eq!(panel.selected, Some(("a.txt".to_string(), false))); + assert_eq!(panel.count(), 2, "a file in both groups counts once"); + + let _ = panel.apply_snapshot(Snapshot { + staged: vec![changed_file("a.txt")], + unstaged: vec![changed_file("b.txt")], + ..Snapshot::default() + }); + assert_eq!(panel.selected, Some(("a.txt".to_string(), true))); + } +} diff --git a/src/ui/clone.rs b/src/ui/clone.rs deleted file mode 100644 index aa5bcfb..0000000 --- a/src/ui/clone.rs +++ /dev/null @@ -1,1158 +0,0 @@ -//! Panneau de clonage de dépôts distants via GitHub ou GitLab. -//! -//! Ce module gère la recherche de dépôts distants, la sélection et le clonage -//! vers un répertoire local. Les fonctions réseau sont exécutées de manière -//! asynchrone via des tâches Iced. - -use std::collections::HashSet; -use std::path::PathBuf; - -use iced::futures::{SinkExt, Stream}; -use iced::widget::{ - button, column, container, pick_list, progress_bar, row, text, text_input, Space, -}; -use iced::{Alignment, Element, Length, Task}; -use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT}; -use reqwest::Client; -use reqwest::StatusCode; -use serde::Deserialize; -use url::Url; - -use crate::auth::AuthManager; -use crate::config::NetworkOptions; -use crate::error::AppError; -use crate::git::clone::{clone_repository, CloneProgress, CloneRequest}; -use crate::ui::recent; -use crate::ui::theme::Theme; - -// --------------------------------------------------------------------------- -// Fournisseur distant (GitHub, GitLab) -// --------------------------------------------------------------------------- - -/// Représente un fournisseur de dépôts distants. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Provider { - GitHub, - GitLab, -} - -impl Provider { - /// Libellé lisible du fournisseur. - fn label(&self) -> &'static str { - match self { - Provider::GitHub => "GitHub", - Provider::GitLab => "GitLab", - } - } - - /// Hôte principal du fournisseur. - fn host(&self) -> &'static str { - match self { - Provider::GitHub => "github.com", - Provider::GitLab => "gitlab.com", - } - } - - /// Icône Nerd Font du fournisseur. - fn icon(&self) -> char { - match self { - Provider::GitHub => '\u{f408}', - Provider::GitLab => '\u{f296}', - } - } - - /// Icône suivie du libellé, pour l'affichage. - fn icon_label(&self) -> String { - format!("{} {}", self.icon(), self.label()) - } -} - -/// Nécessaire pour le widget `pick_list` d'Iced. -impl std::fmt::Display for Provider { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(self.label()) - } -} - -// --------------------------------------------------------------------------- -// Dépôt distant -// --------------------------------------------------------------------------- - -/// Un dépôt trouvé via la recherche distante. -#[derive(Debug, Clone)] -pub struct RemoteRepo { - pub name: String, - pub url: String, -} - -/// Nécessaire pour le widget `pick_list` — affiche le nom du dépôt. -impl std::fmt::Display for RemoteRepo { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.name) - } -} - -/// Comparaison par nom pour la sélection dans `pick_list`. -impl PartialEq for RemoteRepo { - fn eq(&self, other: &Self) -> bool { - self.name == other.name && self.url == other.url - } -} - -impl Eq for RemoteRepo {} - -// --------------------------------------------------------------------------- -// Messages Iced -// --------------------------------------------------------------------------- - -/// Messages émis par le panneau de clonage. -#[derive(Debug, Clone)] -pub enum Message { - /// Le fournisseur sélectionné a changé. - ProviderSelected(Provider), - /// Le texte de recherche a changé. - QueryChanged(String), - /// L'URL du dépôt a changé. - UrlChanged(String), - /// Le chemin de destination a changé. - DestinationChanged(String), - /// Lancer la recherche de dépôts. - Search, - /// Résultat de la recherche asynchrone, avec la version de la requête. - SearchResult(u32, Result, AppError>), - /// Un dépôt a été sélectionné dans la liste. - SelectRepo(usize), - /// Ouvrir le sélecteur de dossier natif. - ChooseDestination, - /// Résultat du sélecteur de dossier. - ChooseDestinationResult(Option), - /// Démarrer le clonage. - StartClone, - /// Progression du clonage. - CloneProgress(CloneProgress), - /// Résultat du clonage asynchrone. - CloneResult(Result<(), AppError>), - /// Relancer le dernier clonage échoué. - RetryClone, - /// Recherche différée après un délai de saisie. - DebouncedSearch(u32), -} - -// --------------------------------------------------------------------------- -// Panneau de clonage -// --------------------------------------------------------------------------- - -/// Panneau principal de clonage de dépôts. -pub struct ClonePanel { - /// Fournisseur actuellement sélectionné. - provider: Provider, - /// Requête de recherche saisie par l'utilisateur. - repo_query: String, - /// URL du dépôt à cloner. - repo_url: String, - /// Chemin de destination pour le clonage. - destination: String, - /// Répertoire de base pour construire les destinations suggérées. - base_destination: PathBuf, - /// Résultats de la dernière recherche. - search_results: Vec, - /// Index du dépôt sélectionné dans `search_results`. - selected_repo: Option, - /// Message d'état de la recherche affiché à l'utilisateur. - search_status: Option, - /// Progression actuelle du clonage. - progress: Option, - /// Message d'état du clonage affiché à l'utilisateur. - clone_status: Option, - /// Indique si un clonage est en cours. - cloning: bool, - /// Destination active pendant le clonage. - active_destination: Option, - /// Dernière requête de clonage (pour le retry). - last_request: Option, - /// Options réseau courantes. - network: NetworkOptions, - /// Version de la recherche : chaque frappe, recherche ou changement de fournisseur - /// l'incrémente, et seuls le délai et le résultat de la version courante sont appliqués. - search_version: u32, -} - -impl ClonePanel { - /// Crée un nouveau panneau de clonage avec la destination et les options réseau. - pub fn new(destination: String, network: NetworkOptions) -> Self { - Self { - provider: Provider::GitHub, - repo_query: String::new(), - repo_url: String::new(), - base_destination: PathBuf::from(&destination), - destination, - search_results: Vec::new(), - selected_repo: None, - search_status: None, - progress: None, - clone_status: None, - cloning: false, - active_destination: None, - last_request: None, - network, - search_version: 0, - } - } - - /// Vrai si `version` est celle de la recherche en cours, pas d'une requête remplacée. - pub fn is_current_search(&self, version: u32) -> bool { - version == self.search_version - } - - /// Met à jour le chemin de destination par défaut. - pub fn set_default_destination>(&mut self, destination: S) { - self.destination = destination.into(); - self.base_destination = PathBuf::from(self.destination.clone()); - } - - /// Met à jour les préférences réseau. - pub fn set_network_preferences(&mut self, network: NetworkOptions) { - self.network = network; - } - - /// Traite un message et renvoie une tâche Iced plus un éventuel chemin cloné. - /// - /// Le `Option` signale au parent qu'un dépôt a été cloné avec succès. - pub fn update( - &mut self, - message: Message, - auth: &AuthManager, - ) -> (Task, Option) { - match message { - Message::ProviderSelected(provider) => { - self.provider = provider; - self.search_results.clear(); - self.selected_repo = None; - self.search_status = None; - // Abandonner la recherche en cours sur l'ancien fournisseur. - self.search_version += 1; - (Task::none(), None) - } - - Message::QueryChanged(query) => { - self.repo_query = query; - self.search_status = None; - // Incrémenter la version et programmer une recherche différée (250 ms) - self.search_version += 1; - let version = self.search_version; - let task = Task::perform( - async move { - tokio::time::sleep(std::time::Duration::from_millis(250)).await; - version - }, - Message::DebouncedSearch, - ); - (task, None) - } - - Message::UrlChanged(url) => { - self.repo_url = url; - (Task::none(), None) - } - - Message::DestinationChanged(dest) => { - self.destination = dest; - (Task::none(), None) - } - - Message::Search => (self.start_search(auth), None), - - Message::SearchResult(version, result) => { - self.apply_search_result(version, result); - (Task::none(), None) - } - - Message::SelectRepo(index) => { - if let Some(repo) = self.search_results.get(index).cloned() { - self.selected_repo = Some(index); - self.update_selection(&repo); - } - (Task::none(), None) - } - - Message::ChooseDestination => { - let task = recent::pick_folder(Some(self.destination.clone())) - .map(Message::ChooseDestinationResult); - (task, None) - } - - Message::ChooseDestinationResult(path) => { - if let Some(folder) = path { - self.base_destination = PathBuf::from(&folder); - self.destination = folder; - } - (Task::none(), None) - } - - Message::StartClone => { - let url = self.repo_url.trim().to_string(); - let destination = PathBuf::from(self.destination.trim()); - // Le token est résolu dans la tâche de clonage. - let request = CloneRequest { - url, - destination, - token: None, - network: self.network.clone(), - }; - let task = self.begin_clone(request, auth); - (task, None) - } - - Message::CloneProgress(progress) => { - self.progress = Some(progress); - (Task::none(), None) - } - - Message::CloneResult(result) => { - self.cloning = false; - match result { - Ok(()) => { - self.clone_status = Some("Clonage terminé avec succès".into()); - let cloned_path = self.active_destination.take(); - (Task::none(), cloned_path) - } - Err(err) => { - self.clone_status = Some(err.user_message()); - self.active_destination = None; - (Task::none(), None) - } - } - } - - Message::RetryClone => { - if self.cloning { - return (Task::none(), None); - } - if let Some(request) = self.last_request.clone() { - let task = self.begin_clone(request, auth); - (task, None) - } else { - (Task::none(), None) - } - } - - Message::DebouncedSearch(version) => { - // Ignorer si une frappe ou une recherche plus récente a incrémenté la version - if !self.is_current_search(version) { - return (Task::none(), None); - } - (self.start_search(auth), None) - } - } - } - - /// Lance la recherche pour la requête courante sous une nouvelle version. Le token est - /// résolu dans la tâche : la lecture du trousseau peut bloquer. - fn start_search(&mut self, auth: &AuthManager) -> Task { - let query = self.repo_query.trim().to_string(); - if query.len() < 2 { - return Task::none(); - } - self.search_version += 1; - let version = self.search_version; - let provider = self.provider; - let network = self.network.clone(); - let auth = auth.clone(); - self.search_status = Some("Recherche en cours...".into()); - - Task::perform( - async move { - let host_url = format!("https://{}", provider.host()); - let token = tokio::task::spawn_blocking(move || auth.resolve_for_url(&host_url)) - .await - .ok() - .flatten(); - search_repositories(provider, &query, token.as_deref(), network).await - }, - move |result| Message::SearchResult(version, result), - ) - } - - /// Applique le résultat d'une recherche, sauf s'il répond à une requête remplacée. - fn apply_search_result(&mut self, version: u32, result: Result, AppError>) { - if !self.is_current_search(version) { - return; - } - match result { - Ok(results) => { - let count = results.len(); - self.search_results = results; - self.selected_repo = None; - self.search_status = Some(format!("{count} résultat(s)")); - // Sélectionner automatiquement le premier résultat - if let Some(repo) = self.search_results.first().cloned() { - self.selected_repo = Some(0); - self.update_selection(&repo); - } - } - Err(err) => { - self.search_status = Some(err.user_message()); - } - } - } - - /// Lance le clonage en arrière-plan et renvoie la tâche Iced correspondante. - fn begin_clone(&mut self, request: CloneRequest, auth: &AuthManager) -> Task { - self.last_request = Some(request.clone()); - self.active_destination = Some(request.destination.clone()); - self.progress = None; - self.clone_status = Some("Démarrage du clonage...".into()); - self.cloning = true; - - Task::run( - clone_with_progress(request, auth.clone()), - std::convert::identity, - ) - } - - /// Met à jour l'URL et la destination d'après le dépôt sélectionné. - fn update_selection(&mut self, repo: &RemoteRepo) { - self.repo_url = repo.url.clone(); - if let Some(destination) = self.suggested_destination(&repo.url) { - self.destination = destination; - } - } - - /// Propose un chemin de destination basé sur le nom du dépôt extrait de l'URL. - fn suggested_destination(&self, repo_url: &str) -> Option { - let repo_name = repo_name_from_url(repo_url)?; - let base = if self.base_destination.as_os_str().is_empty() { - PathBuf::from(self.destination.clone()) - } else { - self.base_destination.clone() - }; - Some(base.join(repo_name).display().to_string()) - } - - // ----------------------------------------------------------------------- - // Vue Iced - // ----------------------------------------------------------------------- - - /// Construit l'arbre de widgets du panneau de clonage. - pub fn view<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let title = text("Cloner un dépôt") - .size(theme.typography.title) - .color(theme.palette.text_primary); - - let subtitle = text( - "Choisissez un fournisseur, recherchez un dépôt distant, \ - ou collez une URL pour cloner vers un chemin local.", - ) - .size(theme.typography.body) - .color(theme.palette.text_secondary); - - // --- Cartes de fournisseur --- - let provider_row = self.view_provider_cards(theme); - - // --- Section de recherche --- - let search_section = self.view_search_section(theme); - - // --- URL du dépôt --- - let url_section = self.view_url_section(theme); - - // --- Section de destination --- - let destination_section = self.view_destination_section(theme); - - // --- Barre d'actions --- - let action_bar = self.view_action_bar(theme); - - // --- Progression --- - let progress_section = self.view_progress_section(theme); - - // --- Statut du clonage --- - let status_section: Element<'a, Message> = if let Some(status) = &self.clone_status { - text(status.as_str()) - .size(theme.typography.body) - .color(theme.palette.text_secondary) - .into() - } else { - Space::new(0, 0).into() - }; - - let content = column![ - title, - subtitle, - Space::with_height(12), - provider_row, - Space::with_height(8), - search_section, - Space::with_height(12), - url_section, - Space::with_height(12), - destination_section, - Space::with_height(12), - action_bar, - progress_section, - status_section, - ] - .spacing(4) - .width(Length::Fill); - - container(content).padding(16).width(Length::Fill).into() - } - - /// Affiche les cartes de sélection du fournisseur (GitHub / GitLab). - fn view_provider_cards<'a>(&self, theme: &'a Theme) -> Element<'a, Message> { - let cards: Vec> = [Provider::GitHub, Provider::GitLab] - .iter() - .map(|&provider| { - let is_active = self.provider == provider; - let bg = if is_active { - theme.palette.surface_highlight - } else { - theme.palette.surface - }; - let label = text(provider.icon_label()) - .size(theme.typography.title) - .color(theme.palette.text_primary); - - button( - container(label) - .center_x(Length::Fill) - .center_y(Length::Fill) - .width(140) - .height(80), - ) - .style(move |_theme, status| { - let mut appearance = button::Style { - background: Some(iced::Background::Color(bg)), - border: iced::Border { - color: if is_active { - theme.palette.accent - } else { - theme.palette.accent_weak - }, - width: 1.0, - radius: 8.0.into(), - }, - text_color: theme.palette.text_primary, - ..button::Style::default() - }; - if matches!(status, button::Status::Hovered) { - appearance.background = - Some(iced::Background::Color(theme.palette.surface_highlight)); - } - appearance - }) - .on_press(Message::ProviderSelected(provider)) - .width(140) - .height(80) - .into() - }) - .collect(); - - row(cards).spacing(12).into() - } - - /// Affiche la section de recherche : champ texte + bouton + liste de résultats. - fn view_search_section<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let heading = text("Recherche de dépôts distants") - .size(theme.typography.title) - .color(theme.palette.text_primary); - - let help_text = text(format!( - "Recherchez sur {} GitHub ou {} GitLab sans quitter l'application.", - Provider::GitHub.icon(), - Provider::GitLab.icon(), - )) - .size(theme.typography.body) - .color(theme.palette.text_secondary); - - // Champ de recherche - let query_input = text_input("Rechercher des dépôts", &self.repo_query) - .on_input(Message::QueryChanged) - .width(320); - - // Bouton de recherche — désactivé si la requête est trop courte ou si un clonage est en cours - let search_enabled = self.repo_query.trim().len() >= 2 && !self.cloning; - let search_btn = if search_enabled { - button(text("Rechercher")).on_press(Message::Search) - } else { - button(text("Rechercher")) - }; - - // Statut de la recherche - let status_label: Element<'_, Message> = if let Some(status) = &self.search_status { - text(status.as_str()) - .size(theme.typography.body) - .color(theme.palette.text_secondary) - .into() - } else { - Space::new(0, 0).into() - }; - - let search_row = row![query_input, search_btn, status_label] - .spacing(8) - .align_y(Alignment::Center); - - // Liste déroulante des résultats — mappe la sélection vers SelectRepo(index) - let results_section = self.view_results_pick_list(theme); - - column![ - heading, - help_text, - Space::with_height(6), - search_row, - Space::with_height(8), - results_section - ] - .spacing(2) - .into() - } - - /// Widget pick_list pour les résultats de recherche. - /// - /// On mappe la sélection vers `SelectRepo(index)` en cherchant l'index par nom. - fn view_results_pick_list<'a>(&'a self, _theme: &'a Theme) -> Element<'a, Message> { - let results = self.search_results.as_slice(); - let selected = self.selected_repo.and_then(|idx| results.get(idx)); - - pick_list(results, selected, move |repo: RemoteRepo| { - // Trouver l'index correspondant au dépôt sélectionné - let index = results.iter().position(|r| *r == repo).unwrap_or(0); - Message::SelectRepo(index) - }) - .placeholder("Sélectionnez un dépôt") - .width(520) - .into() - } - - /// Affiche le champ URL du dépôt. - fn view_url_section<'a>(&self, theme: &'a Theme) -> Element<'a, Message> { - let label = text("URL du dépôt") - .size(theme.typography.body) - .color(theme.palette.text_primary); - - let url_input = text_input( - "https://github.com/owner/repo.git ou git@gitlab.com:owner/repo.git", - &self.repo_url, - ) - .on_input(Message::UrlChanged) - .width(520); - - column![label, url_input].spacing(4).into() - } - - /// Affiche la section de destination : champ texte + bouton « Choisir ». - fn view_destination_section<'a>(&self, theme: &'a Theme) -> Element<'a, Message> { - let label = text("Chemin local") - .size(theme.typography.title) - .color(theme.palette.text_primary); - - let dest_input = text_input("Où cloner le dépôt ?", &self.destination) - .on_input(Message::DestinationChanged) - .width(400); - - let choose_btn = button(text("Choisir")).on_press(Message::ChooseDestination); - - let dest_row = row![dest_input, choose_btn] - .spacing(8) - .align_y(Alignment::Center); - - column![label, dest_row].spacing(4).into() - } - - /// Affiche le bouton de clonage, aligné à droite. - fn view_action_bar<'a>(&self, _theme: &'a Theme) -> Element<'a, Message> { - let can_clone = !self.repo_url.trim().is_empty() - && !self.destination.trim().is_empty() - && !self.cloning; - - let clone_btn = if can_clone { - button(text("Cloner le dépôt")).on_press(Message::StartClone) - } else { - button(text("Cloner le dépôt")) - }; - - // Alignement à droite via un espace flexible - row![Space::with_width(Length::Fill), clone_btn] - .width(Length::Fill) - .into() - } - - /// Affiche la barre de progression si un clonage est en cours. - fn view_progress_section<'a>(&self, theme: &'a Theme) -> Element<'a, Message> { - match &self.progress { - Some(progress) => { - let ratio = if progress.total_objects == 0 { - 0.0 - } else { - progress.received_objects as f32 / progress.total_objects as f32 - }; - - let label = text("Progression du clonage") - .size(theme.typography.body) - .color(theme.palette.text_primary); - - let bar = progress_bar(0.0..=1.0, ratio).width(Length::Fill); - - let detail = text(format!( - "Objets {}/{} ({:.1} Ko) — Deltas indexés {}/{}", - progress.received_objects, - progress.total_objects, - progress.received_bytes as f64 / 1024.0, - progress.indexed_deltas, - progress.total_deltas, - )) - .size(theme.typography.body) - .color(theme.palette.text_secondary); - - column![Space::with_height(10), label, bar, detail] - .spacing(4) - .width(Length::Fill) - .into() - } - None => Space::new(0, 0).into(), - } - } -} - -// --------------------------------------------------------------------------- -// Fonctions utilitaires (extraction du nom de dépôt depuis une URL) -// --------------------------------------------------------------------------- - -/// Extrait le nom du dépôt depuis une URL (HTTPS ou SSH). -fn repo_name_from_url(repo_url: &str) -> Option { - let trimmed = repo_url.trim().trim_end_matches('/'); - if let Ok(url) = Url::parse(trimmed) { - if let Some(segment) = url - .path_segments() - .and_then(|mut segments| segments.rfind(|s| !s.is_empty())) - { - let name = segment.trim_end_matches(".git"); - if !name.is_empty() { - return Some(name.to_string()); - } - } - } - - let mut candidate = trimmed; - if let Some(idx) = trimmed.rfind(':') { - candidate = &trimmed[idx + 1..]; - } - - if let Some(idx) = candidate.rfind('/') { - candidate = &candidate[idx + 1..]; - } - - let name = candidate.trim_end_matches(".git"); - if name.is_empty() { - None - } else { - Some(name.to_string()) - } -} - -// --------------------------------------------------------------------------- -// Fonctions réseau — identiques à l'original -// --------------------------------------------------------------------------- - -/// Lance la recherche sur le fournisseur approprié. -async fn search_repositories( - provider: Provider, - query: &str, - token: Option<&str>, - network: NetworkOptions, -) -> Result, AppError> { - match provider { - Provider::GitHub => search_github(query, token, &network).await, - Provider::GitLab => search_gitlab(query, token, &network).await, - } -} - -/// Construit un client HTTP avec les en-têtes nécessaires (auth, proxy, timeout). -/// Le token part en `Authorization: Bearer`, que GitHub et GitLab acceptent pour un token -/// OAuth comme pour un jeton d'accès personnel. -async fn client_with_headers( - token: Option<&str>, - header: Option<(&'static str, &'static str)>, - network: &NetworkOptions, -) -> Result { - let mut headers = HeaderMap::new(); - headers.insert( - USER_AGENT, - HeaderValue::from_str("gitspace-ui/0.1") - .map_err(|err| AppError::Validation(err.to_string()))?, - ); - if let Some(token) = token { - let auth_value = HeaderValue::from_str(&format!("Bearer {token}")) - .map_err(|err| AppError::Validation(err.to_string()))?; - headers.insert(AUTHORIZATION, auth_value); - } - if let Some((key, value)) = header { - headers.insert( - key, - HeaderValue::from_str(value).map_err(|err| AppError::Validation(err.to_string()))?, - ); - } - let mut builder = - Client::builder() - .default_headers(headers) - .timeout(std::time::Duration::from_secs( - network.network_timeout_secs.max(1), - )); - - if !network.http_proxy.is_empty() { - builder = builder.proxy( - reqwest::Proxy::http(&network.http_proxy) - .map_err(|err| AppError::Validation(err.to_string()))?, - ); - } - - if !network.https_proxy.is_empty() { - builder = builder.proxy( - reqwest::Proxy::https(&network.https_proxy) - .map_err(|err| AppError::Validation(err.to_string()))?, - ); - } - - builder.build().map_err(AppError::from) -} - -/// Vérifie que l'URL respecte la politique HTTPS configurée. -fn enforce_https_policy(url: &str, network: &NetworkOptions) -> Result<(), AppError> { - if url.starts_with("https://") && !network.use_https { - return Err(AppError::Validation( - "HTTPS endpoints are disabled in your network settings.".to_string(), - )); - } - - if url.starts_with("http://") && network.use_https { - return Err(AppError::Validation( - "HTTP requests are blocked. Enable HTTP in network settings or use HTTPS.".to_string(), - )); - } - - Ok(()) -} - -// --- Structures de désérialisation GitHub --- - -#[derive(Debug, Deserialize)] -struct GithubRepoOwner { - login: String, -} - -#[derive(Debug, Deserialize)] -struct GithubRepoItem { - full_name: String, - html_url: String, - owner: GithubRepoOwner, -} - -#[derive(Debug, Deserialize)] -struct GithubUserProfile { - login: String, -} - -/// Recherche les dépôts d'un compte GitHub (publics + privés si authentifié). -async fn search_github( - query: &str, - token: Option<&str>, - network: &NetworkOptions, -) -> Result, AppError> { - let account = query.trim(); - if account.is_empty() { - return Ok(Vec::new()); - } - - let client = client_with_headers(token, None, network).await?; - let mut unique = HashSet::new(); - - let public_user_url = github_api_url(&["users", account, "repos"]); - let public_org_url = github_api_url(&["orgs", account, "repos"]); - let mut parts = vec![ - fetch_github_repos(&client, &public_user_url, &[("type", "public")], network).await, - fetch_github_repos(&client, &public_org_url, &[("type", "public")], network).await, - ]; - if token.is_some() { - parts.push(fetch_github_private_repos(&client, account, network).await); - } - // Une requête refusée (limite de débit, réseau) ne masque pas les résultats des autres. - let repositories = merge_partial_results(parts)?; - - let results = repositories - .into_iter() - .filter(|repo| unique.insert(repo.full_name.clone())) - .map(|item| RemoteRepo { - name: item.full_name, - url: item.html_url, - }) - .collect(); - - Ok(results) -} - -// --- Structure de désérialisation GitLab --- - -#[derive(Debug, Deserialize)] -struct GitlabProject { - name_with_namespace: String, - http_url_to_repo: String, -} - -/// Recherche les projets GitLab correspondant à la requête. -async fn search_gitlab( - query: &str, - token: Option<&str>, - network: &NetworkOptions, -) -> Result, AppError> { - let base_url = "https://gitlab.com/api/v4/projects"; - enforce_https_policy(base_url, network)?; - let client = client_with_headers(token, Some(("Accept", "application/json")), network).await?; - - let mut all_projects = Vec::new(); - let per_page = 100; - - for page in 1..=10 { - let response = client - .get(base_url) - .query(&[ - ("search", query), - ("per_page", &per_page.to_string()), - ("page", &page.to_string()), - ("simple", "true"), - ]) - .send() - .await - .map_err(AppError::from)?; - - if !response.status().is_success() { - if page == 1 { - // error_for_status() renvoie Err quand le statut n'est pas un succès - match response.error_for_status() { - Err(err) => return Err(AppError::from(err)), - Ok(_) => { - return Err(AppError::Network( - "Réponse inattendue du serveur GitLab".to_string(), - )) - } - } - } - break; - } - - let projects: Vec = response.json().await.map_err(AppError::from)?; - let count = projects.len(); - all_projects.extend(projects); - - if count < per_page { - break; - } - } - - Ok(all_projects - .into_iter() - .map(|project| RemoteRepo { - name: project.name_with_namespace, - url: project.http_url_to_repo, - }) - .collect()) -} - -/// Dépôts privés du compte authentifié quand il s'agit de `account`, vide sinon. -async fn fetch_github_private_repos( - client: &Client, - account: &str, - network: &NetworkOptions, -) -> Result, AppError> { - match fetch_github_login(client, network).await? { - Some(login) if login.eq_ignore_ascii_case(account) => { - let repos = fetch_github_repos( - client, - "https://api.github.com/user/repos", - &[ - ("visibility", "all"), - ("affiliation", "owner,collaborator,organization_member"), - ], - network, - ) - .await?; - Ok(repos - .into_iter() - .filter(|repo| repo.owner.login.eq_ignore_ascii_case(account)) - .collect()) - } - _ => Ok(Vec::new()), - } -} - -/// URL de l'API GitHub dont chaque segment est encodé, pour qu'un nom saisi ne change pas le -/// chemin appelé. -fn github_api_url(segments: &[&str]) -> String { - let mut url = Url::parse("https://api.github.com").expect("static URL"); - url.path_segments_mut() - .expect("https URL has a path") - .extend(segments); - url.into() -} - -/// Réunit les résultats de plusieurs requêtes : les réponses obtenues sont gardées, et la -/// première erreur n'est renvoyée que si aucune requête n'a abouti. -fn merge_partial_results( - parts: impl IntoIterator, AppError>>, -) -> Result, AppError> { - let mut items = Vec::new(); - let mut first_error = None; - let mut any_ok = false; - for part in parts { - match part { - Ok(part) => { - any_ok = true; - items.extend(part); - } - Err(err) => { - first_error.get_or_insert(err); - } - } - } - match first_error { - Some(err) if !any_ok => Err(err), - _ => Ok(items), - } -} - -/// Récupère le login de l'utilisateur GitHub authentifié. -async fn fetch_github_login( - client: &Client, - network: &NetworkOptions, -) -> Result, AppError> { - let url = "https://api.github.com/user"; - enforce_https_policy(url, network)?; - let response = client.get(url).send().await.map_err(AppError::from)?; - if response.status() == StatusCode::UNAUTHORIZED { - return Ok(None); - } - let profile: GithubUserProfile = response - .error_for_status()? - .json() - .await - .map_err(AppError::from)?; - Ok(Some(profile.login)) -} - -/// Récupère les dépôts GitHub depuis une URL paginée. -async fn fetch_github_repos( - client: &Client, - base_url: &str, - params: &[(&str, &str)], - network: &NetworkOptions, -) -> Result, AppError> { - enforce_https_policy(base_url, network)?; - let mut all_repos = Vec::new(); - let per_page = 100; - - for page in 1..=10 { - let mut query_params: Vec<(&str, String)> = - params.iter().map(|(k, v)| (*k, (*v).to_string())).collect(); - query_params.push(("per_page", per_page.to_string())); - query_params.push(("page", page.to_string())); - - let response = client - .get(base_url) - .query(&query_params) - .send() - .await - .map_err(AppError::from)?; - - if response.status() == StatusCode::NOT_FOUND { - break; - } - - let response = response.error_for_status().map_err(AppError::from)?; - let mut repos: Vec = response.json().await.map_err(AppError::from)?; - let count = repos.len(); - all_repos.append(&mut repos); - - if count < per_page { - break; - } - } - - Ok(all_repos) -} - -/// Clone bloquant lancé dans un thread dédié, qui envoie sa progression puis son résultat. -/// Le token de l'URL est résolu dans ce thread quand la requête n'en porte pas. -fn clone_with_progress( - mut request: CloneRequest, - auth: AuthManager, -) -> impl Stream { - iced::stream::channel(16, move |mut output| async move { - let mut progress = output.clone(); - let result = tokio::task::spawn_blocking(move || { - if request.token.is_none() { - request.token = auth.resolve_for_url(&request.url); - } - // shortcut: an update is dropped when the UI is 16 behind; the next one replaces it. - clone_repository(request, move |update| { - let _ = progress.try_send(Message::CloneProgress(update)); - }) - }) - .await - .unwrap_or_else(|err| { - Err(AppError::Network(format!( - "Tâche de clonage interrompue : {err}" - ))) - }); - let _ = output.send(Message::CloneResult(result)).await; - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn repo(name: &str) -> RemoteRepo { - RemoteRepo { - name: name.to_string(), - url: format!("https://example.com/{name}.git"), - } - } - - #[test] - fn a_result_for_a_replaced_search_is_dropped() { - let mut panel = ClonePanel::new(String::new(), NetworkOptions::default()); - panel.search_version = 3; - - panel.apply_search_result(2, Ok(vec![repo("old")])); - assert!(panel.search_results.is_empty()); - assert_eq!(panel.search_status, None); - - panel.apply_search_result(3, Ok(vec![repo("new")])); - assert_eq!(panel.search_results, vec![repo("new")]); - assert_eq!(panel.selected_repo, Some(0)); - } - - #[test] - fn partial_results_survive_a_failed_request() { - let merged = merge_partial_results([ - Ok(vec![1, 2]), - Err(AppError::Network("rate limited".into())), - Ok(vec![3]), - ]); - assert_eq!(merged.unwrap(), vec![1, 2, 3]); - } - - #[test] - fn the_first_error_is_returned_when_every_request_fails() { - let merged: Result, _> = merge_partial_results([ - Err(AppError::Network("first".into())), - Err(AppError::Network("second".into())), - ]); - assert!(matches!(merged, Err(AppError::Network(msg)) if msg == "first")); - } - - #[test] - fn github_api_url_encodes_the_account() { - assert_eq!( - github_api_url(&["users", "a/b c?x", "repos"]), - "https://api.github.com/users/a%2Fb%20c%3Fx/repos" - ); - } -} diff --git a/src/ui/context.rs b/src/ui/context.rs index b3c60ca..39b545b 100644 --- a/src/ui/context.rs +++ b/src/ui/context.rs @@ -1,8 +1,34 @@ use std::path::Path; use std::sync::Arc; +use iced::Task; + use crate::git::repo_cache::with_cached_repo; +/// Runs `job` for the repository at `repo` on the blocking thread pool and passes its result, +/// with the repository path, to `done`. Panels compare that path with their current repository +/// and drop results that arrive after a switch. Shared by the changes, branch and history panels. +pub(crate) fn git_task( + repo: Arc, + job: impl FnOnce(&str) -> Result + Send + 'static, + done: impl Fn(Arc, Result) -> M + Send + 'static, +) -> Task +where + M: Send + 'static, + T: Send + 'static, +{ + Task::perform( + async move { + let path = Arc::clone(&repo); + let result = tokio::task::spawn_blocking(move || job(&path)) + .await + .unwrap_or_else(|err| Err(err.to_string())); + (repo, result) + }, + move |(repo, result)| done(repo, result), + ) +} + /// Contexte d'un depot git actuellement ouvert : son chemin et son nom. /// Le path utilise Arc pour eviter les clones couteux. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/src/ui/diff_view.rs b/src/ui/diff_view.rs new file mode 100644 index 0000000..eb4978d --- /dev/null +++ b/src/ui/diff_view.rs @@ -0,0 +1,259 @@ +//! A patch drawn with line numbers: hunk headers on a tinted band, added lines on +//! `success_bg`, removed lines on `error_bg`. Changes and History share it. + +use colony_ui::theme::Palette; +use colony_ui::Typography; +use iced::widget::{column, container, row, scrollable, text, Column}; +use iced::{Color, Element, Length}; + +use crate::i18n::t; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LineKind { + Context, + Added, + Removed, + /// "\ No newline at end of file". + Note, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DiffLine { + pub kind: LineKind, + /// The line number before the change; `None` for an added line. + pub old: Option, + /// The line number after the change; `None` for a removed line. + pub new: Option, + /// The patch line, with its `+`, `-` or space prefix. + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Hunk { + /// The `@@ -a,b +c,d @@ …` line. + pub header: String, + pub lines: Vec, +} + +/// What a diff pane shows. +pub enum Diff { + Loading, + Hunks { + hunks: Vec, + truncated: bool, + }, + /// No text to show: a binary file, or a file with no line changes. + Empty, + Failed(String), +} + +impl Diff { + /// The pane for a loaded `(patch, truncated)`; `None` means the file has no patch. + pub fn loaded(result: Result, String>) -> Self { + match result { + Ok(Some((patch, truncated))) => { + let hunks = parse_hunks(&patch); + if hunks.is_empty() { + Diff::Empty + } else { + Diff::Hunks { hunks, truncated } + } + } + Ok(None) => Diff::Empty, + Err(err) => Diff::Failed(err), + } + } +} + +/// The diff pane filling its parent; `idle` is shown when no file is selected. +pub fn pane<'a, M: 'a>(diff: Option<&'a Diff>, idle: &str) -> Element<'a, M> { + let typo = Typography::current(); + let note = |label: String| -> Element<'a, M> { + container( + text(label) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + ) + .padding([12, 16]) + .width(Length::Fill) + .height(Length::Fill) + .into() + }; + match diff { + None => note(idle.to_string()), + Some(Diff::Loading) => note(t("changes_loading").to_string()), + Some(Diff::Empty) => note(t("changes_no_diff").to_string()), + Some(Diff::Failed(err)) => note(err.clone()), + Some(Diff::Hunks { hunks, truncated }) => { + let hunks = view(hunks); + if *truncated { + column![ + hunks, + container( + text(t("changes_truncated")) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::WARNING()), + ) + .padding([4, 16]), + ] + .height(Length::Fill) + .into() + } else { + hunks + } + } + } +} + +/// Splits a unified patch into hunks and numbers their lines. File headers before the +/// first hunk, and any line that is not part of a hunk, are left out. +pub fn parse_hunks(patch: &str) -> Vec { + let mut hunks: Vec = Vec::new(); + let (mut old, mut new) = (0, 0); + for line in patch.lines() { + if line.starts_with("@@") { + (old, new) = hunk_starts(line); + hunks.push(Hunk { + header: line.to_string(), + lines: Vec::new(), + }); + continue; + } + let Some(hunk) = hunks.last_mut() else { + continue; + }; + let (kind, old_number, new_number) = match line.chars().next() { + Some(' ') => (LineKind::Context, Some(old), Some(new)), + Some('+') => (LineKind::Added, None, Some(new)), + Some('-') => (LineKind::Removed, Some(old), None), + Some('\\') => (LineKind::Note, None, None), + _ => continue, + }; + old += u32::from(old_number.is_some()); + new += u32::from(new_number.is_some()); + hunk.lines.push(DiffLine { + kind, + old: old_number, + new: new_number, + text: line.to_string(), + }); + } + hunks +} + +/// The first old and new line numbers of a `@@ -a,b +c,d @@` header. +fn hunk_starts(header: &str) -> (u32, u32) { + let start = |sign: char| { + header + .split_whitespace() + .find_map(|part| part.strip_prefix(sign)) + .and_then(|range| range.split(',').next()) + .and_then(|number| number.parse().ok()) + .unwrap_or(1) + }; + (start('-'), start('+')) +} + +/// The hunks in a vertical scroll area that fills its parent. +pub fn view<'a, M: 'a>(hunks: &'a [Hunk]) -> Element<'a, M> { + let typo = Typography::current(); + let size = typo.sz(12); + let mut lines = Column::new().padding([8, 0]); + for hunk in hunks { + lines = lines.push( + container( + text(hunk.header.as_str()) + .size(size) + .font(typo.regular) + .color(Palette::ACCENT()), + ) + .width(Length::Fill) + .padding([2, 16]) + .style(|_| band(Palette::ACCENT().scale_alpha(0.12))), + ); + for line in &hunk.lines { + let (background, color) = match line.kind { + LineKind::Added => (Palette::SUCCESS_BG(), Palette::SUCCESS()), + LineKind::Removed => (Palette::ERROR_BG(), Palette::ERROR()), + LineKind::Context => (Color::TRANSPARENT, Palette::TEXT_DIM()), + LineKind::Note => (Color::TRANSPARENT, Palette::TEXT_DIMMEST()), + }; + // One column, as in the mockup: the new number, or the old one for a removal. + let number = line + .new + .or(line.old) + .map(|n| n.to_string()) + .unwrap_or_default(); + lines = lines.push( + container( + row![ + text(number) + .size(size) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .width(Length::Fixed(42.0)) + .align_x(iced::alignment::Horizontal::Right), + text(line.text.as_str()) + .size(size) + .font(typo.regular) + .color(color), + ] + .spacing(8), + ) + .width(Length::Fill) + .padding([0, 16]) + .style(move |_| band(background)), + ); + } + } + scrollable(lines) + .width(Length::Fill) + .height(Length::Fill) + .into() +} + +fn band(background: Color) -> container::Style { + container::Style { + background: Some(background.into()), + ..Default::default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_hunks_numbers_lines() { + let patch = "diff --git a/x b/x\nindex 1..2 100644\n--- a/x\n+++ b/x\n\ + @@ -40,4 +40,5 @@ fn set_active_theme\n a\n-b\n+c\n+d\n e\n\ + \\ No newline at end of file\n@@ -90 +91,2 @@\n z\n+y\n"; + let hunks = parse_hunks(patch); + assert_eq!(hunks.len(), 2); + assert_eq!(hunks[0].header, "@@ -40,4 +40,5 @@ fn set_active_theme"); + + let numbers: Vec<_> = hunks[0] + .lines + .iter() + .map(|line| (line.kind, line.old, line.new, line.text.as_str())) + .collect(); + assert_eq!( + numbers, + [ + (LineKind::Context, Some(40), Some(40), " a"), + (LineKind::Removed, Some(41), None, "-b"), + (LineKind::Added, None, Some(41), "+c"), + (LineKind::Added, None, Some(42), "+d"), + (LineKind::Context, Some(42), Some(43), " e"), + (LineKind::Note, None, None, "\\ No newline at end of file"), + ] + ); + // A range without a count still gives the start line. + assert_eq!(hunks[1].lines[0].old, Some(90)); + assert_eq!(hunks[1].lines[1].new, Some(92)); + // No hunk: a binary file, or the truncation marker on its own. + assert!(parse_hunks("Binary file change\n").is_empty()); + } +} diff --git a/src/ui/fonts.rs b/src/ui/fonts.rs deleted file mode 100644 index 58eddcf..0000000 --- a/src/ui/fonts.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! JetBrains Mono Nerd Font, embedded in the binary. -//! -//! Only the Regular weight is bundled: no widget asks for another weight or style. - -/// Regular weight, registered with iced at startup. -pub const FONT_REGULAR: &[u8] = - include_bytes!("../../assets/JetBrainsMonoNerdFont/JetBrainsMonoNerdFont-Regular.ttf"); - -/// Default font of the interface. It is monospaced, so diffs and codes use it too. -pub const DEFAULT_FONT: iced::Font = iced::Font::with_name("JetBrainsMono Nerd Font"); diff --git a/src/ui/history.rs b/src/ui/history.rs index 077a255..64abd14 100644 --- a/src/ui/history.rs +++ b/src/ui/history.rs @@ -1,682 +1,994 @@ -// Panneau d'historique des commits pour l'interface Iced. -// Affiche la liste des commits avec filtres, et un volet de details -// avec les fichiers modifies et les diffs expansibles. -// Les lectures git tournent en tache de fond ; view() ne lit que l'etat du panneau. +//! The History tab: the commit list with a filter, a branch picker, ref badges and merge +//! markers, then the selected commit's detail, its changed files and the diff of one file. +//! Git reads run in background tasks; `view` only reads the panel's state. -use std::collections::{HashMap, HashSet}; use std::sync::Arc; -use chrono::{Datelike, NaiveDate, TimeZone, Utc}; -use iced::widget::{ - button, column, container, horizontal_rule, pick_list, row, scrollable, text, text_input, Space, +use chrono::{Local, TimeZone}; +use colony_ui::theme::{accent_key_to_color, contrast_on, Palette, ACCENT_OVERRIDES}; +use colony_ui::{fonts, Typography}; +use git2::{Oid, Repository}; +use iced::widget::text::Wrapping; +use iced::widget::{button, column, container, pick_list, row, scrollable, stack, text}; +use iced::widget::{text_input, Column, Space}; +use iced::{Alignment, Border, Element, Length, Task}; + +use crate::git::branch::{checkout_branch, create_branch}; +use crate::git::diff::{commit_diff_file, commit_diff_summaries, FileDiffSummary}; +use crate::git::log::{ + list_local_branches, read_commit_log, CommitFilter, CommitInfo, RefKind, RefLabel, }; -use iced::{Element, Length, Task}; - -use crate::ui::theme::Theme; - -use crate::git::{ - diff::{commit_diff_file, commit_diff_summaries, FileDiff, FileDiffSummary}, - log::{list_local_branches, read_commit_log, CommitFilter, CommitInfo}, -}; -use crate::ui::context::RepoContext; -use crate::ui::stage::git_task; - -/// Nombre maximal de commits charges au total. +use crate::i18n::{t, tf}; +use crate::ui::changes::{field, horizontal_divider, item, question, vertical_divider}; +use crate::ui::context::{git_task, RepoContext}; +use crate::ui::diff_view::{self, Diff}; +use crate::ui::widgets::button as gs_button; +use crate::ui::widgets::chip::{chip, Tone}; +use crate::ui::widgets::ellipsis::ellipsis; +use crate::ui::widgets::menu::{self, Entry}; +use crate::ui::widgets::toast::Toast; + +/// Most commits listed, after every "Load more". const MAX_COMMITS: usize = 200; - -/// Nombre de commits charges par page (chargement incremental). +/// Commits added by each "Load more". const PAGE_SIZE: usize = 50; - -// --------------------------------------------------------------------------- -// Filtres -// --------------------------------------------------------------------------- - -/// Criteres de filtrage de l'historique de commits. -#[derive(Default, Clone)] -pub struct HistoryFilters { - pub branch: String, - pub author: String, - pub search: String, - pub since: String, - pub until: String, -} - -impl HistoryFilters { - /// Filtre git correspondant aux champs saisis ; un champ vide ne filtre pas. - fn to_commit_filter(&self) -> CommitFilter { - let non_empty = |value: &str| (!value.is_empty()).then(|| value.to_string()); - CommitFilter { - branch: non_empty(&self.branch), - author: non_empty(&self.author), - search: non_empty(&self.search), - since: parse_date(&self.since), - until: parse_date(&self.until), - } - } -} - -/// Une page de commits et les branches locales proposees dans le filtre. +/// Width of the commit list. +const LIST_WIDTH: f32 = 360.0; +/// Characters of a short hash, as in `CommitInfo::short_id`. +const SHORT_HASH: usize = 7; +const MORE_GLYPH: &str = "\u{f141}"; +const COPY_GLYPH: &str = "\u{f0c5}"; + +/// One page of commits and the local branches offered by the branch picker. #[derive(Debug, Clone)] pub struct LogPage { commits: Vec, branches: Vec, - /// Nombre de commits demandes : une page pleine signale qu'il en reste. + /// The number asked for: a full page means more commits may match. limit: usize, } -// --------------------------------------------------------------------------- -// Messages -// --------------------------------------------------------------------------- +/// What the detail pane needs besides the commit itself. +#[derive(Debug, Clone)] +pub struct Detail { + files: Vec, + parents: Vec, +} + +/// A git action from the commit's "⋯" menu that ended. +#[derive(Debug, Clone)] +pub enum Done { + /// The short hash now checked out. + Checkout(String), + /// The name of the new branch. + Branch(String), +} + +/// An entry of the branch picker. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BranchChoice { + /// Follows HEAD, including a detached one. + Head, + Branch(String), +} + +impl std::fmt::Display for BranchChoice { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Head => f.write_str(t("history_current_branch")), + Self::Branch(name) => f.write_str(name), + } + } +} -/// Actions possibles depuis le panneau d'historique. #[derive(Debug, Clone)] pub enum Message { - /// Filtre de branche modifie. - BranchFilterChanged(String), - /// Branche locale choisie dans la liste (appliquee tout de suite). - BranchPicked(String), - /// Filtre d'auteur modifie. - AuthorChanged(String), - /// Recherche textuelle modifiee. - SearchChanged(String), - /// Application differee de la recherche apres debounce (version). - ApplyDebouncedSearch(u32), - /// Date de debut modifiee (format YYYY-MM-DD). - SinceChanged(String), - /// Date de fin modifiee (format YYYY-MM-DD). - UntilChanged(String), - /// Appliquer les filtres et recharger les commits. - ApplyFilters, - /// Selectionner un commit par son identifiant. - SelectCommit(String), - /// Etendre ou charger le diff d'un fichier. - ExpandFile(String), - /// Charger la page suivante de commits. + Filter(String), + /// Applies the filter typed 250 ms ago, unless a later key press replaced it. + ApplyFilter(u32), + BranchPicked(BranchChoice), + Select(String), + SelectFile(String), LoadMore, - /// Resultat d'une lecture du journal (numero de requete, page). + /// Opens or closes the detail's "⋯" menu. + CommitMenu(bool), + CopyHash(String), + /// Asks to confirm checking out the selected commit, or closes the question. + ConfirmCheckout(bool), + Checkout, + /// Opens the branch name field (`Some`), types in it, or closes it (`None`). + BranchName(Option), + CreateBranch, + /// A read of the log, numbered so that only the latest one is shown. Loaded(Arc, u64, Result), - /// Fichiers modifies d'un commit (identifiant, resumes). - SummariesLoaded(Arc, String, Result, String>), - /// Patch d'un fichier (identifiant du commit, chemin, patch). - PatchLoaded(Arc, String, String, FileDiff), + DetailLoaded(Arc, String, Result), + /// The patch of `(commit, file)`. + DiffLoaded( + Arc, + (String, String), + Result, String>, + ), + /// The key names the failure title. + ActionDone(Arc, &'static str, Result), +} + +/// A commit as the list draws it. +#[derive(Debug, Clone, PartialEq)] +pub struct CommitRow { + pub short_id: String, + pub summary: String, + pub author: String, + pub initials: String, + /// A key of `colony_ui::theme::ACCENT_OVERRIDES`. + pub avatar_accent: &'static str, + pub when: String, + pub refs: Vec, + pub is_merge: bool, } -// --------------------------------------------------------------------------- -// Panneau principal -// --------------------------------------------------------------------------- +impl CommitRow { + /// Built when drawn, so the relative date and its language are never stale. + fn new(commit: &CommitInfo, now: i64) -> Self { + Self { + short_id: commit.short_id.clone(), + summary: commit.summary.clone(), + author: commit.author.clone(), + initials: initials(&commit.author), + avatar_accent: avatar_accent(commit.email.as_deref().unwrap_or(&commit.author)), + when: relative_time(commit.time.seconds(), now), + refs: commit.refs.clone(), + is_merge: commit.parent_count > 1, + } + } +} -/// Panneau d'historique affichant les commits et leurs details. +#[derive(Default)] pub struct HistoryPanel { repo: Option>, - filters: HistoryFilters, - /// Filtre de la derniere recherche lancee, reutilise par la pagination. + filter: String, + /// The branch shown; `None` follows HEAD. + branch: Option, + /// The filter of the last read, reused by "Load more". applied: CommitFilter, - /// Branches locales proposees dans le filtre de branche. branches: Vec, commits: Vec, - selected_commit: Option, - /// Resumes legers des fichiers modifies (charges a la selection du commit). - diff_summaries: Vec, - /// Diffs complets charges a la demande (cle = chemin du fichier). - loaded_patches: HashMap, - /// Ensemble des fichiers dont le diff est actuellement affiche. - expanded_files: HashSet, error: Option, - diff_error: Option, - /// Compteur de version pour le debounce de la recherche. - search_debounce_version: u32, - /// Numero de la derniere lecture du journal ; les reponses plus anciennes sont ignorees. - request: u64, loading: bool, - /// Indique s'il reste des commits a charger. has_more: bool, + /// Number of the last log read; older replies are dropped. + request: u64, + filter_version: u32, + selected: Option, + detail: Option, + detail_error: Option, + selected_file: Option, + diff: Option, + commit_menu: bool, + confirm_checkout: bool, + branch_name: Option, + busy: bool, } impl HistoryPanel { - /// Cree un nouveau panneau d'historique. - pub fn new() -> Self { - Self { - repo: None, - filters: HistoryFilters::default(), - applied: CommitFilter::default(), - branches: Vec::new(), - commits: Vec::new(), - selected_commit: None, - diff_summaries: Vec::new(), - loaded_patches: HashMap::new(), - expanded_files: HashSet::new(), - error: None, - diff_error: None, - search_debounce_version: 0, - request: 0, - loading: false, - has_more: false, - } - } - - /// Oublie le depot precedent et charge l'historique de `repo` en tache de fond. - /// Les filtres saisis sont conserves, sauf la branche quand on change de depot. + /// Forgets the previous repository and reads the history of `repo` in the background. + /// The filter text stays; the branch is cleared when the repository changes. pub fn load(&mut self, repo: &RepoContext) -> Task { - let mut filters = std::mem::take(&mut self.filters); - if self.repo.is_some() && !self.is_current(repo.path()) { - filters.branch.clear(); - } + let same = self.is_current(repo.path()); *self = Self { repo: Some(repo.path_arc()), - filters, - // Keep request numbers growing so a reply from before the reset is ignored. + filter: std::mem::take(&mut self.filter), + branch: if same { self.branch.take() } else { None }, + // Keep request numbers growing so a reply from before the reset is dropped. request: self.request, - ..Self::new() + ..Self::default() }; self.refresh() } - /// Affiche l'historique de `branch` dans `repo`. + /// Shows the history of `branch` in `repo`. pub fn show_branch(&mut self, branch: String, repo: &RepoContext) -> Task { if !self.is_current(repo.path()) { // Only the reset is wanted: a task that is never run never starts its job. let _ = self.load(repo); } - self.filters.branch = branch; + self.branch = Some(branch); self.refresh() } - // ----------------------------------------------------------------------- - // Mise a jour (logique) - // ----------------------------------------------------------------------- - - /// Traite un message et effectue les operations correspondantes. - pub fn update(&mut self, message: Message, _repo: Option<&RepoContext>) -> Task { + /// Handles a message; the toast, if any, is for the application to show. + pub fn update(&mut self, message: Message) -> (Task, Option) { match message { - Message::BranchFilterChanged(value) => { - self.filters.branch = value; - } - - Message::BranchPicked(value) => { - self.filters.branch = value; - return self.refresh(); - } - - Message::AuthorChanged(value) => { - self.filters.author = value; - } - - Message::SearchChanged(value) => { - // Stocker le texte immediatement pour l'affichage du champ - self.filters.search = value; - // Incrementer la version pour invalider les debounces precedents - self.search_debounce_version += 1; - let version = self.search_debounce_version; - // Retourner une tache qui attend 250ms puis envoie ApplyDebouncedSearch - return Task::perform( - async move { - tokio::time::sleep(std::time::Duration::from_millis(250)).await; - }, - move |_| Message::ApplyDebouncedSearch(version), + Message::Filter(value) => { + self.filter = value; + self.filter_version += 1; + let version = self.filter_version; + let wait = Task::perform( + tokio::time::sleep(std::time::Duration::from_millis(250)), + move |_| Message::ApplyFilter(version), ); + return (wait, None); } - - Message::SinceChanged(value) => { - self.filters.since = value; - } - - Message::UntilChanged(value) => { - self.filters.until = value; - } - - Message::ApplyDebouncedSearch(version) => { - // Appliquer uniquement si aucune frappe plus recente n'a eu lieu - if version == self.search_debounce_version { - return self.refresh(); + Message::ApplyFilter(version) => { + if version == self.filter_version { + return (self.refresh(), None); } } - - Message::ApplyFilters => { - return self.refresh(); - } - - Message::SelectCommit(id) => { - self.selected_commit = Some(id); - return self.load_diff(); + Message::BranchPicked(choice) => { + self.branch = match choice { + BranchChoice::Head => None, + BranchChoice::Branch(name) => Some(name), + }; + return (self.refresh(), None); } - + Message::Select(id) => return (self.select(id), None), + Message::SelectFile(path) => return (self.select_file(path), None), Message::LoadMore => { - // La page suivante relit les premiers commits correspondants, plus une page + // The next page reads the first matching commits again, plus one page. if self.has_more && !self.loading { let limit = (self.commits.len() + PAGE_SIZE).min(MAX_COMMITS); - return self.fetch(limit); + return (self.fetch(limit), None); } } - - Message::ExpandFile(path) => { - // Basculer l'etat d'expansion du fichier - if self.expanded_files.remove(&path) { - return Task::none(); + Message::CommitMenu(open) => self.commit_menu = open, + Message::CopyHash(id) => { + self.commit_menu = false; + return (iced::clipboard::write(id), None); + } + Message::ConfirmCheckout(open) => { + self.commit_menu = false; + self.branch_name = None; + self.confirm_checkout = open; + } + Message::Checkout => { + self.confirm_checkout = false; + if let Some(id) = self.selected.clone() { + let task = self.run("history_checkout_failed", move |repo| { + checkout_branch(repo, &id) + .map(|()| Done::Checkout(short_hash(&id).to_string())) + .map_err(|err| err.to_string()) + }); + return (task, None); } - self.expanded_files.insert(path.clone()); - if !self.loaded_patches.contains_key(&path) { - return self.load_file_patch(path); + } + Message::BranchName(name) => { + self.commit_menu = false; + self.confirm_checkout = false; + self.branch_name = name; + } + Message::CreateBranch => { + let name = self.branch_name.as_deref().unwrap_or_default().trim(); + if let (false, Some(id)) = (name.is_empty(), self.selected.clone()) { + let name = name.to_string(); + self.branch_name = None; + let task = self.run("history_create_failed", move |repo| { + create_branch(repo, &name, Some(&id)) + .map(|()| Done::Branch(name)) + .map_err(|err| err.to_string()) + }); + return (task, None); } } - - // -- Resultats des taches de fond -- Message::Loaded(repo, request, result) => { - if !self.is_current(&repo) || request != self.request { - return Task::none(); - } - self.loading = false; - match result { - Ok(page) => { - self.has_more = - page.commits.len() == page.limit && page.limit < MAX_COMMITS; - self.commits = page.commits; - self.branches = page.branches; - } - Err(err) => { - self.commits.clear(); - self.has_more = false; - self.error = Some(format!("Echec de lecture des commits : {err}")); - } + if self.is_current(&repo) && request == self.request { + return (self.apply_page(result), None); } } - - Message::SummariesLoaded(repo, id, result) => { - if self.is_current(&repo) && self.selected_commit.as_ref() == Some(&id) { + Message::DetailLoaded(repo, id, result) => { + if self.is_current(&repo) && self.selected.as_ref() == Some(&id) { match result { - Ok(summaries) => self.diff_summaries = summaries, - Err(err) => { - self.diff_error = Some(format!("Echec du chargement du diff : {err}")); + Ok(detail) => { + let first = detail.files.first().map(|file| file.path.clone()); + self.detail = Some(detail); + if let Some(path) = first { + return (self.select_file(path), None); + } } + Err(err) => self.detail_error = Some(err), } } } - - Message::PatchLoaded(repo, id, path, diff) => { - if self.is_current(&repo) && self.selected_commit.as_ref() == Some(&id) { - self.loaded_patches.insert(path, diff); + Message::DiffLoaded(repo, key, result) => { + if self.is_current(&repo) + && self.selected.as_ref() == Some(&key.0) + && self.selected_file.as_ref() == Some(&key.1) + { + self.diff = Some(Diff::loaded(result)); + } + } + Message::ActionDone(repo, failed, result) => { + if self.is_current(&repo) { + self.busy = false; + // On success the application reloads every panel, this one included. + let toast = match result { + Ok(Done::Checkout(hash)) => { + Toast::success(tf("history_checked_out", &[("hash", &hash)])) + } + Ok(Done::Branch(name)) => { + Toast::success(tf("history_branch_created", &[("name", &name)])) + } + Err(err) => Toast::error(t(failed), err), + }; + return (Task::none(), Some(toast)); } } } - - Task::none() + (Task::none(), None) } - // ----------------------------------------------------------------------- - // Vue (rendu) - // ----------------------------------------------------------------------- - - /// Construit l'arbre de widgets Iced pour le panneau d'historique. - pub fn view<'a>( - &'a self, - _theme: &'a Theme, - repo: Option<&'a RepoContext>, - ) -> Element<'a, Message> { - let mut main_col = column![].spacing(8).padding(8); - - // Titre et description - main_col = main_col - .push(text("Commit history").size(24)) - .push(text("Explore commits, filter by branch or author, and inspect diffs.").size(14)); - - // Sans depot, message d'aide - if repo.is_none() { - main_col = main_col - .push(text("Select or clone a repository to view its commit history.").size(14)); - return main_col.into(); - } - - // Section des filtres - main_col = main_col.push(self.view_filters()); + fn is_current(&self, repo: &str) -> bool { + self.repo.as_deref() == Some(repo) + } - // Erreur globale, sous les filtres pour pouvoir les corriger - if let Some(error) = &self.error { - main_col = main_col.push(text(error.as_str()).size(14).style(text::danger)); - } + #[cfg(test)] + pub(crate) fn selected(&self) -> Option<&str> { + self.selected.as_deref() + } - main_col = main_col.push(horizontal_rule(1)); + /// Reads the log again from the first page, with the filter and branch shown. + fn refresh(&mut self) -> Task { + self.error = None; + self.clear_selection(); + let search = self.filter.trim(); + self.applied = CommitFilter { + branch: self.branch.clone(), + search: (!search.is_empty()).then(|| search.to_string()), + ..CommitFilter::default() + }; + self.fetch(PAGE_SIZE) + } - // Deux colonnes : liste des commits | volet de details - let commit_list = self.view_commit_list(); - let details = self.view_details_pane(); + fn clear_selection(&mut self) { + self.selected = None; + self.detail = None; + self.detail_error = None; + self.selected_file = None; + self.diff = None; + self.commit_menu = false; + self.confirm_checkout = false; + self.branch_name = None; + } - let two_columns = row![ - container(commit_list).width(Length::FillPortion(55)), - container(details).width(Length::FillPortion(45)), - ] - .spacing(16); + /// Reads the first `limit` commits of the applied filter. + fn fetch(&mut self, limit: usize) -> Task { + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + self.request += 1; + self.loading = true; + let request = self.request; + let filter = self.applied.clone(); + git_task( + repo, + move |repo| read_page(repo, &filter, limit), + move |repo, result| Message::Loaded(repo, request, result), + ) + } - main_col = main_col.push(two_columns); + fn apply_page(&mut self, result: Result) -> Task { + self.loading = false; + match result { + Ok(page) => { + self.has_more = page.commits.len() == page.limit && page.limit < MAX_COMMITS; + self.commits = page.commits; + self.branches = page.branches; + // "Load more" keeps the selection; a new read selects the newest commit. + match (&self.selected, self.commits.first()) { + (None, Some(first)) => { + let id = first.id.clone(); + self.select(id) + } + _ => Task::none(), + } + } + Err(err) => { + self.commits.clear(); + self.has_more = false; + self.error = Some(err); + Task::none() + } + } + } - main_col.into() + fn select(&mut self, id: String) -> Task { + self.clear_selection(); + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + self.selected = Some(id.clone()); + let job_id = id.clone(); + git_task( + repo, + move |repo| read_detail(repo, &job_id), + move |repo, result| Message::DetailLoaded(repo, id.clone(), result), + ) } - /// Section de filtres dans un conteneur stylise. - fn view_filters(&self) -> Element<'_, Message> { - // Premiere ligne : branche et auteur - let branch_input = - text_input("All branches", &self.filters.branch).on_input(Message::BranchFilterChanged); - let branch_pick = pick_list( - self.branches.as_slice(), - None::, - Message::BranchPicked, + fn select_file(&mut self, path: String) -> Task { + let (Some(repo), Some(id)) = (self.repo.clone(), self.selected.clone()) else { + return Task::none(); + }; + self.selected_file = Some(path.clone()); + self.diff = Some(Diff::Loading); + let key = (id.clone(), path.clone()); + git_task( + repo, + move |repo| { + commit_diff_file(repo, &id, &path) + .map(|diff| diff.map(|diff| (diff.patch, diff.truncated))) + .map_err(|err| err.to_string()) + }, + move |repo, result| Message::DiffLoaded(repo, key.clone(), result), ) - .placeholder("Branches locales"); - let author_input = - text_input("name or email", &self.filters.author).on_input(Message::AuthorChanged); - - let first_row = row![ - text("Branch").size(14), - branch_input, - branch_pick, - Space::with_width(Length::Fixed(8.0)), - text("Author").size(14), - author_input, - ] - .spacing(8); - - // Deuxieme ligne : recherche, dates, bouton appliquer - let search_input = - text_input("message contains", &self.filters.search).on_input(Message::SearchChanged); - let since_input = - text_input("YYYY-MM-DD", &self.filters.since).on_input(Message::SinceChanged); - let until_input = - text_input("YYYY-MM-DD", &self.filters.until).on_input(Message::UntilChanged); - let apply_btn = button(text("Apply filters")).on_press(Message::ApplyFilters); - - let second_row = row![ - text("Search").size(14), - search_input, - Space::with_width(Length::Fixed(8.0)), - text("Since").size(14), - since_input, - text("Until").size(14), - until_input, - apply_btn, - ] - .spacing(8); + } + + /// Runs a git action unless one is running. + fn run( + &mut self, + failed: &'static str, + job: impl FnOnce(&str) -> Result + Send + 'static, + ) -> Task { + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + if self.busy { + return Task::none(); + } + self.busy = true; + git_task(repo, job, move |repo, result| { + Message::ActionDone(repo, failed, result) + }) + } - container(column![text("Filters").size(20), first_row, second_row,].spacing(6)) - .padding(10) + pub fn view(&self) -> Element<'_, Message> { + let list = column![self.toolbar(), self.commit_list()] + .width(Length::Fixed(LIST_WIDTH)) + .height(Length::Fill); + row![list, vertical_divider(), self.detail_pane()] + .height(Length::Fill) .into() } - /// Liste defilable des commits. - fn view_commit_list(&self) -> Element<'_, Message> { - let mut col = column![].spacing(4); + /// The filter field and the branch picker. + fn toolbar(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let filter = field( + text_input(t("history_filter_placeholder"), &self.filter).on_input(Message::Filter), + None, + ); + let choices: Vec = std::iter::once(BranchChoice::Head) + .chain(self.branches.iter().cloned().map(BranchChoice::Branch)) + .collect(); + let selected = self + .branch + .clone() + .map_or(BranchChoice::Head, BranchChoice::Branch); + let branch = pick_list(choices, Some(selected), Message::BranchPicked) + .text_size(typo.sz(12)) + .font(typo.regular); + container(row![filter, branch].spacing(6).align_y(Alignment::Center)) + .padding([10, 10]) + .into() + } + fn commit_list(&self) -> Element<'_, Message> { if self.commits.is_empty() { - let empty = if self.loading { - "Chargement..." - } else { - "No commits match the current filters." + let label = match &self.error { + Some(err) => tf("history_load_failed", &[("error", err)]), + None if self.loading => t("changes_loading").to_string(), + None if self.applied.search.is_some() => t("history_no_match").to_string(), + None => t("history_empty").to_string(), }; - col = col.push(text(empty).size(14)); - return scrollable(col).into(); + return note(label); } - + let now = chrono::Utc::now().timestamp(); + let mut rows = Column::new().padding([0, 6]); for commit in &self.commits { - let is_selected = self - .selected_commit - .as_deref() - .map(|id| id == commit.id) - .unwrap_or(false); - - // Formater la date - let date_str = chrono::DateTime::::from_timestamp(commit.time.seconds(), 0) - .map(|dt| dt.format("%Y-%m-%d %H:%M").to_string()) - .unwrap_or_else(|| "Unknown time".to_string()); - - let commit_id = commit.id.clone(); - - // Contenu de la ligne - let row_content = column![ - row![ - text(&commit.summary).size(14), - Space::with_width(Length::Fixed(8.0)), - text(&commit.short_id).size(12), - ] - .spacing(4), - text(commit.author.to_string()).size(12), - text(date_str).size(12), - ] - .spacing(2); - - // Envelopper dans un bouton pour la selection - let commit_btn = button(row_content) - .on_press(Message::SelectCommit(commit_id)) - .padding(8) - .width(Length::Fill); - - // Marquer visuellement la selection - if is_selected { - col = col.push(container(commit_btn).padding(2)); - } else { - col = col.push(commit_btn); - } + let selected = self.selected.as_deref() == Some(commit.id.as_str()); + rows = rows.push(commit_row( + CommitRow::new(commit, now), + commit.id.clone(), + selected, + )); } - - // Bouton pour charger la page suivante si des commits restent disponibles if self.has_more { - col = col.push( - button(text("Charger plus...").size(14)) - .on_press_maybe((!self.loading).then_some(Message::LoadMore)) - .padding(8) - .width(Length::Fill), + rows = rows.push( + container(gs_button::ghost( + t("history_load_more"), + (!self.loading).then_some(Message::LoadMore), + )) + .center_x(Length::Fill) + .padding([8, 0]), ); } - - scrollable(col).into() + scrollable(rows).height(Length::Fill).into() } - /// Volet de details du commit selectionne. - fn view_details_pane(&self) -> Element<'_, Message> { - let mut col = column![].spacing(6); - col = col.push(text("Details").size(20)); - - let Some(commit_id) = &self.selected_commit else { - col = col - .push(text("Select a commit from the list to see its details and diff.").size(14)); - return col.into(); + fn detail_pane(&self) -> Element<'_, Message> { + let selected = self + .selected + .as_ref() + .and_then(|id| self.commits.iter().find(|commit| &commit.id == id)); + let Some(commit) = selected else { + return note(t("history_select_commit").to_string()); }; + let mut files = Column::new().spacing(1); + if let Some(err) = &self.detail_error { + files = files.push(note_line(err.clone())); + } + for file in self.detail.iter().flat_map(|detail| &detail.files) { + files = files.push(self.file_row(file)); + } + let files = container(scrollable(files.padding([6, 10]))).max_height(180.0); + column![ + self.detail_header(commit), + horizontal_divider(), + files, + horizontal_divider(), + diff_view::pane(self.diff.as_ref(), t("history_select_file")), + ] + .width(Length::Fill) + .height(Length::Fill) + .into() + } - // Trouver le commit dans la liste - let Some(commit) = self.commits.iter().find(|c| &c.id == commit_id) else { - col = col.push(text("Commit not found.").size(14)); - return col.into(); + /// The summary with the "⋯" menu, the body, the author, date, hash and parents, then a + /// pending checkout question or branch name field. + fn detail_header<'a>(&'a self, commit: &'a CommitInfo) -> Element<'a, Message> { + let typo = Typography::current(); + let entries = vec![ + item( + t("history_copy_hash"), + Message::CopyHash(commit.id.clone()), + false, + ), + Entry::Separator, + item(t("history_checkout"), Message::ConfirmCheckout(true), false), + item( + t("history_create_branch"), + Message::BranchName(Some(String::new())), + false, + ), + ]; + let more = menu::popup( + gs_button::icon( + MORE_GLYPH, + Some(Message::CommitMenu(!self.commit_menu)), + t("history_commit_actions"), + ), + self.commit_menu, + entries, + Message::CommitMenu(false), + ); + let title = row![ + text(commit.summary.as_str()) + .size(typo.sz(15)) + .font(typo.bold) + .color(Palette::TEXT_PRIMARY()) + .width(Length::Fill), + more, + ] + .spacing(10) + .align_y(Alignment::Start); + + let small = |label: String| { + text(label) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIM()) }; + let date = Local + .timestamp_opt(commit.time.seconds(), 0) + .single() + .map(|date| date.format("%Y-%m-%d %H:%M").to_string()) + .unwrap_or_default(); + let hash = button( + row![ + text(commit.short_id.as_str()) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY()), + text(COPY_GLYPH) + .size(typo.sz(10)) + .font(fonts::glyph_font()) + .color(Palette::TEXT_DIMMER()), + ] + .spacing(6) + .align_y(Alignment::Center), + ) + .padding([2, 7]) + .on_press(Message::CopyHash(commit.id.clone())) + .style(|_, status| button::Style { + background: Some( + if matches!(status, button::Status::Hovered | button::Status::Pressed) { + Palette::BG_SELECTED() + } else { + Palette::BG_CARD_HOVER() + } + .into(), + ), + border: Border::default().rounded(4), + ..Default::default() + }); + let mut meta = row![ + avatar( + &initials(&commit.author), + avatar_accent(commit.email.as_deref().unwrap_or(&commit.author)), + 18.0, + ), + small(commit.author.clone()), + small(date), + gs_button::with_tip(hash, t("history_copy_hash")), + ] + .spacing(12) + .align_y(Alignment::Center); + if let Some(detail) = &self.detail { + let parents: Vec<&str> = detail.parents.iter().map(|id| short_hash(id)).collect(); + match parents.as_slice() { + [] => {} + [one] => meta = meta.push(small(tf("history_parent", &[("hash", one)]))), + many => { + meta = meta.push(small(tf( + "history_parents", + &[("hashes", &many.join(", "))], + ))) + } + } + } - // Resume du commit - col = col.push(text(&commit.summary).size(16)); - - // Corps du message (si different du resume) - let full_message = commit.message.trim(); - let summary_trimmed = commit.summary.trim(); - let message_body = if full_message.starts_with(summary_trimmed) { - full_message - .get(summary_trimmed.len()..) - .unwrap_or("") - .trim_start() - } else { - full_message + let mut header = column![title].spacing(8).padding([16, 18]); + let body = commit_body(commit); + if !body.is_empty() { + header = header.push( + text(body) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIM()), + ); + } + header = header.push(meta); + + let mut bands = column![header]; + let prompt = |label: String| -> Element<'a, Message> { + text(label) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY()) + .into() }; - if !message_body.is_empty() { - col = col.push(text(message_body).size(13)); + let hash = commit.short_id.as_str(); + if self.confirm_checkout { + bands = bands.push(question( + vec![prompt(tf("history_checkout_confirm", &[("hash", hash)]))], + gs_button::primary( + t("history_checkout_button"), + (!self.busy).then_some(Message::Checkout), + ), + Message::ConfirmCheckout(false), + )); } - - // Email de l'auteur - if let Some(email) = &commit.email { - col = col.push(text(email.as_str()).size(12)); + if let Some(name) = &self.branch_name { + let ready = !self.busy && !name.trim().is_empty(); + bands = bands.push(question( + vec![ + prompt(tf("history_branch_prompt", &[("hash", hash)])), + container(field( + text_input(t("history_branch_name"), name) + .on_input(|name| Message::BranchName(Some(name))) + .on_submit_maybe(ready.then_some(Message::CreateBranch)), + None, + )) + .width(Length::Fixed(220.0)) + .into(), + ], + gs_button::primary( + t("history_create_button"), + ready.then_some(Message::CreateBranch), + ), + Message::BranchName(None), + )); } + bands.into() + } - // Statistiques du commit - if let (Some(files), Some(additions), Some(deletions)) = - (commit.files_changed, commit.additions, commit.deletions) - { - col = col.push( - text(format!( - "Files changed: {files} (+{additions}, -{deletions})" - )) - .size(12), + /// A changed file: its name and folder, +N −N and the five-cell bar. + fn file_row<'a>(&'a self, file: &'a FileDiffSummary) -> Element<'a, Message> { + let typo = Typography::current(); + let selected = self.selected_file.as_deref() == Some(file.path.as_str()); + let (folder, name) = file + .path + .rsplit_once('/') + .unwrap_or(("", file.path.as_str())); + let mut content = row![ + text(name) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()), + text(folder) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .width(Length::Fill), + ] + .spacing(8) + .align_y(Alignment::Center); + if file.additions > 0 { + content = content.push( + text(format!("+{}", file.additions)) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::SUCCESS()), ); } - - col = col.push(horizontal_rule(1)); - col = col.push(text("Files changed").size(18)); - - // Erreur de diff - if let Some(error) = &self.diff_error { - col = col.push(text(error.as_str()).size(14)); + if file.deletions > 0 { + content = content.push( + text(format!("−{}", file.deletions)) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::ERROR()), + ); } - - // Liste des fichiers modifies avec diffs expansibles - if self.diff_summaries.is_empty() { - col = col.push(text("No file changes found.").size(14)); - return scrollable(col).into(); + if !file.is_binary { + content = content.push(change_bar(file.additions, file.deletions)); } + button(content) + .on_press(Message::SelectFile(file.path.clone())) + .padding([5, 8]) + .width(Length::Fill) + .style(move |_, status| button::Style { + background: (selected + || matches!(status, button::Status::Hovered | button::Status::Pressed)) + .then(|| Palette::BG_CARD_HOVER().into()), + border: Border::default().rounded(6), + ..Default::default() + }) + .into() + } +} - let mut files_col = column![].spacing(4); - for summary in &self.diff_summaries { - let file_path = summary.path.clone(); - let is_expanded = self.expanded_files.contains(&file_path); - - // En-tete du fichier - let header_text = if summary.is_binary { - format!("{} (binary)", summary.path) - } else { - format!( - "{} (+{}, -{})", - summary.path, summary.additions, summary.deletions - ) - }; - - let expand_label = if is_expanded { "[-]" } else { "[+]" }; - - let header_row = row![ - button(text(expand_label).size(12)) - .on_press(Message::ExpandFile(file_path.clone())) - .padding(2), - text(header_text).size(13), - ] - .spacing(4); +/// A list row: the lane dot, the avatar, the summary with its ref badges over +/// "author · date", and the short hash. +fn commit_row<'a>(commit: CommitRow, id: String, selected: bool) -> Element<'a, Message> { + let typo = Typography::current(); + let mut line = row![ellipsis( + commit.summary, + typo.sz(12), + typo.regular, + Palette::TEXT_PRIMARY() + )] + .spacing(6) + .align_y(Alignment::Center); + for label in &commit.refs { + let tone = match label.kind { + RefKind::Local | RefKind::Head => Tone::Accent, + RefKind::Remote => Tone::Remote, + RefKind::Tag => Tone::Tag, + }; + line = line.push(chip(&label.name, tone)); + } + let meta = text(format!("{} · {}", commit.author, commit.when)) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .wrapping(Wrapping::None); + let content = row![ + lane(commit.is_merge), + avatar(&commit.initials, commit.avatar_accent, 22.0), + column![line, meta] + .spacing(2) + .width(Length::Fill) + .padding([7, 0]), + text(commit.short_id) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + ] + .spacing(10) + .height(Length::Fill) + .align_y(Alignment::Center); + // No vertical padding: the lane runs the full height of the row. + button(content) + .on_press(Message::Select(id)) + .padding(iced::Padding { + top: 0.0, + right: 10.0, + bottom: 0.0, + left: 6.0, + }) + .width(Length::Fill) + .height(Length::Fixed(row_height())) + .style(move |_, status| button::Style { + background: (selected + || matches!(status, button::Status::Hovered | button::Status::Pressed)) + .then(|| Palette::BG_CARD_HOVER().into()), + border: Border::default().rounded(6), + ..Default::default() + }) + .into() +} - files_col = files_col.push(header_row); +/// A row's height at the current text size: its padding, the summary line (as tall as a +/// badge) and the meta line. Fixed so the lane line can run from row to row. +fn row_height() -> f32 { + let typo = Typography::current(); + let line = |size: f32| size * 1.3; + let badge = line(typo.sz(11)) + 6.0; + 14.0 + line(typo.sz(12)).max(badge) + 2.0 + line(typo.sz(11)) + 2.0 +} - // Afficher le diff si le fichier est etendu - if is_expanded { - if let Some(diff) = self.loaded_patches.get(&file_path) { - if diff.truncated { - files_col = - files_col.push(text("Fichier tronque (trop volumineux)").size(11)); - } - // Afficher le patch dans un conteneur a largeur fixe - files_col = files_col.push( - container(scrollable(text(&diff.patch).size(12))) - .padding(4) - .width(Length::Fill), - ); - } else { - files_col = files_col.push(text("Loading...").size(12)); - } +/// The vertical line through the rows with this commit's dot: filled for a commit, +/// a hollow ring for a merge. +fn lane<'a>(is_merge: bool) -> Element<'a, Message> { + let line = container(Space::new().width(2).height(Length::Fill)).style(|_| container::Style { + background: Some(Palette::BG_SELECTED().into()), + ..Default::default() + }); + let dot = container(Space::new().width(9).height(9)).style(move |_| container::Style { + background: Some( + if is_merge { + Palette::BG_PRIMARY() + } else { + Palette::ACCENT() } - } + .into(), + ), + border: Border::default() + .rounded(5) + .width(if is_merge { 2 } else { 0 }) + .color(Tone::Remote.color()), + ..Default::default() + }); + stack![ + container(line) + .center_x(Length::Fixed(16.0)) + .height(Length::Fill), + container(dot) + .center_x(Length::Fixed(16.0)) + .center_y(Length::Fill), + ] + .width(Length::Fixed(16.0)) + .height(Length::Fill) + .into() +} - col = col.push(scrollable(files_col)); +/// The author's initials in a circle of their accent colour. +pub(crate) fn avatar<'a, M: 'a>(initials: &str, accent: &str, size: f32) -> Element<'a, M> { + let typo = Typography::current(); + let color = accent_key_to_color(accent).unwrap_or_else(Palette::ACCENT); + container( + text(initials.to_string()) + .size(typo.sz(if size < 20.0 { 9 } else { 10 })) + .font(typo.bold) + .color(contrast_on(color)), + ) + .center_x(Length::Fixed(size)) + .center_y(Length::Fixed(size)) + .style(move |_| container::Style { + background: Some(color.into()), + border: Border::default().rounded(size / 2.0), + ..Default::default() + }) + .into() +} - scrollable(col).into() +/// Five cells: green for added lines, red for removed ones, one cell per changed line up +/// to five, then shared out in proportion. +fn change_bar<'a>(additions: usize, deletions: usize) -> Element<'a, Message> { + let (added, removed) = bar_cells(additions, deletions); + let mut cells = row![].spacing(1); + for index in 0..5 { + let color = if index < added { + Palette::SUCCESS() + } else if index < added + removed { + Palette::ERROR() + } else { + Palette::BG_SELECTED() + }; + cells = cells.push(container(Space::new().width(6).height(8)).style(move |_| { + container::Style { + background: Some(color.into()), + border: Border::default().rounded(1), + ..Default::default() + } + })); } + cells.into() +} - // ----------------------------------------------------------------------- - // Logique interne - // ----------------------------------------------------------------------- - - fn is_current(&self, repo: &str) -> bool { - self.repo.as_deref() == Some(repo) +/// The green and red cells of the five-cell bar. +fn bar_cells(additions: usize, deletions: usize) -> (usize, usize) { + let total = additions + deletions; + if total == 0 { + return (0, 0); } + let filled = total.min(5); + let added = (filled * additions + total / 2) / total; + // A file with removals shows at least one red cell. + let added = if deletions > 0 { + added.min(filled - 1) + } else { + added + }; + (added, filled - added) +} - /// Relance la recherche avec les filtres saisis, depuis la premiere page. - fn refresh(&mut self) -> Task { - self.error = None; - self.diff_error = None; - self.selected_commit = None; - self.diff_summaries.clear(); - self.loaded_patches.clear(); - self.expanded_files.clear(); - self.applied = self.filters.to_commit_filter(); - self.fetch(PAGE_SIZE) - } +fn note<'a>(label: String) -> Element<'a, Message> { + container(note_line(label)) + .padding([12, 16]) + .width(Length::Fill) + .height(Length::Fill) + .into() +} - /// Lit les `limit` premiers commits du filtre applique. - fn fetch(&mut self, limit: usize) -> Task { - let Some(repo) = self.repo.clone() else { - return Task::none(); - }; - self.request += 1; - self.loading = true; - let request = self.request; - let filter = self.applied.clone(); - git_task( - repo, - move |repo| read_page(repo, &filter, limit), - move |repo, result| Message::Loaded(repo, request, result), - ) - } +fn note_line<'a>(label: String) -> Element<'a, Message> { + let typo = Typography::current(); + text(label) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()) + .into() +} - /// Charge les resumes de diff pour le commit selectionne. - fn load_diff(&mut self) -> Task { - self.diff_summaries.clear(); - self.loaded_patches.clear(); - self.expanded_files.clear(); - self.diff_error = None; +/// The message without its summary line. +fn commit_body(commit: &CommitInfo) -> &str { + let message = commit.message.trim(); + message + .strip_prefix(commit.summary.trim()) + .unwrap_or(message) + .trim_start() +} - let (Some(repo), Some(id)) = (self.repo.clone(), self.selected_commit.clone()) else { - return Task::none(); - }; - git_task( - repo, - { - let id = id.clone(); - move |repo| commit_diff_summaries(repo, &id).map_err(|err| err.to_string()) - }, - move |repo, result| Message::SummariesLoaded(repo, id.clone(), result), - ) - } +fn short_hash(id: &str) -> &str { + id.get(..SHORT_HASH).unwrap_or(id) +} - /// Charge le patch d'un fichier a la demande (chargement paresseux). - fn load_file_patch(&self, file_path: String) -> Task { - let (Some(repo), Some(id)) = (self.repo.clone(), self.selected_commit.clone()) else { - return Task::none(); - }; - let job_id = id.clone(); - let job_path = file_path.clone(); - git_task( - repo, - move |repo| match commit_diff_file(repo, &job_id, &job_path) { - Ok(Some(diff)) => Ok(diff), - // Fichier absent du diff, inserer un espace reserve - Ok(None) => Ok(placeholder_diff("(pas de modifications)")), - Err(err) => Err(err.to_string()), - }, - move |repo, result| { - let diff = result.unwrap_or_else(|err| { - placeholder_diff(&format!("Erreur de chargement du diff : {err}")) - }); - Message::PatchLoaded(repo, id.clone(), file_path.clone(), diff) - }, - ) - } +/// The first letters of the first two words of `author`, upper case. Words are split on +/// anything that is not a letter or digit, so "release-please" gives "RP". +pub(crate) fn initials(author: &str) -> String { + author + .split(|c: char| !c.is_alphanumeric()) + .filter_map(|word| word.chars().next()) + .take(2) + .flat_map(char::to_uppercase) + .collect() +} + +/// The accent key of an author's avatar, the same on every start and machine. +pub(crate) fn avatar_accent(email_or_name: &str) -> &'static str { + // A fixed string hash: std's hashers may change between Rust releases. + let hash = email_or_name + .to_lowercase() + .bytes() + .fold(0u32, |hash, byte| { + hash.wrapping_mul(31).wrapping_add(u32::from(byte)) + }); + ACCENT_OVERRIDES[hash as usize % ACCENT_OVERRIDES.len()].key } -/// Diff sans contenu reel, affiche a la place d'un patch absent ou en erreur. -fn placeholder_diff(patch: &str) -> FileDiff { - FileDiff { - additions: 0, - deletions: 0, - patch: patch.to_string(), - truncated: false, +/// "just now", "5 min ago", "3 h ago", "yesterday", "4 days ago", then the date. +pub(crate) fn relative_time(then: i64, now: i64) -> String { + const MINUTE: i64 = 60; + const HOUR: i64 = 60 * MINUTE; + const DAY: i64 = 24 * HOUR; + const TWO_DAYS: i64 = 2 * DAY; + const WEEK: i64 = 7 * DAY; + let elapsed = now - then; + let count = |unit: i64| (elapsed / unit).to_string(); + match elapsed { + // A commit from a clock ahead of this one counts as new. + i64::MIN..MINUTE => t("time_just_now").to_string(), + MINUTE..HOUR => tf("time_minutes_ago", &[("count", &count(MINUTE))]), + HOUR..DAY => tf("time_hours_ago", &[("count", &count(HOUR))]), + DAY..TWO_DAYS => t("time_yesterday").to_string(), + TWO_DAYS..WEEK => tf("time_days_ago", &[("count", &count(DAY))]), + _ => Local + .timestamp_opt(then, 0) + .single() + .map(|date| date.format("%Y-%m-%d").to_string()) + .unwrap_or_default(), } } -/// Lit les `limit` premiers commits correspondant a `filter` et les branches locales. +/// Reads the first `limit` commits matching `filter` and the local branch names. fn read_page(repo: &str, filter: &CommitFilter, limit: usize) -> Result { let commits = read_commit_log(repo, filter, limit, false).map_err(|err| err.to_string())?; let branches = list_local_branches(repo).unwrap_or_default(); @@ -687,25 +999,94 @@ fn read_page(repo: &str, filter: &CommitFilter, limit: usize) -> Result Option { - if input.trim().is_empty() { - return None; - } - - NaiveDate::parse_from_str(input.trim(), "%Y-%m-%d") - .ok() - .and_then(|date| { - Utc.with_ymd_and_hms(date.year(), date.month(), date.day(), 0, 0, 0) - .earliest() +/// The changed files and the parent hashes of commit `id`. +fn read_detail(repo_path: &str, id: &str) -> Result { + let files = commit_diff_summaries(repo_path, id).map_err(|err| err.to_string())?; + let parents = Oid::from_str(id) + .and_then(|oid| { + let repo = Repository::open(repo_path)?; + let commit = repo.find_commit(oid)?; + Ok(commit.parent_ids().map(|id| id.to_string()).collect()) }) - .map(|dt| dt.timestamp()) + .map_err(|err| err.to_string())?; + Ok(Detail { files, parents }) } #[cfg(test)] mod tests { use super::*; + #[test] + fn initials_take_two_words() { + assert_eq!(initials("Ada Lovelace Byron"), "AL"); + assert_eq!(initials("release-please[bot]"), "RP"); + assert_eq!(initials("élise durand"), "ÉD"); + assert_eq!(initials("Torvalds"), "T"); + assert_eq!(initials(" "), ""); + } + + #[test] + fn avatar_accent_is_stable_per_author() { + let keys: Vec<&str> = ACCENT_OVERRIDES.iter().map(|accent| accent.key).collect(); + let first = avatar_accent("ada@example.com"); + assert!(keys.contains(&first)); + assert_eq!(avatar_accent("ada@example.com"), first); + // A fixed hash, not a seeded one: these values hold on every machine. + let spread: std::collections::HashSet<_> = (0..40) + .map(|n| avatar_accent(&format!("author{n}@example.com"))) + .collect(); + assert!(spread.len() > 3, "authors spread over the accents"); + } + + #[test] + fn relative_time_buckets() { + let now = 1_764_072_000; // 2025-11-25 12:00 UTC + let minute = 60; + let hour = 60 * minute; + let day = 24 * hour; + assert_eq!(relative_time(now - 20, now), t("time_just_now")); + assert_eq!( + relative_time(now - 5 * minute, now), + tf("time_minutes_ago", &[("count", "5")]) + ); + assert_eq!( + relative_time(now - 3 * hour, now), + tf("time_hours_ago", &[("count", "3")]) + ); + assert_eq!(relative_time(now - 30 * hour, now), t("time_yesterday")); + assert_eq!( + relative_time(now - 4 * day, now), + tf("time_days_ago", &[("count", "4")]) + ); + // Noon UTC is the same calendar day in every time zone within ±11 h. + assert_eq!(relative_time(now - 10 * day, now), "2025-11-15"); + // A commit dated in the future, from a skewed clock. + assert_eq!(relative_time(now + hour, now), t("time_just_now")); + } + + #[test] + fn bar_cells_scale_to_five() { + assert_eq!(bar_cells(0, 0), (0, 0)); + assert_eq!(bar_cells(1, 0), (1, 0)); + assert_eq!(bar_cells(5, 1), (4, 1)); + assert_eq!(bar_cells(100, 0), (5, 0)); + assert_eq!(bar_cells(100, 1), (4, 1)); + assert_eq!(bar_cells(1, 1), (1, 1)); + } + + #[test] + fn current_branch_choice_follows_head_again() { + let mut panel = HistoryPanel { + branch: Some("feature-x".into()), + ..HistoryPanel::default() + }; + let _ = panel.update(Message::BranchPicked(BranchChoice::Branch("main".into()))); + assert_eq!(panel.branch.as_deref(), Some("main")); + let _ = panel.update(Message::BranchPicked(BranchChoice::Head)); + assert_eq!(panel.branch, None); + assert_eq!(panel.applied.branch, None); + } + #[test] fn a_full_page_means_more_commits_may_match() { let dir = tempfile::tempdir().unwrap(); @@ -729,5 +1110,9 @@ mod tests { let page = read_page(path, &CommitFilter::default(), 4).unwrap(); assert_eq!(page.commits.len(), 3); assert!(!page.branches.is_empty()); + + let head = parent.unwrap(); + let detail = read_detail(path, &head.id().to_string()).unwrap(); + assert_eq!(detail.parents, [head.parent_id(0).unwrap().to_string()]); } } diff --git a/src/ui/layout.rs b/src/ui/layout.rs deleted file mode 100644 index 0837de4..0000000 --- a/src/ui/layout.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! Structure de la coquille de l'application : header, sidebar, tab bar. - -use iced::widget::{button, column, container, horizontal_rule, row, scrollable, text, Space}; -use iced::{Alignment, Element, Length}; - -use crate::ui::context::RepoContext; -use crate::ui::menu; -use crate::ui::theme::Theme; - -/// Onglet principal de l'application. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub enum MainTab { - Clone, - Open, - RepoOverview, - Stage, - History, - Branches, - Auth, -} - -impl MainTab { - pub const ALL: [Self; 7] = [ - Self::Clone, - Self::Open, - Self::RepoOverview, - Self::Stage, - Self::History, - Self::Branches, - Self::Auth, - ]; - - pub fn label(&self) -> &'static str { - match self { - Self::Clone => "Clone", - Self::Open => "Open", - Self::RepoOverview => "Repo Overview", - Self::Stage => "Stage", - Self::History => "History", - Self::Branches => "Branches", - Self::Auth => "Auth", - } - } -} - -/// Messages générés par le layout shell. -#[derive(Debug, Clone)] -pub enum LayoutMessage { - TabSelected(MainTab), - HeaderClicked, - OpenFileManager, - CopyPath, -} - -/// Construit le header de l'application. -pub fn view_header(theme: &Theme) -> Element<'_, LayoutMessage> { - let header_content = row![ - Space::with_width(8), - button( - text("GitSpace") - .size(theme.typography.heading) - .color(theme.palette.text_primary) - ) - .on_press(LayoutMessage::HeaderClicked) - .padding([4, 8]) - .style(|_: &iced::Theme, _| button::Style { - background: None, - ..Default::default() - }), - Space::with_width(12), - text("Workspace shell") - .size(theme.typography.body) - .color(theme.palette.accent), - Space::with_width(Length::Fill), - ] - .align_y(Alignment::Center) - .height(48); - - container(header_content) - .width(Length::Fill) - .style(move |_: &iced::Theme| { - let surface = theme.palette.surface; - container::Style { - background: Some(surface.into()), - ..Default::default() - } - }) - .into() -} - -/// Construit la sidebar de navigation. -pub fn view_sidebar<'a>( - theme: &'a Theme, - active_tab: MainTab, - repo: Option<&'a RepoContext>, -) -> Element<'a, LayoutMessage> { - let mut sidebar = column![].spacing(2).padding(8).width(220); - - sidebar = sidebar.push(Space::with_height(12)); - sidebar = sidebar.push( - text("Navigation") - .size(theme.typography.title) - .color(theme.palette.text_primary), - ); - sidebar = sidebar.push(horizontal_rule(1)); - sidebar = sidebar.push(Space::with_height(8)); - - // Section Workspaces - sidebar = sidebar.push( - text("Workspaces") - .size(theme.typography.label) - .color(theme.palette.text_secondary), - ); - for (label, tab) in [("Recent", MainTab::Open), ("Remote Repos", MainTab::Clone)] { - sidebar = sidebar.push(menu::menu_item( - theme, - label, - active_tab == tab, - LayoutMessage::TabSelected(tab), - )); - } - - sidebar = sidebar.push(Space::with_height(12)); - sidebar = sidebar.push( - text("Actions") - .size(theme.typography.label) - .color(theme.palette.text_secondary), - ); - for (label, tab) in [ - ("Clone", MainTab::Clone), - ("Open", MainTab::Open), - ("New Branch", MainTab::Branches), - ("Sync", MainTab::Stage), - ] { - sidebar = sidebar.push(menu::menu_item( - theme, - label, - active_tab == tab, - LayoutMessage::TabSelected(tab), - )); - } - - // Section contexte - sidebar = sidebar.push(Space::with_height(12)); - sidebar = sidebar.push( - text("Context") - .size(theme.typography.label) - .color(theme.palette.text_secondary), - ); - - if let Some(repo) = repo { - sidebar = sidebar.push( - text("Active repository") - .size(theme.typography.label) - .color(theme.palette.text_secondary), - ); - sidebar = sidebar.push( - text(&repo.name) - .size(theme.typography.body) - .color(theme.palette.text_primary), - ); - sidebar = sidebar.push( - text(repo.path()) - .size(theme.typography.label) - .color(theme.palette.text_secondary), - ); - sidebar = sidebar.push(Space::with_height(8)); - sidebar = sidebar.push( - button(text("Ouvrir le dossier").size(12)) - .on_press(LayoutMessage::OpenFileManager) - .padding([2, 8]), - ); - sidebar = sidebar.push( - button(text("Copier le chemin").size(12)) - .on_press(LayoutMessage::CopyPath) - .padding([2, 8]), - ); - } else { - sidebar = sidebar.push( - text("Aucun dépôt sélectionné") - .size(theme.typography.label) - .color(theme.palette.text_secondary), - ); - } - - let sidebar_surface = theme.palette.surface; - let sidebar_border = theme.palette.surface_highlight; - - container(scrollable(sidebar).height(Length::Fill)) - .width(220) - .height(Length::Fill) - .style(move |_: &iced::Theme| container::Style { - background: Some(sidebar_surface.into()), - border: iced::Border { - width: 1.0, - color: sidebar_border, - ..Default::default() - }, - ..Default::default() - }) - .into() -} - -/// Construit la barre d'onglets. -pub fn view_tab_bar<'a>( - theme: &'a Theme, - tab_order: &'a [MainTab], - active: MainTab, -) -> Element<'a, LayoutMessage> { - let mut tabs = row![].spacing(4).padding([0, 8]); - - for tab in tab_order { - tabs = tabs.push(menu::tab_button( - theme, - tab.label(), - active == *tab, - LayoutMessage::TabSelected(*tab), - )); - } - - column![container(tabs).width(Length::Fill), horizontal_rule(1),].into() -} diff --git a/src/ui/menu.rs b/src/ui/menu.rs deleted file mode 100644 index f4874db..0000000 --- a/src/ui/menu.rs +++ /dev/null @@ -1,116 +0,0 @@ -//! Composants de menu avec style pour GitSpace Iced. -//! -//! Fournit des fonctions utilitaires pour créer des éléments de menu -//! avec le style Catppuccin et les animations hover/sélection. - -use iced::widget::{button, container, row, text, Space}; -use iced::{Alignment, Color, Element, Length}; - -use crate::ui::theme::{with_alpha, Theme}; - -/// Crée un élément de menu stylisé. -pub fn menu_item<'a, M: Clone + 'a>( - theme: &Theme, - label: &'a str, - selected: bool, - on_press: M, -) -> Element<'a, M> { - let text_color = if selected { - theme.palette.accent - } else { - theme.palette.text_primary - }; - - let bg_color = if selected { - with_alpha(theme.palette.surface_highlight, 0.3) - } else { - Color::TRANSPARENT - }; - - let icon_color = if selected { - with_alpha(theme.palette.accent, 0.9) - } else { - with_alpha(theme.palette.accent, 0.35) - }; - - let content = row![ - // Indicateur circulaire - container(Space::new(7, 7)).style(move |_: &iced::Theme| container::Style { - background: Some(icon_color.into()), - border: iced::Border { - radius: 4.0.into(), - ..Default::default() - }, - ..Default::default() - }), - Space::with_width(10), - text(label).size(theme.typography.body).color(text_color), - ] - .align_y(Alignment::Center) - .padding([4, 8]); - - button(content) - .on_press(on_press) - .padding([4, 8]) - .width(Length::Fill) - .style(move |_theme: &iced::Theme, status| { - let bg = match status { - button::Status::Hovered => with_alpha(bg_color, 0.4), - button::Status::Pressed => with_alpha(bg_color, 0.5), - _ => bg_color, - }; - button::Style { - background: Some(bg.into()), - border: iced::Border { - radius: 6.0.into(), - ..Default::default() - }, - text_color, - ..Default::default() - } - }) - .into() -} - -/// Crée un bouton tab pour la barre d'onglets. -pub fn tab_button<'a, M: Clone + 'a>( - theme: &Theme, - label: &'a str, - is_active: bool, - on_press: M, -) -> Element<'a, M> { - let text_color = if is_active { - theme.palette.text_primary - } else { - theme.palette.text_secondary - }; - - let accent = theme.palette.accent; - - let content = text(label).size(theme.typography.body).color(text_color); - - button(content) - .on_press(on_press) - .padding([6, 16]) - .style(move |_theme: &iced::Theme, status| { - let bg = match status { - button::Status::Hovered if !is_active => with_alpha(accent, 0.1), - _ => Color::TRANSPARENT, - }; - button::Style { - background: Some(bg.into()), - border: iced::Border { - radius: 4.0.into(), - width: if is_active { 2.0 } else { 0.0 }, - color: if is_active { - accent - } else { - Color::TRANSPARENT - }, - }, - text_color, - ..Default::default() - } - }) - .into() -} diff --git a/src/ui/mod.rs b/src/ui/mod.rs index d264314..0a44e8f 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -1,15 +1,80 @@ +pub mod add_repo; pub mod app; -pub mod auth; pub mod branches; -pub mod clone; +pub mod changes; pub mod context; -pub mod fonts; +pub mod diff_view; pub mod history; -pub mod layout; -pub mod menu; -pub mod notifications; pub mod preferences; -pub mod recent; -pub mod repo_overview; -pub mod stage; -pub mod theme; +pub mod repo_header; +pub mod repo_list; +pub mod sidebar; +pub mod stashes; +pub mod widgets; + +/// The lines of `source`, numbered from zero, without the `#[cfg(test)]` items: a whole +/// `mod tests { … }` or a single test-only function, `use` or field. The source guards scan +/// what is left. +#[cfg(test)] +pub(crate) fn non_test_lines(source: &str) -> Vec<(usize, &str)> { + let mut kept = Vec::new(); + let (mut skipping, mut opened, mut depth) = (false, false, 0i64); + for (number, line) in source.lines().enumerate() { + if !skipping && line.trim_start().starts_with("#[cfg(test)]") { + (skipping, opened, depth) = (true, false, 0); + } + if !skipping { + kept.push((number, line)); + continue; + } + // shortcut: brackets inside string literals and comments count too; good enough while + // test items keep them balanced, a real tokenizer if one ever does not. + let mut code = line.to_string(); + for quoted in ["'{'", "'}'", "'('", "')'", "'['", "']'"] { + code = code.replace(quoted, ""); + } + let count = |set: &[char]| code.matches(set).count() as i64; + depth += count(&['{', '(', '[']) - count(&['}', ')', ']']); + opened |= code.contains('{'); + // The item ends where its body closes, or at the `;` or `,` of an item without one. + if depth <= 0 && (opened || code.trim_end().ends_with([';', ','])) { + skipping = false; + } + } + kept +} + +#[cfg(test)] +mod tests { + use super::non_test_lines; + + #[test] + fn source_guards_skip_only_test_items() { + let sample = "fn a() {}\n\ + #[cfg(test)]\n\ + fn helper(\n\ + \x20 a: u8,\n\ + ) -> char {\n\ + \x20 '{'\n\ + }\n\ + fn b() {}\n\ + #[cfg(test)]\n\ + use std::fmt;\n\ + fn c() {}\n\ + #[cfg(test)]\n\ + mod tests {\n\ + \x20 fn d() {}\n\ + }\n\ + fn e() {}"; + let kept = non_test_lines(sample); + assert_eq!( + kept, + [ + (0, "fn a() {}"), + (7, "fn b() {}"), + (10, "fn c() {}"), + (15, "fn e() {}") + ] + ); + } +} diff --git a/src/ui/notifications.rs b/src/ui/notifications.rs deleted file mode 100644 index 7b1df0d..0000000 --- a/src/ui/notifications.rs +++ /dev/null @@ -1,224 +0,0 @@ -//! Système de notifications toast avec auto-dismiss et limites. - -use std::path::PathBuf; -use std::time::{Duration, Instant}; - -use iced::widget::{button, column, container, row, text, Space}; -use iced::{Alignment, Color, Element, Length}; - -use crate::ui::theme::Theme; - -/// Nombre maximum de notifications affichées simultanément. -const MAX_NOTIFICATIONS: usize = 5; - -/// Durée d'affichage d'une erreur avant auto-dismiss (secondes). -const ERROR_DURATION_SECS: u64 = 20; - -/// Actions déclenchables depuis les boutons de notification. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum NotificationAction { - RetryClone, - CopyLogPath(PathBuf), -} - -/// Une notification toast d'erreur avec actions optionnelles. -#[derive(Debug, Clone)] -pub struct Notification { - pub title: String, - pub message: String, - pub detail: Option, - pub actions: Vec, - /// Identifiant attribué par le centre, stable quand d'autres toasts disparaissent. - id: u64, - created_at: Instant, - duration: Duration, -} - -impl Notification { - /// Crée une notification d'erreur. - pub fn error, D: Into>(title: T, message: D) -> Self { - Self { - title: title.into(), - message: message.into(), - detail: None, - actions: Vec::new(), - id: 0, - created_at: Instant::now(), - duration: Duration::from_secs(ERROR_DURATION_SECS), - } - } - - /// Ajoute un bouton d'action à la notification. - pub fn with_action(mut self, action: NotificationAction) -> Self { - self.actions.push(action); - self - } - - /// Retourne true si la notification doit être retirée. - fn is_expired(&self) -> bool { - self.created_at.elapsed() >= self.duration - } -} - -/// Messages du centre de notifications. -#[derive(Debug, Clone)] -pub enum Message { - Dismiss(u64), - ActionClicked(u64, NotificationAction), - Tick, -} - -/// Conteneur pour gérer et afficher les notifications. -#[derive(Default)] -pub struct NotificationCenter { - queue: Vec, - next_id: u64, -} - -impl NotificationCenter { - /// Crée un nouveau centre de notifications. - pub fn new() -> Self { - Self::default() - } - - /// Ajoute une notification à la file. - pub fn push(&mut self, mut notification: Notification) { - notification.id = self.next_id; - self.next_id += 1; - self.queue.push(notification); - while self.queue.len() > MAX_NOTIFICATIONS { - self.queue.remove(0); - } - } - - /// Retourne true s'il n'y a aucune notification. - pub fn is_empty(&self) -> bool { - self.queue.is_empty() - } - - /// Gère un message de notification. Retourne les actions déclenchées. - pub fn update(&mut self, message: Message) -> Vec { - match message { - Message::Dismiss(id) => { - self.queue.retain(|n| n.id != id); - Vec::new() - } - Message::ActionClicked(id, action) => { - self.queue.retain(|n| n.id != id); - vec![action] - } - Message::Tick => { - self.queue.retain(|n| !n.is_expired()); - Vec::new() - } - } - } - - /// Construit la vue des notifications en overlay. - pub fn view(&self, theme: &Theme) -> Element<'_, Message> { - if self.queue.is_empty() { - return Space::new(0, 0).into(); - } - - let fill_color = Color::from_rgb8(125, 32, 32); - let mut notifications = column![].spacing(8).width(Length::Fixed(340.0)); - - for notification in &self.queue { - let id = notification.id; - let mut content = column![].spacing(4); - - // Titre + bouton dismiss - let title_row = row![ - text(¬ification.title) - .size(theme.typography.body) - .color(Color::WHITE), - Space::with_width(Length::Fill), - button(text("x").size(12).color(Color::WHITE)) - .on_press(Message::Dismiss(id)) - .padding(2), - ] - .align_y(Alignment::Center); - content = content.push(title_row); - - // Message - content = content.push( - text(¬ification.message) - .size(theme.typography.label) - .color(Color::from_rgba8(255, 255, 255, 0.85)), - ); - - // Détail optionnel - if let Some(detail) = ¬ification.detail { - content = content.push( - text(detail) - .size(theme.typography.label) - .color(Color::from_rgba8(255, 255, 255, 0.7)), - ); - } - - // Boutons d'action - if !notification.actions.is_empty() { - let mut action_row = row![].spacing(6); - for action in ¬ification.actions { - let label = match action { - NotificationAction::RetryClone => "Réessayer", - NotificationAction::CopyLogPath(_) => "Copier le chemin log", - }; - action_row = action_row.push( - button(text(label).size(12).color(Color::WHITE)) - .on_press(Message::ActionClicked(id, action.clone())) - .padding([2, 6]), - ); - } - content = content.push(action_row); - } - - let toast = container(content) - .padding(12) - .style(move |_theme: &iced::Theme| container::Style { - background: Some(fill_color.into()), - border: iced::Border { - radius: 8.0.into(), - ..Default::default() - }, - ..Default::default() - }) - .width(Length::Fill); - - notifications = notifications.push(toast); - } - - container(notifications).width(Length::Fixed(340.0)).into() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn new_notification_is_not_expired() { - assert!(!Notification::error("Test", "Message").is_expired()); - } - - #[test] - fn notification_center_respects_limit() { - let mut center = NotificationCenter::new(); - for i in 0..10 { - center.push(Notification::error(format!("Test {i}"), "Message")); - } - assert_eq!(center.queue.len(), MAX_NOTIFICATIONS); - assert_eq!(center.queue[0].title, "Test 5"); - } - - #[test] - fn dismiss_removes_the_clicked_notification_at_once() { - let mut center = NotificationCenter::new(); - center.push(Notification::error("Test 1", "Message")); - center.push(Notification::error("Test 2", "Message")); - let second = center.queue[1].id; - center.update(Message::Dismiss(second)); - assert_eq!(center.queue.len(), 1); - assert_eq!(center.queue[0].title, "Test 1"); - } -} diff --git a/src/ui/preferences.rs b/src/ui/preferences.rs deleted file mode 100644 index d501eff..0000000 --- a/src/ui/preferences.rs +++ /dev/null @@ -1,1042 +0,0 @@ -//! Panneau de preferences plein ecran avec sidebar et categories. -//! -//! Remplace le contenu principal quand ouvert. Utilise une sidebar -//! gauche avec 4 categories et un contenu scrollable a droite. - -use iced::widget::{ - button, checkbox, column, container, horizontal_rule, pick_list, row, scrollable, slider, text, - text_input, Space, -}; -use iced::{Alignment, Color, Element, Length, Task}; - -use crate::config::{ - LoggingOptions, Preferences, ThemeMode, MAX_LOG_RETENTION_FILES, MIN_LOG_RETENTION_FILES, -}; -use crate::ui::theme::{with_alpha, Theme}; - -/// Modes de theme disponibles pour le pick_list. -const THEME_MODES: &[ThemeMode] = &[ - ThemeMode::Latte, - ThemeMode::Frappe, - ThemeMode::Macchiato, - ThemeMode::Mocha, -]; - -// ─── Categories ─────────────────────────────────────────────────────────── - -/// Categorie de la sidebar preferences. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PreferencesCategory { - General, - Appearance, - GitSpace, -} - -impl PreferencesCategory { - pub const ALL: [Self; 3] = [Self::General, Self::Appearance, Self::GitSpace]; - - /// Libelle affiche dans la sidebar. - pub fn label(&self) -> &'static str { - match self { - Self::General => "General", - Self::Appearance => "Apparences", - Self::GitSpace => "GitSpace", - } - } - - /// Icone affichee devant le libelle. - pub fn icon(&self) -> &'static str { - match self { - Self::General => "\u{2699}", // ⚙ - Self::Appearance => "\u{1f3a8}", // 🎨 - Self::GitSpace => "\u{1f680}", // 🚀 - } - } -} - -// ─── Messages ───────────────────────────────────────────────────────────── - -/// Messages emis par le panneau de preferences. -#[derive(Debug, Clone)] -pub enum Message { - /// Changer la categorie active dans la sidebar. - SelectCategory(PreferencesCategory), - /// Fermer le panneau de preferences. - Close, - - // -- General -- - /// Chemin de destination par defaut modifie. - DefaultClonePathChanged(String), - /// Ouvrir le selecteur de dossier. - BrowseClonePath, - /// Resultat du selecteur de dossier. - BrowseClonePathResult(Option), - /// Proxy HTTP modifie. - HttpProxyChanged(String), - /// Proxy HTTPS modifie. - HttpsProxyChanged(String), - /// Timeout reseau modifie. - NetworkTimeoutChanged(String), - /// Preference HTTPS modifiee. - UseHttpsChanged(bool), - /// Permission SSH modifiee. - AllowSshChanged(bool), - /// Recuperation automatique activee/desactivee. - AutoFetchEnabledChanged(bool), - /// Intervalle de recuperation automatique modifie. - AutoFetchIntervalChanged(String), - - // -- Apparences -- - /// Mode de theme modifie. - ThemeModeChanged(ThemeMode), - - // -- GitSpace -- - /// Nombre de fichiers de log conserves modifie. - RetentionFilesChanged(f32), - /// Stockage chiffre autorise/desautorise. - AllowEncryptedTokensChanged(bool), - /// Importer les parametres. - ImportSettings, - /// Resultat de l'import (`None` si l'utilisateur a annule). - ImportResult(Result, String>), - /// Exporter les parametres. - ExportSettings, - /// Resultat de l'export : chemin ecrit, ou `None` si l'utilisateur a annule. - ExportResult(Result, String>), - - // -- Actions globales -- - /// Sauvegarder les preferences. - SavePreferences, - /// Demander la reinitialisation des preferences par defaut. - ResetDefaults, - /// Confirmer la reinitialisation. - ConfirmReset, - /// Annuler la reinitialisation. - CancelReset, -} - -// ─── Etat ───────────────────────────────────────────────────────────────── - -/// Panneau de preferences plein ecran. -pub struct PreferencesPanel { - /// Preferences courantes en cours d'edition. - preferences: Preferences, - /// Options de journalisation courantes. - logging: LoggingOptions, - /// Dernieres preferences appliquees, restaurees a la fermeture sans sauvegarde. - applied: Preferences, - /// Derniere journalisation appliquee. - applied_logging: LoggingOptions, - /// Preferences en attente d'application par l'app. - pending_preferences: Option, - /// Journalisation en attente d'application. - pending_logging: Option, - /// Statut import/export. - import_status: Option, - export_status: Option, - /// Erreur d'import ou d'export. - io_error: Option, - /// La reinitialisation attend une confirmation. - confirm_reset: bool, - /// Le panneau est-il ouvert ? - open: bool, - /// Categorie active de la sidebar. - active_category: PreferencesCategory, - /// Tampon texte pour le timeout reseau. - timeout_buffer: String, - /// Tampon texte pour l'intervalle de fetch. - fetch_interval_buffer: String, -} - -impl PreferencesPanel { - /// Cree un nouveau panneau de preferences. - pub fn new(preferences: Preferences, logging: LoggingOptions) -> Self { - let timeout_buffer = preferences.network().network_timeout_secs.to_string(); - let fetch_interval_buffer = preferences.auto_fetch_interval_minutes().to_string(); - Self { - applied: preferences.clone(), - applied_logging: logging, - preferences, - logging, - pending_preferences: None, - pending_logging: None, - import_status: None, - export_status: None, - io_error: None, - confirm_reset: false, - open: false, - active_category: PreferencesCategory::General, - timeout_buffer, - fetch_interval_buffer, - } - } - - /// Enregistre les preferences appliquees par l'application. Les modifications en cours - /// restent a l'ecran tant que le panneau est ouvert. - pub fn set_preferences(&mut self, preferences: Preferences) { - self.applied = preferences; - if !self.open { - self.discard_edits(); - } - } - - /// Remplace la copie editee par les dernieres valeurs appliquees. - fn discard_edits(&mut self) { - self.preferences = self.applied.clone(); - self.logging = self.applied_logging; - self.timeout_buffer = self.preferences.network().network_timeout_secs.to_string(); - self.fetch_interval_buffer = self.preferences.auto_fetch_interval_minutes().to_string(); - self.confirm_reset = false; - } - - /// Transmet `preferences` a l'application et les retient comme appliquees. - fn apply(&mut self, preferences: Preferences) { - self.applied = preferences.clone(); - self.pending_preferences = Some(preferences); - } - - /// Le panneau est-il ouvert ? - pub fn is_open(&self) -> bool { - self.open - } - - /// Bascule l'ouverture du panneau. Les modifications non sauvegardees sont abandonnees. - pub fn toggle(&mut self) { - self.discard_edits(); - self.open = !self.open; - } - - /// Recupere les preferences en attente d'application. - pub fn take_changes(&mut self) -> Option { - self.pending_preferences.take() - } - - /// Recupere les changements de journalisation en attente. - pub fn take_logging_changes(&mut self) -> Option { - self.pending_logging.take() - } - - // ─── Update ─────────────────────────────────────────────────────── - - /// Traite un message et renvoie une tache Iced. - pub fn update(&mut self, message: Message) -> Task { - match message { - Message::SelectCategory(cat) => { - self.active_category = cat; - Task::none() - } - Message::Close => { - self.discard_edits(); - self.open = false; - Task::none() - } - - // -- General -- - Message::DefaultClonePathChanged(path) => { - self.preferences.set_default_clone_path(path); - Task::none() - } - Message::BrowseClonePath => Task::perform( - tokio::task::spawn_blocking(|| { - rfd::FileDialog::new() - .pick_folder() - .map(|p| p.display().to_string()) - }), - |result| Message::BrowseClonePathResult(result.ok().flatten()), - ), - Message::BrowseClonePathResult(Some(path)) => { - self.preferences.set_default_clone_path(path); - Task::none() - } - Message::BrowseClonePathResult(None) => Task::none(), - Message::HttpProxyChanged(val) => { - self.preferences.network_mut().http_proxy = val; - Task::none() - } - Message::HttpsProxyChanged(val) => { - self.preferences.network_mut().https_proxy = val; - Task::none() - } - Message::NetworkTimeoutChanged(val) => { - self.timeout_buffer = val.clone(); - if let Ok(secs) = val.trim().parse::() { - self.preferences.network_mut().network_timeout_secs = secs; - } - Task::none() - } - Message::UseHttpsChanged(val) => { - self.preferences.network_mut().use_https = val; - Task::none() - } - Message::AllowSshChanged(val) => { - self.preferences.network_mut().allow_ssh = val; - Task::none() - } - Message::AutoFetchEnabledChanged(val) => { - self.preferences.set_auto_fetch_enabled(val); - Task::none() - } - Message::AutoFetchIntervalChanged(val) => { - self.fetch_interval_buffer = val.clone(); - if let Ok(minutes) = val.trim().parse::() { - if minutes > 0 { - self.preferences.set_auto_fetch_interval_minutes(minutes); - } - } - Task::none() - } - - // -- Apparences -- - Message::ThemeModeChanged(mode) => { - // Le theme s'applique tout de suite, sans les autres modifications en cours. - self.preferences.set_theme_mode(mode); - let mut applied = self.applied.clone(); - applied.set_theme_mode(mode); - self.apply(applied); - Task::none() - } - - // -- GitSpace -- - Message::RetentionFilesChanged(val) => { - self.logging.set_retention_files(val as usize); - Task::none() - } - Message::AllowEncryptedTokensChanged(val) => { - self.preferences.set_allow_encrypted_tokens(val); - Task::none() - } - Message::ImportSettings => Task::perform( - tokio::task::spawn_blocking(|| { - let path = rfd::FileDialog::new() - .add_filter("JSON", &["json"]) - .pick_file(); - path.map(|p| Preferences::from_path(&p).map_err(|e| e.to_string())) - .transpose() - }), - |result| match result { - Ok(inner) => Message::ImportResult(inner), - Err(err) => Message::ImportResult(Err(err.to_string())), - }, - ), - Message::ImportResult(result) => { - match result { - Ok(Some(prefs)) => { - self.apply(prefs); - self.discard_edits(); - self.io_error = None; - self.import_status = Some("Preferences importees avec succes".to_string()); - } - Ok(None) => {} - Err(e) => { - self.import_status = None; - self.io_error = Some(format!("Erreur d'import : {e}")); - } - } - Task::none() - } - Message::ExportSettings => { - let prefs = self.preferences.clone(); - Task::perform( - tokio::task::spawn_blocking(move || { - let path = rfd::FileDialog::new() - .add_filter("JSON", &["json"]) - .set_file_name("gitspace-preferences.json") - .save_file(); - path.map(|p| { - prefs - .save_to_path(&p) - .map(|_| p.display().to_string()) - .map_err(|e| e.to_string()) - }) - .transpose() - }), - |result| match result { - Ok(inner) => Message::ExportResult(inner), - Err(err) => Message::ExportResult(Err(err.to_string())), - }, - ) - } - Message::ExportResult(result) => { - match result { - Ok(Some(path)) => { - self.io_error = None; - self.export_status = Some(format!("Preferences exportees dans {path}")); - } - Ok(None) => {} - Err(e) => { - self.export_status = None; - self.io_error = Some(format!("Erreur d'export : {e}")); - } - } - Task::none() - } - - // -- Actions globales -- - Message::SavePreferences => { - self.apply(self.preferences.clone()); - self.applied_logging = self.logging; - self.pending_logging = Some(self.logging); - Task::none() - } - Message::ResetDefaults => { - self.confirm_reset = true; - Task::none() - } - Message::CancelReset => { - self.confirm_reset = false; - Task::none() - } - Message::ConfirmReset => { - self.apply(Preferences::default()); - self.applied_logging = LoggingOptions::default(); - self.pending_logging = Some(self.applied_logging); - self.discard_edits(); - Task::none() - } - } - } - - // ─── View ───────────────────────────────────────────────────────── - - /// Construit la vue plein ecran du panneau de preferences. - /// Retourne `None` si le panneau est ferme. - pub fn view<'a>(&'a self, theme: &'a Theme) -> Option> { - if !self.open { - return None; - } - let palette = &theme.palette; - - // Sidebar gauche - let sidebar = self.view_sidebar(theme); - - // Contenu a droite selon la categorie - let content_area = match self.active_category { - PreferencesCategory::General => self.view_general(theme), - PreferencesCategory::Appearance => self.view_appearance(theme), - PreferencesCategory::GitSpace => self.view_gitspace(theme), - }; - - // Boutons Sauvegarder / Reinitialiser en bas du contenu - let actions = self.view_content_actions(theme); - - let right_panel = column![ - scrollable( - container(content_area) - .width(Length::Fill) - .padding(theme.spacing.lg) - ) - .width(Length::Fill) - .height(Length::Fill), - container(actions) - .width(Length::Fill) - .padding([theme.spacing.sm, theme.spacing.lg]), - ] - .width(Length::Fill) - .height(Length::Fill); - - // Separateur vertical simule par un container colore - let separator = - container(Space::with_width(1)) - .height(Length::Fill) - .style(move |_: &iced::Theme| container::Style { - background: Some(palette.surface_highlight.into()), - ..Default::default() - }); - - let layout = row![sidebar, separator, right_panel] - .width(Length::Fill) - .height(Length::Fill); - - let panel = container(layout) - .width(Length::Fill) - .height(Length::Fill) - .style(move |_: &iced::Theme| container::Style { - background: Some(palette.background.into()), - ..Default::default() - }); - - Some(panel.into()) - } - - // ─── Sidebar ────────────────────────────────────────────────────── - - /// Construit la sidebar avec les categories et le bouton fermer. - fn view_sidebar<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let mut sidebar_items = column![ - Space::with_height(theme.spacing.sm), - text("Preferences") - .size(typo.title) - .color(palette.text_primary), - Space::with_height(theme.spacing.md), - ] - .spacing(2); - - // Boutons de categories - for cat in PreferencesCategory::ALL { - let is_selected = self.active_category == cat; - sidebar_items = sidebar_items.push(self.view_sidebar_button(theme, cat, is_selected)); - } - - // Espace flexible pour pousser le bouton Fermer en bas - sidebar_items = sidebar_items.push(Space::with_height(Length::Fill)); - - // Bouton Fermer (abandonne les modifications non sauvegardees) - let close_btn = button(text("Fermer").size(typo.body).color(palette.text_primary)) - .on_press(Message::Close) - .padding([6, 12]) - .width(Length::Fill) - .style(rounded_style( - with_alpha(palette.surface_highlight, 0.3), - with_alpha(palette.accent, 0.2), - with_alpha(palette.accent, 0.3), - palette.text_primary, - )); - - sidebar_items = sidebar_items.push(close_btn); - sidebar_items = sidebar_items.push(Space::with_height(theme.spacing.sm)); - - container(sidebar_items.padding(theme.spacing.sm)) - .width(200) - .height(Length::Fill) - .style(move |_: &iced::Theme| container::Style { - background: Some(palette.surface.into()), - ..Default::default() - }) - .into() - } - - /// Construit un bouton de sidebar pour une categorie. - fn view_sidebar_button<'a>( - &'a self, - theme: &'a Theme, - category: PreferencesCategory, - is_selected: bool, - ) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let text_color = if is_selected { - palette.accent - } else { - palette.text_primary - }; - let accent = palette.accent; - let surface_hl = palette.surface_highlight; - - let label_text = format!("{} {}", category.icon(), category.label()); - - let content = row![ - // Indicateur accent a gauche si selectionne - if is_selected { - container(Space::with_width(3)) - .height(24) - .style(move |_: &iced::Theme| container::Style { - background: Some(accent.into()), - border: iced::Border { - radius: 2.0.into(), - ..Default::default() - }, - ..Default::default() - }) - } else { - container(Space::with_width(3)).height(24) - }, - Space::with_width(6), - text(label_text).size(typo.body).color(text_color), - ] - .align_y(Alignment::Center); - - let selected_bg = if is_selected { - with_alpha(surface_hl, 0.4) - } else { - Color::TRANSPARENT - }; - - let hovered = if is_selected { - selected_bg - } else { - with_alpha(surface_hl, 0.25) - }; - - button(content) - .on_press(Message::SelectCategory(category)) - .padding([6, 8]) - .width(Length::Fill) - .style(rounded_style( - selected_bg, - hovered, - with_alpha(surface_hl, 0.5), - text_color, - )) - .into() - } - - // ─── Boutons d'actions bas du contenu ────────────────────────────── - - /// Boutons Sauvegarder et Reinitialiser en bas du contenu. La reinitialisation demande - /// une confirmation. - fn view_content_actions<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - let accent = palette.accent; - let surface_hl = palette.surface_highlight; - - let save_btn = button( - text("Sauvegarder") - .size(typo.body) - .color(palette.background), - ) - .on_press(Message::SavePreferences) - .padding([8, 16]) - .style(rounded_style( - accent, - with_alpha(accent, 0.85), - with_alpha(accent, 0.7), - palette.background, - )); - - let mut actions = row![save_btn] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - if self.confirm_reset { - actions = actions - .push( - text("Remettre toutes les preferences par defaut ?") - .size(typo.body) - .color(palette.text_primary), - ) - .push(styled_secondary_button( - theme, - "Confirmer", - Message::ConfirmReset, - )) - .push(styled_secondary_button( - theme, - "Annuler", - Message::CancelReset, - )); - } else { - actions = actions.push( - button( - text("Reinitialiser") - .size(typo.body) - .color(palette.text_primary), - ) - .on_press(Message::ResetDefaults) - .padding([8, 16]) - .style(rounded_style( - with_alpha(surface_hl, 0.2), - with_alpha(surface_hl, 0.4), - with_alpha(surface_hl, 0.6), - palette.text_primary, - )), - ); - } - - actions.into() - } - - // ─── Contenu : General ──────────────────────────────────────────── - - /// Section General : chemin de clone, options reseau. - fn view_general<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let heading = text("General") - .size(typo.heading) - .color(palette.text_primary); - - let subtitle = text("Chemin de clone par defaut et options reseau") - .size(typo.body) - .color(palette.text_secondary); - - // -- Chemin de clone -- - let clone_label = text("Destination par defaut") - .size(typo.body) - .color(palette.text_secondary); - - let clone_input = text_input("/home/me/code", self.preferences.default_clone_path()) - .on_input(Message::DefaultClonePathChanged) - .width(Length::Fixed(300.0)); - - let browse_btn = styled_secondary_button(theme, "Choisir", Message::BrowseClonePath); - - let clone_row = row![clone_label, clone_input, browse_btn] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - // -- Reseau -- - let network = self.preferences.network(); - - let http_proxy_label = text("Proxy HTTP") - .size(typo.body) - .color(palette.text_secondary); - let http_proxy_input = text_input("http://proxy:8080", &network.http_proxy) - .on_input(Message::HttpProxyChanged) - .width(Length::Fixed(260.0)); - let http_proxy_row = row![http_proxy_label, http_proxy_input] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - let https_proxy_label = text("Proxy HTTPS") - .size(typo.body) - .color(palette.text_secondary); - let https_proxy_input = text_input("https://proxy:8443", &network.https_proxy) - .on_input(Message::HttpsProxyChanged) - .width(Length::Fixed(260.0)); - let https_proxy_row = row![https_proxy_label, https_proxy_input] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - let timeout_label = text("Timeout (sec)") - .size(typo.body) - .color(palette.text_secondary); - let timeout_input = text_input("30", &self.timeout_buffer) - .on_input(Message::NetworkTimeoutChanged) - .width(Length::Fixed(80.0)); - let timeout_row = row![timeout_label, timeout_input] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - let use_https_cb = - checkbox("Preferer HTTPS", network.use_https).on_toggle(Message::UseHttpsChanged); - let allow_ssh_cb = - checkbox("Autoriser SSH", network.allow_ssh).on_toggle(Message::AllowSshChanged); - let proto_row = row![ - use_https_cb, - Space::with_width(theme.spacing.md), - allow_ssh_cb - ] - .align_y(Alignment::Center); - - let auto_fetch_cb = checkbox( - "Recuperation automatique des remotes", - self.preferences.auto_fetch_enabled(), - ) - .on_toggle(Message::AutoFetchEnabledChanged); - - let mut network_col = column![ - section_header(theme, "Reseau", "Proxy, timeout et protocoles"), - Space::with_height(theme.spacing.xs), - http_proxy_row, - https_proxy_row, - timeout_row, - proto_row, - auto_fetch_cb, - ] - .spacing(theme.spacing.sm); - - // Intervalle de fetch si active - if self.preferences.auto_fetch_enabled() { - let interval_label = text("Intervalle (min)") - .size(typo.body) - .color(palette.text_secondary); - let interval_input = text_input("5", &self.fetch_interval_buffer) - .on_input(Message::AutoFetchIntervalChanged) - .width(Length::Fixed(80.0)); - let interval_row = row![interval_label, interval_input] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - network_col = network_col.push(interval_row); - } - - column![ - heading, - subtitle, - Space::with_height(theme.spacing.md), - section_header( - theme, - "Depots", - "Chemin de destination par defaut pour les clones" - ), - Space::with_height(theme.spacing.xs), - clone_row, - Space::with_height(theme.spacing.md), - horizontal_rule(1), - Space::with_height(theme.spacing.md), - network_col, - ] - .spacing(theme.spacing.sm) - .width(Length::Fill) - .into() - } - - // ─── Contenu : Apparences ───────────────────────────────────────── - - /// Section Apparences : selection du theme. - fn view_appearance<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let heading = text("Apparences") - .size(typo.heading) - .color(palette.text_primary); - - let subtitle = text("Personnalisez l'apparence de GitSpace") - .size(typo.body) - .color(palette.text_secondary); - - // Theme - let theme_label = text("Theme Catppuccin") - .size(typo.body) - .color(palette.text_secondary); - - let theme_pick = pick_list( - THEME_MODES, - Some(self.preferences.theme_mode()), - Message::ThemeModeChanged, - ) - .width(Length::Fixed(160.0)); - - let theme_row = row![theme_label, theme_pick] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - column![ - heading, - subtitle, - Space::with_height(theme.spacing.md), - section_header(theme, "Theme", "Choisissez un theme Catppuccin"), - Space::with_height(theme.spacing.xs), - theme_row, - ] - .spacing(theme.spacing.sm) - .width(Length::Fill) - .into() - } - - // ─── Contenu : GitSpace ─────────────────────────────────────────── - - /// Section GitSpace : journalisation, import/export, mises a jour, reinitialisation. - fn view_gitspace<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let heading = text("GitSpace") - .size(typo.heading) - .color(palette.text_primary); - - let subtitle = text("Parametres specifiques a GitSpace") - .size(typo.body) - .color(palette.text_secondary); - - // -- Journalisation -- - let retention_label = text("Fichiers de log conserves") - .size(typo.body) - .color(palette.text_secondary); - - let retention_slider = slider( - MIN_LOG_RETENTION_FILES as f32..=MAX_LOG_RETENTION_FILES as f32, - self.logging.retention_files() as f32, - Message::RetentionFilesChanged, - ) - .width(Length::Fixed(200.0)); - - let retention_value = text(format!("{}", self.logging.retention_files())) - .size(typo.label) - .color(palette.text_secondary); - - let retention_row = row![retention_label, retention_slider, retention_value] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - // -- Confidentialite -- - let encrypted_cb = checkbox( - "Autoriser le stockage chiffre des tokens", - self.preferences.allow_encrypted_tokens(), - ) - .on_toggle(Message::AllowEncryptedTokensChanged); - - // -- Import / Export -- - let import_btn = styled_secondary_button(theme, "Importer", Message::ImportSettings); - - let export_btn = styled_secondary_button(theme, "Exporter", Message::ExportSettings); - - let mut ie_col = column![ - row![import_btn, Space::with_width(theme.spacing.sm), export_btn] - .align_y(Alignment::Center), - ] - .spacing(theme.spacing.xs); - - if let Some(status) = &self.import_status { - ie_col = ie_col.push( - text(status.as_str()) - .size(typo.label) - .color(palette.text_secondary), - ); - } - if let Some(status) = &self.export_status { - ie_col = ie_col.push( - text(status.as_str()) - .size(typo.label) - .color(palette.text_secondary), - ); - } - if let Some(error) = &self.io_error { - ie_col = ie_col.push(text(error.as_str()).size(typo.body).style(text::danger)); - } - - column![ - heading, - subtitle, - Space::with_height(theme.spacing.md), - section_header( - theme, - "Journalisation", - "Nombre de fichiers de log conserves" - ), - Space::with_height(theme.spacing.xs), - retention_row, - Space::with_height(theme.spacing.md), - horizontal_rule(1), - Space::with_height(theme.spacing.md), - section_header(theme, "Confidentialite", "Stockage securise des tokens"), - Space::with_height(theme.spacing.xs), - encrypted_cb, - Space::with_height(theme.spacing.md), - horizontal_rule(1), - Space::with_height(theme.spacing.md), - section_header( - theme, - "Import / Export", - "Transferez vos preferences au format JSON" - ), - Space::with_height(theme.spacing.xs), - ie_col, - ] - .spacing(theme.spacing.sm) - .width(Length::Fill) - .into() - } -} - -// ─── Helpers ────────────────────────────────────────────────────────────── - -/// En-tete de sous-section avec barre accent a gauche. -fn section_header<'a, M: 'a>( - theme: &'a Theme, - title: &'a str, - subtitle: &'a str, -) -> Element<'a, M> { - let palette = &theme.palette; - let typo = &theme.typography; - let accent = palette.accent; - - let indicator = container(Space::with_width(3)) - .height(32) - .style(move |_: &iced::Theme| container::Style { - background: Some(accent.into()), - border: iced::Border { - radius: 2.0.into(), - ..Default::default() - }, - ..Default::default() - }); - - let labels = column![ - text(title).size(typo.body).color(palette.text_primary), - text(subtitle) - .size(typo.label) - .color(palette.text_secondary), - ] - .spacing(2); - - row![indicator, Space::with_width(8), labels] - .align_y(Alignment::Center) - .into() -} - -/// Cree un bouton secondaire style Colony (fond surface_highlight, coins arrondis). -fn styled_secondary_button<'a>( - theme: &'a Theme, - label: &'a str, - on_press: Message, -) -> Element<'a, Message> { - let palette = &theme.palette; - let surface_hl = palette.surface_highlight; - - button( - text(label) - .size(theme.typography.body) - .color(palette.text_primary), - ) - .on_press(on_press) - .padding([6, 12]) - .style(rounded_style( - with_alpha(surface_hl, 0.3), - with_alpha(surface_hl, 0.5), - with_alpha(surface_hl, 0.7), - palette.text_primary, - )) - .into() -} - -/// Style de bouton a coins arrondis, avec un fond par etat (repos, survol, appui). -fn rounded_style( - idle: Color, - hovered: Color, - pressed: Color, - text_color: Color, -) -> impl Fn(&iced::Theme, button::Status) -> button::Style { - move |_, status| button::Style { - background: Some( - match status { - button::Status::Hovered => hovered, - button::Status::Pressed => pressed, - _ => idle, - } - .into(), - ), - border: iced::Border { - radius: 6.0.into(), - ..Default::default() - }, - text_color, - ..Default::default() - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn open_panel() -> PreferencesPanel { - let mut panel = PreferencesPanel::new(Preferences::default(), LoggingOptions::default()); - panel.toggle(); - panel - } - - #[test] - fn theme_change_applies_only_the_theme() { - let mut panel = open_panel(); - let _ = panel.update(Message::AutoFetchEnabledChanged(true)); - let _ = panel.update(Message::ThemeModeChanged(ThemeMode::Latte)); - - let applied = panel.take_changes().expect("theme applied"); - assert_eq!(applied.theme_mode(), ThemeMode::Latte); - assert!(!applied.auto_fetch_enabled()); - // The app hands the applied value back; the unsaved edit stays on screen. - panel.set_preferences(applied); - assert!(panel.preferences.auto_fetch_enabled()); - } - - #[test] - fn close_discards_unsaved_edits_and_reset_waits_for_confirmation() { - let mut panel = open_panel(); - let _ = panel.update(Message::AutoFetchEnabledChanged(true)); - let _ = panel.update(Message::Close); - assert!(!panel.preferences.auto_fetch_enabled()); - assert!(panel.take_changes().is_none()); - - panel.toggle(); - let _ = panel.update(Message::ResetDefaults); - assert!(panel.take_changes().is_none()); - let _ = panel.update(Message::ConfirmReset); - assert_eq!(panel.take_changes(), Some(Preferences::default())); - } -} diff --git a/src/ui/preferences/about.rs b/src/ui/preferences/about.rs new file mode 100644 index 0000000..2c50e1f --- /dev/null +++ b/src/ui/preferences/about.rs @@ -0,0 +1,66 @@ +//! Preferences → About: version, licence, source code and where GitSpace keeps its files. + +use std::path::Path; + +use colony_ui::theme::Palette; +use colony_ui::widgets::{category_heading, setting_row}; +use colony_ui::Typography; +use iced::widget::{row, text, Column}; +use iced::Element; + +use super::{Message, PreferencesPage}; +use crate::i18n::t; +use crate::ui::widgets::button as gs_button; + +const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); + +pub(super) fn view<'a>(page: &'a PreferencesPage, typo: &Typography) -> Column<'a, Message> { + let value = |value: &str| -> Element<'a, Message> { + text(value.to_string()) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY()) + .into() + }; + let folder = |title: &str, path: &Path| { + let shown = path.display().to_string(); + setting_row( + typo, + title, + &shown, + row![ + gs_button::secondary(t("prefs_copy"), Some(Message::Copy(shown.clone()))), + gs_button::secondary( + t("prefs_open"), + Some(Message::OpenFolder(path.to_path_buf())) + ), + ] + .spacing(8), + ) + }; + category_heading( + typo, + colony_ui::i18n::t(super::ABOUT_CATEGORY), + t("prefs_about_desc"), + ) + .push(setting_row( + typo, + t("prefs_version"), + "", + value(env!("CARGO_PKG_VERSION")), + )) + .push(setting_row( + typo, + t("prefs_licence"), + "", + value(env!("CARGO_PKG_LICENSE")), + )) + .push(setting_row( + typo, + t("prefs_source_code"), + REPOSITORY, + gs_button::secondary(t("prefs_open"), Some(Message::OpenUrl(REPOSITORY))), + )) + .push(folder(t("prefs_config_folder"), &page.config_dir)) + .push(folder(t("prefs_logs_folder"), &page.logs_dir)) +} diff --git a/src/ui/preferences/accounts.rs b/src/ui/preferences/accounts.rs new file mode 100644 index 0000000..5e31bae --- /dev/null +++ b/src/ui/preferences/accounts.rs @@ -0,0 +1,672 @@ +//! Preferences → Accounts: the saved accounts, GitHub's device flow, GitLab's browser +//! sign-in (OAuth2 PKCE) and personal access tokens. + +use std::sync::mpsc::{self, Receiver, Sender}; + +use colony_ui::theme::Palette; +use colony_ui::Typography; +use iced::futures::{SinkExt, Stream}; +use iced::widget::{column, container, row, text, text_input, Column}; +use iced::{Alignment, Border, Element, Length, Task}; + +use crate::auth::{AuthManager, DeviceFlow, OAuthProvider, OAuthResult}; +use crate::i18n::{t, tf}; +use crate::ui::changes::field; +use crate::ui::history::{avatar, avatar_accent, initials}; +use crate::ui::widgets::button as gs_button; +use crate::ui::widgets::chip::{chip, Tone}; + +/// OAuth client IDs set at build time. When set, they replace the ID typed in Preferences. +/// +/// GitHub (device flow): an OAuth app at https://github.com/settings/developers with +/// "Enable Device Flow" ticked; the callback URL is not used. +/// GitLab (PKCE): an application at https://gitlab.com/-/user_settings/applications with +/// "Confidential" unticked and the redirect URI http://127.0.0.1:9876/callback. +const GITHUB_CLIENT_ID: Option<&str> = option_env!("GITSPACE_GITHUB_CLIENT_ID"); +const GITLAB_CLIENT_ID: Option<&str> = option_env!("GITSPACE_GITLAB_CLIENT_ID"); + +/// A status line: a label key and the error or detail its `{error}` placeholder takes. +/// Translated when drawn, so a language change shows at once. +type Status = Option<(&'static str, String)>; + +#[derive(Debug, Clone)] +pub enum Message { + StartGithubOAuth, + StartGitlabOAuth, + /// A step of a GitHub sign-in, with the attempt's id. + GithubSignIn(u64, GithubSignInEvent), + CancelGithubSignIn, + CopyGithubCode, + OpenGithubVerification, + GitlabOAuthResult(OAuthResult), + ManualHostChanged(String), + ManualTokenChanged(String), + ValidateAndSave, + ValidationResult(Result<(), String>), + GithubClientIdChanged(String), + GitlabClientIdChanged(String), + /// Removes the account saved for a host. + Disconnect(String), + Disconnected(Result<(), String>), + /// A received OAuth token was saved, or not. + OAuthStored(OAuthService, Result<(), String>), + /// The saved accounts, read again: host, whether it holds an OAuth token, and the + /// account name saved with that token. + AccountsLoaded(Vec<(String, bool, Option)>), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OAuthService { + GitHub, + GitLab, +} + +/// A step sent by the background task of a GitHub sign-in. +#[derive(Debug, Clone)] +pub enum GithubSignInEvent { + /// GitHub gave the code to enter on its verification page. + Code { + user_code: String, + verification_uri: String, + }, + /// The sign-in ended: accepted, refused, expired or cancelled. + Finished(OAuthResult), +} + +/// A GitHub sign-in in progress (device flow). +#[derive(Debug, Clone)] +struct GithubSignIn { + /// The attempt's id: steps of a cancelled attempt are dropped. + id: u64, + /// The code and verification page, once GitHub sent them. + code: Option<(String, String)>, + /// Dropping it stops the background wait for the token. + _cancel: Sender<()>, +} + +#[derive(Debug, Clone)] +pub struct Accounts { + auth: AuthManager, + github_status: Status, + gitlab_status: Status, + github_sign_in: Option, + next_github_sign_in: u64, + gitlab_in_progress: bool, + manual_host: String, + manual_token: String, + manual_status: Status, + manual_validating: bool, + custom_github_client_id: String, + custom_gitlab_client_id: String, + /// Saved accounts (host, OAuth, login), read again in the background after every change. + accounts: Vec<(String, bool, Option)>, + /// The error of the last disconnect. + accounts_status: Status, +} + +impl Accounts { + pub fn new(auth: AuthManager) -> Self { + Self { + auth, + github_status: None, + gitlab_status: None, + github_sign_in: None, + next_github_sign_in: 0, + gitlab_in_progress: false, + manual_host: String::new(), + manual_token: String::new(), + manual_status: None, + manual_validating: false, + custom_github_client_id: String::new(), + custom_gitlab_client_id: String::new(), + accounts: Vec::new(), + accounts_status: None, + } + } + + /// Replaces the auth manager and reads the accounts again. + pub fn set_auth_manager(&mut self, auth: AuthManager) -> Task { + self.auth = auth; + self.refresh_accounts() + } + + /// Reads the saved accounts off the UI thread: the host list reads a file and each + /// OAuth check asks the keyring. + pub fn refresh_accounts(&self) -> Task { + let auth = self.auth.clone(); + Task::perform( + async move { + tokio::task::spawn_blocking(move || { + auth.known_hosts() + .into_iter() + .filter(|host| !host.starts_with("oauth:")) + .map(|host| { + let oauth = auth.get_oauth_token(&host); + (host, oauth.is_some(), oauth.and_then(|token| token.login)) + }) + .collect() + }) + .await + .unwrap_or_default() + }, + Message::AccountsLoaded, + ) + } + + /// Whether an account is saved for `host`, as of the last account read. + pub fn is_connected(&self, host: &str) -> bool { + self.accounts.iter().any(|(saved, ..)| saved == host) + } + + fn status_mut(&mut self, service: OAuthService) -> &mut Status { + match service { + OAuthService::GitHub => &mut self.github_status, + OAuthService::GitLab => &mut self.gitlab_status, + } + } + + /// Ends an OAuth sign-in: the account name is read and the token saved in the background. + fn finish_oauth(&mut self, service: OAuthService, result: OAuthResult) -> Task { + let status = match result { + OAuthResult::Success(mut token) => { + *self.status_mut(service) = Some(("prefs_signin_saving", String::new())); + let auth = self.auth.clone(); + return Task::perform( + async move { + token.login = + crate::auth::fetch_login(&token.host, &token.access_token).await; + tokio::task::spawn_blocking(move || auth.store_oauth_token(&token)) + .await + .unwrap_or_else(|err| Err(err.to_string())) + }, + move |result| Message::OAuthStored(service, result), + ); + } + OAuthResult::Cancelled => ("prefs_signin_cancelled", String::new()), + OAuthResult::Error(e) => ("prefs_signin_failed", e), + }; + *self.status_mut(service) = Some(status); + Task::none() + } + + pub fn update(&mut self, message: Message) -> Task { + match message { + Message::StartGithubOAuth => { + let Some(client_id) = client_id(GITHUB_CLIENT_ID, &self.custom_github_client_id) + else { + self.github_status = Some(("prefs_no_client_id", String::new())); + return Task::none(); + }; + + let id = self.next_github_sign_in; + self.next_github_sign_in += 1; + let (cancel, cancelled) = mpsc::channel(); + self.github_status = None; + self.github_sign_in = Some(GithubSignIn { + id, + code: None, + _cancel: cancel, + }); + + Task::run( + github_device_flow(OAuthProvider::github(&client_id), cancelled), + move |event| Message::GithubSignIn(id, event), + ) + } + + Message::StartGitlabOAuth => { + let Some(client_id) = client_id(GITLAB_CLIENT_ID, &self.custom_gitlab_client_id) + else { + self.gitlab_status = Some(("prefs_no_client_id", String::new())); + return Task::none(); + }; + + self.gitlab_status = Some(("prefs_gitlab_opening", String::new())); + self.gitlab_in_progress = true; + + let auth = self.auth.clone(); + let provider = OAuthProvider::gitlab(&client_id); + + Task::perform( + tokio::task::spawn_blocking(move || auth.start_oauth(provider)), + |result| match result { + Ok(oauth_result) => Message::GitlabOAuthResult(oauth_result), + Err(err) => Message::GitlabOAuthResult(OAuthResult::Error(err.to_string())), + }, + ) + } + + Message::GithubSignIn(id, event) => { + if self.github_sign_in.as_ref().map(|sign_in| sign_in.id) != Some(id) { + return Task::none(); + } + let result = match event { + GithubSignInEvent::Code { + user_code, + verification_uri, + } => { + if let Some(sign_in) = &mut self.github_sign_in { + sign_in.code = Some((user_code, verification_uri)); + } + return Task::none(); + } + GithubSignInEvent::Finished(result) => result, + }; + self.github_sign_in = None; + self.finish_oauth(OAuthService::GitHub, result) + } + + Message::CancelGithubSignIn => { + // Dropping the attempt closes its cancel channel and stops the wait. + self.github_sign_in = None; + self.github_status = Some(("prefs_signin_cancelled", String::new())); + Task::none() + } + + Message::CopyGithubCode => match self.github_code() { + Some((user_code, _)) => iced::clipboard::write(user_code.to_string()), + None => Task::none(), + }, + + Message::OpenGithubVerification => { + if let Some((_, verification_uri)) = self.github_code() { + if let Err(err) = webbrowser::open(verification_uri) { + self.github_status = Some(("prefs_browser_failed", err.to_string())); + } + } + Task::none() + } + + Message::GitlabOAuthResult(result) => { + self.gitlab_in_progress = false; + self.finish_oauth(OAuthService::GitLab, result) + } + + Message::OAuthStored(service, result) => { + *self.status_mut(service) = Some(match result { + Ok(()) => ("prefs_signin_done", String::new()), + Err(e) => ("prefs_token_store_failed", e), + }); + self.refresh_accounts() + } + + Message::ManualHostChanged(value) => { + self.manual_host = value; + Task::none() + } + + Message::ManualTokenChanged(value) => { + self.manual_token = value; + Task::none() + } + + Message::ValidateAndSave => { + let host = self.manual_host.trim().to_string(); + let token = self.manual_token.trim().to_string(); + + if host.is_empty() || token.is_empty() { + self.manual_status = Some(("prefs_token_empty", String::new())); + return Task::none(); + } + + self.manual_status = Some(("prefs_token_checking", String::new())); + self.manual_validating = true; + + let auth = self.auth.clone(); + Task::perform( + async move { auth.validate_and_store(&host, &token).await }, + Message::ValidationResult, + ) + } + + Message::ValidationResult(result) => { + self.manual_validating = false; + match result { + Ok(()) => { + self.manual_status = Some(("prefs_token_saved", String::new())); + self.manual_token.clear(); + return self.refresh_accounts(); + } + Err(e) => { + self.manual_status = Some(("prefs_token_rejected", e)); + } + } + Task::none() + } + + Message::GithubClientIdChanged(value) => { + self.custom_github_client_id = value; + Task::none() + } + + Message::GitlabClientIdChanged(value) => { + self.custom_gitlab_client_id = value; + Task::none() + } + + Message::Disconnect(host) => { + self.accounts_status = None; + let auth = self.auth.clone(); + Task::perform( + async move { + tokio::task::spawn_blocking(move || { + // An OAuth account removes its OAuth token, any other its plain one. + if auth.has_oauth(&host) { + auth.clear_oauth_token(&host) + } else { + auth.clear_token(&host) + } + }) + .await + .unwrap_or_else(|err| Err(err.to_string())) + }, + Message::Disconnected, + ) + } + + Message::Disconnected(result) => { + if let Err(e) = result { + self.accounts_status = Some(("prefs_disconnect_failed", e)); + } + self.refresh_accounts() + } + + Message::AccountsLoaded(accounts) => { + self.accounts = accounts; + Task::none() + } + } + } + + /// The GitHub code waiting to be entered, and its verification page. + fn github_code(&self) -> Option<(&str, &str)> { + let (user_code, verification_uri) = self.github_sign_in.as_ref()?.code.as_ref()?; + Some((user_code, verification_uri)) + } + + // ─── View ───────────────────────────────────────────────────────── + + /// One card per saved account, with its Disconnect button. + pub fn cards(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let mut cards = Column::new().spacing(8); + if self.accounts.is_empty() { + cards = cards.push(muted(&typo, t("prefs_accounts_none"))); + } + for (host, oauth, login) in &self.accounts { + let how = account_detail(*oauth, login.as_deref()); + let card = row![ + avatar(&provider_initials(host), avatar_accent(host), 30.0), + column![ + text(host.clone()) + .size(typo.sz(13)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()), + text(how) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + ] + .spacing(2) + .width(Length::Fill), + chip(t("prefs_connected"), Tone::Success), + gs_button::danger( + t("prefs_disconnect"), + Some(Message::Disconnect(host.clone())) + ), + ] + .spacing(12) + .align_y(Alignment::Center); + cards = cards.push( + container(card) + .padding([12, 14]) + .style(|_| container::Style { + background: Some(Palette::BG_SIDEBAR().into()), + border: Border::default().rounded(10), + ..Default::default() + }), + ); + } + cards = push_status(cards, &typo, &self.accounts_status); + cards.into() + } + + /// Sign in to GitHub: the start button, or the code with Copy, Open and Cancel. + pub fn github(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let body = match &self.github_sign_in { + None => { + let available = client_id(GITHUB_CLIENT_ID, &self.custom_github_client_id); + let start = column![gs_button::primary( + t("prefs_github_start"), + available.as_ref().map(|_| Message::StartGithubOAuth), + )]; + match available { + Some(_) => start, + None => start.push(dimmer(&typo, t("prefs_no_client_id"))), + } + } + Some(GithubSignIn { code: None, .. }) => column![row![ + muted(&typo, t("prefs_github_requesting")), + gs_button::secondary(t("prefs_cancel"), Some(Message::CancelGithubSignIn)), + ] + .spacing(12) + .align_y(Alignment::Center)], + Some(GithubSignIn { + code: Some((user_code, verification_uri)), + .. + }) => { + let code = container( + text(user_code.clone()) + .size(typo.sz(22)) + .font(typo.bold) + .color(Palette::TEXT_PRIMARY()), + ) + .padding([10, 16]) + .style(|_| container::Style { + background: Some(Palette::BG_SIDEBAR().into()), + border: Border::default().rounded(8), + ..Default::default() + }); + column![ + muted( + &typo, + &tf("prefs_github_enter_code", &[("uri", verification_uri)]) + ), + row![ + code, + gs_button::secondary(t("prefs_copy"), Some(Message::CopyGithubCode)), + gs_button::primary( + t("prefs_open_github"), + Some(Message::OpenGithubVerification) + ), + gs_button::secondary(t("prefs_cancel"), Some(Message::CancelGithubSignIn)), + ] + .spacing(10) + .align_y(Alignment::Center), + dimmer(&typo, t("prefs_github_waiting")), + ] + } + }; + push_status(body.spacing(10), &typo, &self.github_status).into() + } + + /// Sign in to GitLab: the browser sign-in button and its status. + pub fn gitlab(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let has_id = client_id(GITLAB_CLIENT_ID, &self.custom_gitlab_client_id).is_some(); + let mut body = column![gs_button::primary( + t("prefs_gitlab_start"), + (has_id && !self.gitlab_in_progress).then_some(Message::StartGitlabOAuth), + )] + .spacing(10); + if !has_id { + body = body.push(dimmer(&typo, t("prefs_no_client_id"))); + } + push_status(body, &typo, &self.gitlab_status).into() + } + + /// Add a token: host and token fields, then Validate and save. + pub fn token(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let can_save = !self.manual_host.trim().is_empty() + && !self.manual_token.trim().is_empty() + && !self.manual_validating; + let body = column![ + field( + text_input(t("prefs_token_host"), &self.manual_host) + .on_input(Message::ManualHostChanged), + None, + ), + field( + text_input(t("prefs_token_value"), &self.manual_token) + .on_input(Message::ManualTokenChanged) + .secure(true), + None, + ), + gs_button::primary( + t("prefs_token_save"), + can_save.then_some(Message::ValidateAndSave) + ), + ] + .spacing(10); + push_status(body, &typo, &self.manual_status).into() + } + + /// OAuth app client IDs: one field per provider. + pub fn client_ids(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let mut body = column![ + field( + text_input(t("prefs_github_client_id"), &self.custom_github_client_id) + .on_input(Message::GithubClientIdChanged), + None, + ), + field( + text_input(t("prefs_gitlab_client_id"), &self.custom_gitlab_client_id) + .on_input(Message::GitlabClientIdChanged), + None, + ), + ] + .spacing(10); + if GITHUB_CLIENT_ID.is_some() || GITLAB_CLIENT_ID.is_some() { + body = body.push(dimmer(&typo, t("prefs_client_ids_built_in"))); + } + body.into() + } +} + +/// The client ID to sign in with: the built-in one, else the one typed in Preferences. +fn client_id(built_in: Option<&str>, typed: &str) -> Option { + built_in + .map(str::to_string) + .or_else(|| Some(typed.trim().to_string()).filter(|id| !id.is_empty())) +} + +/// The line under an account's host: the account name for an OAuth sign-in when it is +/// known, else how the account signs in. +fn account_detail(oauth: bool, login: Option<&str>) -> String { + match (oauth, login) { + (true, Some(user)) => tf("prefs_account_oauth_user", &[("user", user)]), + (true, None) => t("prefs_account_oauth").to_string(), + (false, _) => t("prefs_account_token").to_string(), + } +} + +/// "GH" for GitHub, "GL" for GitLab, else the host's own initials. +fn provider_initials(host: &str) -> String { + if host.contains("github") { + "GH".to_string() + } else if host.contains("gitlab") { + "GL".to_string() + } else { + initials(host) + } +} + +fn muted<'a>(typo: &Typography, label: &str) -> Element<'a, Message> { + text(label.to_string()) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_MUTED()) + .into() +} + +fn dimmer<'a>(typo: &Typography, label: &str) -> Element<'a, Message> { + text(label.to_string()) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .into() +} + +fn push_status<'a>( + body: Column<'a, Message>, + typo: &Typography, + status: &Status, +) -> Column<'a, Message> { + match status { + Some((key, detail)) => body.push(muted(typo, &tf(key, &[("error", detail)]))), + None => body, + } +} + +/// GitHub sign-in by device flow: asks for a code, sends it to the UI, then waits until the +/// user accepts or refuses it, the code expires or `cancelled` is closed. +fn github_device_flow( + provider: OAuthProvider, + cancelled: Receiver<()>, +) -> impl Stream { + iced::stream::channel(2, async move |mut output| { + let flow = match tokio::task::spawn_blocking(move || DeviceFlow::start(provider)).await { + Ok(Ok(flow)) => flow, + Ok(Err(err)) => { + let _ = output + .send(GithubSignInEvent::Finished(OAuthResult::Error(err))) + .await; + return; + } + Err(err) => { + let _ = output + .send(GithubSignInEvent::Finished(OAuthResult::Error( + err.to_string(), + ))) + .await; + return; + } + }; + let _ = output + .send(GithubSignInEvent::Code { + user_code: flow.user_code().to_string(), + verification_uri: flow.verification_uri().to_string(), + }) + .await; + let result = tokio::task::spawn_blocking(move || flow.wait(&cancelled)) + .await + .unwrap_or_else(|err| OAuthResult::Error(err.to_string())); + let _ = output.send(GithubSignInEvent::Finished(result)).await; + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn built_in_client_id_wins_and_blank_ids_do_not_count() { + assert_eq!(client_id(Some("built"), "typed").as_deref(), Some("built")); + assert_eq!(client_id(None, " typed ").as_deref(), Some("typed")); + assert_eq!(client_id(None, " "), None); + assert_eq!(provider_initials("github.com"), "GH"); + assert_eq!(provider_initials("gitlab.example.com"), "GL"); + assert_eq!(provider_initials("gitea.example.com"), "GE"); + } + + #[test] + fn oauth_cards_name_the_signed_in_user() { + assert!(account_detail(true, Some("MotherSphere")).starts_with("MotherSphere")); + // Without a saved name the line still says how the account signs in. + assert!(!account_detail(true, None).contains("MotherSphere")); + assert_ne!(account_detail(true, None), account_detail(false, None)); + } +} diff --git a/src/ui/preferences/git.rs b/src/ui/preferences/git.rs new file mode 100644 index 0000000..ba7ca3b --- /dev/null +++ b/src/ui/preferences/git.rs @@ -0,0 +1,152 @@ +//! Preferences → Git: cloning, background fetch, pinned branches and logs. + +use colony_ui::theme::Palette; +use colony_ui::widgets::{category_heading, dropdown, functional_toggle, setting_row}; +use colony_ui::Typography; +use iced::widget::{container, row, space, text, text_input, Column}; +use iced::{Alignment, Length}; + +use super::{Message, PreferencesPage, FETCH_INTERVALS}; +use crate::config::{ + LoggingOptions, Preferences, MAX_LOG_RETENTION_FILES, MIN_LOG_RETENTION_FILES, +}; +use crate::i18n::{t, tf}; +use crate::ui::changes::field; +use crate::ui::widgets::button as gs_button; + +pub(super) fn view<'a>( + page: &'a PreferencesPage, + typo: &Typography, + prefs: &'a Preferences, + logging: &LoggingOptions, +) -> Column<'a, Message> { + let folder = page + .clone_path + .as_deref() + .unwrap_or(prefs.default_clone_path()); + let cloning = Column::new() + .push(setting_row( + typo, + t("prefs_default_folder"), + t("prefs_default_folder_desc"), + row![ + container(field( + text_input("", folder) + .on_input(Message::ClonePathChanged) + .on_submit(Message::ClonePathSubmitted), + None, + )) + .width(280), + gs_button::secondary(t("prefs_browse"), Some(Message::BrowseClonePath)), + ] + .spacing(8) + .align_y(Alignment::Center), + )) + .push(functional_toggle( + typo, + t("prefs_scan_folder"), + t("prefs_scan_folder_desc"), + prefs.scan_clone_folder(), + Message::ScanCloneFolder(!prefs.scan_clone_folder()), + )); + + let intervals = FETCH_INTERVALS.map(|minutes| { + ( + minutes, + tf("prefs_minutes", &[("count", &minutes.to_string())]), + ) + }); + let fetch = Column::new() + .push(functional_toggle( + typo, + t("prefs_fetch"), + t("prefs_fetch_toggle_desc"), + prefs.auto_fetch_enabled(), + Message::AutoFetch(!prefs.auto_fetch_enabled()), + )) + .push(setting_row( + typo, + t("prefs_fetch_interval"), + t("prefs_fetch_interval_desc"), + dropdown( + typo, + intervals, + &prefs.auto_fetch_interval_minutes(), + Message::FetchInterval, + ), + )); + + let mut pinned = Column::new().spacing(4); + if prefs.pinned_branches().is_empty() { + pinned = pinned.push( + text(t("prefs_pinned_none")) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_MUTED()), + ); + } + for branch in prefs.pinned_branches() { + pinned = pinned.push( + row![ + text(branch.clone()) + .size(typo.sz(13)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()), + space().width(Length::Fill), + gs_button::ghost(t("prefs_unpin"), Some(Message::Unpin(branch.clone()))), + ] + .padding([2, 4]) + .align_y(Alignment::Center), + ); + } + + let kept = + (MIN_LOG_RETENTION_FILES..=MAX_LOG_RETENTION_FILES).map(|files| (files, files.to_string())); + let logs = Column::new() + .spacing(8) + .push(setting_row( + typo, + t("prefs_logs_kept"), + t("prefs_logs_kept_desc"), + dropdown( + typo, + kept, + &logging.retention_files(), + Message::LogRetention, + ), + )) + .push(gs_button::secondary( + t("prefs_open_logs"), + Some(Message::OpenFolder(page.logs_dir.clone())), + )); + + category_heading(typo, t("prefs_cat_git"), t("prefs_git_desc")) + .push(page.section( + typo, + "cloning", + t("prefs_section_cloning"), + t("prefs_cloning_desc"), + cloning, + )) + .push(page.section( + typo, + "fetch", + t("prefs_section_fetch"), + t("prefs_fetch_desc"), + fetch, + )) + .push(page.section( + typo, + "pinned", + t("prefs_section_pinned"), + t("prefs_pinned_desc"), + pinned, + )) + .push(page.section( + typo, + "logs", + t("prefs_section_logs"), + t("prefs_logs_desc"), + logs, + )) +} diff --git a/src/ui/preferences/mod.rs b/src/ui/preferences/mod.rs new file mode 100644 index 0000000..6c3575c --- /dev/null +++ b/src/ui/preferences/mod.rs @@ -0,0 +1,587 @@ +//! The Preferences page, built on the colony-ui kit: General, Appearance and Accessibility +//! from the kit, then GitSpace's Accounts, Git and Network, then About. +//! +//! There is no Save button: every message changes the preferences the app hands in, and +//! the app applies and saves them as soon as `update` returns. + +mod about; +pub mod accounts; +mod git; +mod network; + +use std::collections::HashSet; +use std::ops::Range; +use std::path::PathBuf; + +use colony_ui::preferences::Change; +use colony_ui::theme::Palette; +use colony_ui::widgets::{ + category_heading, category_list, collapsible_section, dropdown, functional_toggle, nav_label, + preferences_page, section_description, setting_row, PreferencesView, ABOUT_CATEGORY, + STANDARD_CATEGORIES, +}; +use colony_ui::Typography; +use iced::widget::{column, container, row, text, Column}; +use iced::{Alignment, Element, Padding, Task}; + +use crate::auth::AuthManager; +use crate::config::{Language, LoggingOptions, Preferences}; +use crate::i18n::{t, tf}; +use crate::ui::repo_header::open_folder; +use crate::ui::widgets::button as gs_button; +use crate::ui::widgets::toast::Toast; + +/// Category keys, in the order the list shows them. +pub const CATEGORIES: [&str; 7] = [ + STANDARD_CATEGORIES[0], + STANDARD_CATEGORIES[1], + STANDARD_CATEGORIES[2], + "prefs_cat_accounts", + "prefs_cat_git", + "prefs_cat_network", + ABOUT_CATEGORY, +]; +const ACCOUNTS: usize = 3; +/// GitSpace's own categories, listed under the "GitSpace" separator. +const GITSPACE: Range = 3..6; + +/// Background fetch intervals offered, in minutes. +pub const FETCH_INTERVALS: [u64; 5] = [1, 5, 15, 30, 60]; + +#[derive(Debug, Clone)] +pub enum Message { + /// Opens or closes the page; a clone folder typed without Enter is applied first. + Toggle, + Category(usize), + /// Opens or closes a collapsible section, by key. + Section(&'static str), + Standard(Change), + Language(Language), + ReopenLastRepo(bool), + ImportSettings, + /// `None` when the file dialog was cancelled. + ImportResult(Result, String>), + ExportSettings, + /// The path written, or `None` when the file dialog was cancelled. + ExportResult(Result, String>), + ResetDefaults, + ConfirmReset, + CancelReset, + + Accounts(accounts::Message), + EncryptedTokens(bool), + + ClonePathChanged(String), + ClonePathSubmitted, + BrowseClonePath, + BrowseClonePathResult(Option), + ScanCloneFolder(bool), + AutoFetch(bool), + FetchInterval(u64), + Unpin(String), + LogRetention(usize), + + HttpProxy(String), + HttpsProxy(String), + IdleTimeout(String), + PreferHttps(bool), + AllowSsh(bool), + + OpenFolder(PathBuf), + Copy(String), + OpenUrl(&'static str), +} + +pub struct PreferencesPage { + pub category: usize, + /// Keys of the open sections. All closed each time the page opens. + pub expanded: HashSet, + open: bool, + pub accounts: accounts::Accounts, + /// A typed clone folder not applied yet: it applies on Enter or when the page closes, + /// so a half-typed path never starts a folder scan. + clone_path: Option, + /// The idle timeout as typed; only a valid number reaches the preferences. + idle_timeout: Option, + confirm_reset: bool, + config_dir: PathBuf, + logs_dir: PathBuf, +} + +impl PreferencesPage { + pub fn new(auth: AuthManager) -> Self { + let (config_dir, data_dir) = crate::paths::effective_dirs(); + Self { + category: 0, + expanded: HashSet::new(), + open: false, + accounts: accounts::Accounts::new(auth), + clone_path: None, + idle_timeout: None, + confirm_reset: false, + config_dir, + logs_dir: data_dir.join("logs"), + } + } + + pub fn is_open(&self) -> bool { + self.open + } + + /// Opens or closes the page: the identity button, Close, Ctrl+, and Escape. + fn toggle(&mut self) { + self.open = !self.open; + if self.open { + self.expanded.clear(); + self.clone_path = None; + self.idle_timeout = None; + self.confirm_reset = false; + } + } + + /// Saves the clone folder typed but not applied yet. + fn apply_clone_path(&mut self, prefs: &mut Preferences) { + if let Some(path) = self.clone_path.take() { + prefs.set_default_clone_path(path); + } + } + + /// Opens the page on Accounts. + pub fn open_accounts(&mut self) { + if !self.open { + self.toggle(); + } + self.category = ACCOUNTS; + } + + /// Changes `prefs` and `logging` in place; the app saves whatever changed. + pub fn update( + &mut self, + message: Message, + prefs: &mut Preferences, + logging: &mut LoggingOptions, + ) -> (Task, Option) { + let mut task = Task::none(); + let mut toast = None; + match message { + Message::Toggle => { + if self.open { + self.apply_clone_path(prefs); + } + self.toggle(); + } + Message::Category(index) => self.category = index.min(CATEGORIES.len() - 1), + Message::Section(key) => { + if !self.expanded.remove(key) { + self.expanded.insert(key.to_string()); + } + } + // `update` also applies the change. + Message::Standard(change) => prefs.standard.update(change), + Message::Language(language) => set_language(prefs, language), + Message::ReopenLastRepo(on) => prefs.set_reopen_last_repo(on), + Message::ImportSettings => { + task = Task::perform( + tokio::task::spawn_blocking(|| { + rfd::FileDialog::new() + .add_filter("JSON", &["json"]) + .pick_file() + .map(|path| Preferences::from_path(&path).map_err(|e| e.to_string())) + .transpose() + }), + |result| Message::ImportResult(result.unwrap_or_else(|e| Err(e.to_string()))), + ) + } + Message::ImportResult(Ok(Some(imported))) => { + *prefs = imported; + self.clone_path = None; + self.idle_timeout = None; + toast = Some(Toast::success(t("prefs_imported"))); + } + Message::ImportResult(Ok(None)) | Message::ExportResult(Ok(None)) => {} + Message::ImportResult(Err(err)) => { + toast = Some(Toast::error(t("prefs_import_failed"), err)); + } + Message::ExportSettings => { + let current = prefs.clone(); + task = Task::perform( + tokio::task::spawn_blocking(move || { + rfd::FileDialog::new() + .add_filter("JSON", &["json"]) + .set_file_name("gitspace-preferences.json") + .save_file() + .map(|path| { + current + .save_to_path(&path) + .map(|_| path.display().to_string()) + .map_err(|e| e.to_string()) + }) + .transpose() + }), + |result| Message::ExportResult(result.unwrap_or_else(|e| Err(e.to_string()))), + ) + } + Message::ExportResult(Ok(Some(path))) => { + toast = Some(Toast::success(tf("prefs_exported", &[("path", &path)]))); + } + Message::ExportResult(Err(err)) => { + toast = Some(Toast::error(t("prefs_export_failed"), err)); + } + Message::ResetDefaults => self.confirm_reset = true, + Message::CancelReset => self.confirm_reset = false, + Message::ConfirmReset => { + *prefs = Preferences::default(); + *logging = LoggingOptions::default(); + self.confirm_reset = false; + self.clone_path = None; + self.idle_timeout = None; + } + + Message::Accounts(msg) => task = self.accounts.update(msg).map(Message::Accounts), + Message::EncryptedTokens(on) => prefs.set_allow_encrypted_tokens(on), + + Message::ClonePathChanged(path) => self.clone_path = Some(path), + Message::ClonePathSubmitted => self.apply_clone_path(prefs), + Message::BrowseClonePath => { + task = Task::perform( + tokio::task::spawn_blocking(|| { + rfd::FileDialog::new() + .pick_folder() + .map(|path| path.display().to_string()) + }), + |result| Message::BrowseClonePathResult(result.ok().flatten()), + ) + } + Message::BrowseClonePathResult(Some(path)) => { + self.clone_path = None; + prefs.set_default_clone_path(path); + } + Message::BrowseClonePathResult(None) => {} + Message::ScanCloneFolder(on) => prefs.set_scan_clone_folder(on), + Message::AutoFetch(on) => prefs.set_auto_fetch_enabled(on), + Message::FetchInterval(minutes) => prefs.set_auto_fetch_interval_minutes(minutes), + Message::Unpin(branch) => { + let kept = prefs + .pinned_branches() + .iter() + .filter(|name| **name != branch) + .cloned() + .collect(); + prefs.set_pinned_branches(kept); + } + Message::LogRetention(files) => logging.set_retention_files(files), + + Message::HttpProxy(proxy) => prefs.network_mut().http_proxy = proxy, + Message::HttpsProxy(proxy) => prefs.network_mut().https_proxy = proxy, + Message::IdleTimeout(typed) => { + if let Some(secs) = typed.trim().parse::().ok().filter(|secs| *secs > 0) { + prefs.network_mut().network_timeout_secs = secs; + } + self.idle_timeout = Some(typed); + } + Message::PreferHttps(on) => prefs.network_mut().use_https = on, + Message::AllowSsh(on) => prefs.network_mut().allow_ssh = on, + + Message::OpenFolder(path) => { + let path = path.display().to_string(); + if let Err(err) = open_folder(&path) { + toast = Some(Toast::error( + t("open_folder_failed"), + format!("{path}: {err}"), + )); + } + } + Message::Copy(value) => task = iced::clipboard::write(value), + Message::OpenUrl(url) => { + if let Err(err) = webbrowser::open(url) { + toast = Some(Toast::error( + t("prefs_open_link_failed"), + format!("{url}: {err}"), + )); + } + } + } + (task, toast) + } + + // ─── View ───────────────────────────────────────────────────────── + + /// The whole page. `on_close` is the message the identity button sends. + pub fn view<'a, M: Clone + 'a>( + &'a self, + prefs: &'a Preferences, + logging: &'a LoggingOptions, + wrap: fn(Message) -> M, + on_close: M, + ) -> Element<'a, M> { + let typo = Typography::current(); + let kit = PreferencesView::new( + typo, + &prefs.standard, + &self.expanded, + Message::Standard, + Message::Section, + ); + let content: Column<'a, Message> = match self.category { + 0 => self.general(&typo, kit.general(), prefs), + 1 => kit.appearance(), + 2 => kit.accessibility(), + 3 => self.accounts_view(&typo, prefs), + 4 => git::view(self, &typo, prefs, logging), + 5 => network::view(self, &typo, prefs), + _ => about::view(self, &typo), + }; + preferences_page( + &typo, + Element::from(self.categories(&typo)).map(wrap), + Element::from(content).map(wrap), + on_close, + ) + } + + /// The kit's category lists, with GitSpace's own under a separator and About apart. + fn categories<'a>(&self, typo: &Typography) -> Column<'a, Message> { + let list = |range: Range| { + let start = range.start; + category_list( + typo, + CATEGORIES[range].iter().map(|key| category_label(key)), + self.category.wrapping_sub(start), + move |index| Message::Category(start + index), + ) + }; + let gap = |top, label: &str| { + container(nav_label(typo, label)).padding(Padding { + top, + right: 0.0, + bottom: 4.0, + left: 10.0, + }) + }; + column![ + list(0..GITSPACE.start), + gap(12.0, t("prefs_cat_gitspace")), + list(GITSPACE), + gap(8.0, ""), + list(GITSPACE.end..CATEGORIES.len()), + ] + } + + /// A collapsible section: its description, then `body`. + fn section<'a>( + &self, + typo: &Typography, + key: &'static str, + title: &str, + description: &str, + body: impl Into>, + ) -> Element<'a, Message> { + collapsible_section( + typo, + title, + self.expanded.contains(key), + Message::Section(key), + column![section_description(typo, description), body.into()].into(), + ) + } + + /// The kit's General heading, then Language, Startup and the preferences file. + fn general<'a>( + &self, + typo: &Typography, + heading: Column<'a, Message>, + prefs: &Preferences, + ) -> Column<'a, Message> { + let languages = [ + (Language::System, t("prefs_language_system").to_string()), + (Language::English, t("prefs_language_english").to_string()), + (Language::French, t("prefs_language_french").to_string()), + ]; + let language = setting_row( + typo, + t("prefs_language"), + t("prefs_language_row_desc"), + dropdown(typo, languages, &prefs.language(), Message::Language), + ); + let reopen = functional_toggle( + typo, + t("prefs_reopen_last"), + t("prefs_reopen_last_desc"), + prefs.reopen_last_repo(), + Message::ReopenLastRepo(!prefs.reopen_last_repo()), + ); + let reset: Element<'a, Message> = if self.confirm_reset { + row![ + text(t("prefs_reset_confirm")) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()), + gs_button::danger(t("prefs_reset_yes"), Some(Message::ConfirmReset)), + gs_button::secondary(t("prefs_cancel"), Some(Message::CancelReset)), + ] + .spacing(10) + .align_y(Alignment::Center) + .into() + } else { + gs_button::danger(t("prefs_reset"), Some(Message::ResetDefaults)) + }; + let file = column![ + row![ + gs_button::secondary(t("prefs_import"), Some(Message::ImportSettings)), + gs_button::secondary(t("prefs_export"), Some(Message::ExportSettings)), + ] + .spacing(10), + reset, + ] + .spacing(12); + + heading + .push(self.section( + typo, + "language", + t("prefs_section_language"), + t("prefs_language_desc"), + language, + )) + .push(self.section( + typo, + "startup", + t("prefs_section_startup"), + t("prefs_startup_desc"), + reopen, + )) + .push(self.section( + typo, + "file", + t("prefs_section_file"), + t("prefs_file_desc"), + file, + )) + } + + /// Accounts: the saved accounts as cards, then the sign-in and token sections. + fn accounts_view<'a>(&'a self, typo: &Typography, prefs: &Preferences) -> Column<'a, Message> { + let accounts = &self.accounts; + let storage = functional_toggle( + typo, + t("prefs_encrypted_fallback"), + t("prefs_encrypted_fallback_desc"), + prefs.allow_encrypted_tokens(), + Message::EncryptedTokens(!prefs.allow_encrypted_tokens()), + ); + category_heading(typo, t("prefs_cat_accounts"), t("prefs_accounts_desc")) + .push(accounts.cards().map(Message::Accounts)) + .push(self.section( + typo, + "github", + t("prefs_section_github"), + t("prefs_github_desc"), + accounts.github().map(Message::Accounts), + )) + .push(self.section( + typo, + "gitlab", + t("prefs_section_gitlab"), + t("prefs_gitlab_desc"), + accounts.gitlab().map(Message::Accounts), + )) + .push(self.section( + typo, + "token", + t("prefs_section_token"), + t("prefs_token_desc"), + accounts.token().map(Message::Accounts), + )) + .push(self.section( + typo, + "storage", + t("prefs_section_storage"), + t("prefs_storage_desc"), + storage, + )) + .push(self.section( + typo, + "client_ids", + t("prefs_section_client_ids"), + t("prefs_client_ids_desc"), + accounts.client_ids().map(Message::Accounts), + )) + } +} + +/// The kit translates its own category names; GitSpace's come from its table. +fn category_label(key: &str) -> &'static str { + if key.starts_with("settings_") { + colony_ui::i18n::t(key) + } else { + t(key) + } +} + +/// Stores the language and switches both label tables to it at once. +fn set_language(prefs: &mut Preferences, language: Language) { + prefs.set_language(language); + colony_ui::i18n::set_locale(language.locale()); +} + +#[cfg(test)] +mod tests { + use super::*; + use colony_ui::i18n::Locale; + + #[test] + fn categories_are_in_colony_order() { + let [general, appearance, accessibility] = STANDARD_CATEGORIES; + assert_eq!( + CATEGORIES.to_vec(), + [ + general, + appearance, + accessibility, + "prefs_cat_accounts", + "prefs_cat_git", + "prefs_cat_network", + ABOUT_CATEGORY, + ] + ); + assert_eq!(CATEGORIES[ACCOUNTS], "prefs_cat_accounts"); + // Every label is translated, by the kit or by GitSpace's table. + for key in CATEGORIES.iter().chain(["prefs_cat_gitspace"].iter()) { + assert_ne!(category_label(key), *key); + } + } + + #[test] + fn closing_the_page_applies_a_typed_clone_folder() { + let dir = tempfile::tempdir().expect("tempdir"); + let mut page = PreferencesPage::new(AuthManager::in_dir(dir.path())); + let mut prefs = Preferences::default(); + let mut logging = LoggingOptions::default(); + for message in [ + Message::Toggle, + Message::ClonePathChanged("/tmp/gitspace-clones".to_string()), + Message::Toggle, + ] { + let _ = page.update(message, &mut prefs, &mut logging); + } + assert!(!page.is_open()); + assert_eq!(prefs.default_clone_path(), "/tmp/gitspace-clones"); + } + + #[test] + fn interval_choices_are_the_spec_values() { + assert_eq!(FETCH_INTERVALS.to_vec(), [1, 5, 15, 30, 60]); + } + + #[test] + fn language_change_sets_the_locale() { + let mut prefs = Preferences::default(); + set_language(&mut prefs, Language::French); + // Read and put back at once: the locale is shared with tests running alongside. + let seen = colony_ui::i18n::locale(); + set_language(&mut prefs, Language::English); + assert_eq!(seen, Locale::Fr); + assert_eq!(colony_ui::i18n::locale(), Locale::En); + assert_eq!(prefs.language(), Language::English); + } +} diff --git a/src/ui/preferences/network.rs b/src/ui/preferences/network.rs new file mode 100644 index 0000000..14f3bc6 --- /dev/null +++ b/src/ui/preferences/network.rs @@ -0,0 +1,90 @@ +//! Preferences → Network: proxies, the idle timeout and the allowed protocols. + +use colony_ui::widgets::{category_heading, functional_toggle, setting_row}; +use colony_ui::Typography; +use iced::widget::{container, text_input, Column}; + +use super::{Message, PreferencesPage}; +use crate::config::Preferences; +use crate::i18n::t; +use crate::ui::changes::field; + +pub(super) fn view<'a>( + page: &'a PreferencesPage, + typo: &Typography, + prefs: &'a Preferences, +) -> Column<'a, Message> { + let network = prefs.network(); + let input = |placeholder: &str, value: &str, on_input: fn(String) -> Message, width: f32| { + container(field( + text_input(placeholder, value).on_input(on_input), + None, + )) + .width(width) + }; + let proxy = Column::new() + .push(setting_row( + typo, + t("prefs_http_proxy"), + t("prefs_http_proxy_desc"), + input( + t("prefs_proxy_example"), + &network.http_proxy, + Message::HttpProxy, + 260.0, + ), + )) + .push(setting_row( + typo, + t("prefs_https_proxy"), + t("prefs_https_proxy_desc"), + input( + t("prefs_proxy_example"), + &network.https_proxy, + Message::HttpsProxy, + 260.0, + ), + )); + + let timeout = page + .idle_timeout + .clone() + .unwrap_or_else(|| network.network_timeout_secs.to_string()); + let connection = Column::new() + .push(setting_row( + typo, + t("prefs_idle_timeout"), + t("prefs_idle_timeout_desc"), + input("", &timeout, Message::IdleTimeout, 80.0), + )) + .push(functional_toggle( + typo, + t("prefs_prefer_https"), + t("prefs_prefer_https_desc"), + network.use_https, + Message::PreferHttps(!network.use_https), + )) + .push(functional_toggle( + typo, + t("prefs_allow_ssh"), + t("prefs_allow_ssh_desc"), + network.allow_ssh, + Message::AllowSsh(!network.allow_ssh), + )); + + category_heading(typo, t("prefs_cat_network"), t("prefs_network_desc")) + .push(page.section( + typo, + "proxy", + t("prefs_section_proxy"), + t("prefs_proxy_desc"), + proxy, + )) + .push(page.section( + typo, + "connection", + t("prefs_section_connection"), + t("prefs_connection_desc"), + connection, + )) +} diff --git a/src/ui/recent.rs b/src/ui/recent.rs deleted file mode 100644 index 9c0b17e..0000000 --- a/src/ui/recent.rs +++ /dev/null @@ -1,298 +0,0 @@ -//! Panneau des dépôts récents avec recherche et filtrage. -//! -//! Affiche la liste des dépôts récemment ouverts depuis la configuration, -//! avec un champ de recherche, un bouton de navigation et des raccourcis rapides. - -use std::collections::HashSet; -use std::path::Path; - -use iced::widget::{button, column, container, row, scrollable, text, text_input, Space}; -use iced::{Alignment, Element, Length, Task}; - -use crate::config::AppConfig; -use crate::ui::theme::Theme; - -/// État du panneau des dépôts récents. -#[derive(Debug, Clone)] -pub struct RecentList { - /// Texte saisi dans le champ de recherche (affiché immédiatement). - pub search: String, - /// Texte de recherche appliqué au filtrage (mis à jour après le délai). - pub search_applied: String, - /// Compteur de version pour le mécanisme de debounce. - pub search_debounce: u32, - /// Raccourcis d'accès rapide, calculés une fois au démarrage. - common_paths: Vec<(String, String)>, -} - -/// Messages émis par le panneau des dépôts récents. -#[derive(Debug, Clone)] -pub enum Message { - /// Le texte du champ de recherche a changé. - SearchChanged(String), - /// Applique le filtre de recherche après le délai de debounce. - DebouncedSearch(u32), - /// L'utilisateur a cliqué sur le bouton « Parcourir... ». - BrowseClicked, - /// L'utilisateur a sélectionné un dépôt dans la liste. - RepoSelected(String), - /// L'utilisateur a cliqué sur un raccourci d'accès rapide. - QuickAccessClicked(String), - /// Résultat du dialogue de sélection de dossier. - BrowseResult(Option), -} - -impl RecentList { - /// Crée une nouvelle instance du panneau. - pub fn new() -> Self { - Self { - search: String::new(), - search_applied: String::new(), - search_debounce: 0, - common_paths: common_paths(), - } - } - - /// Traite un message et renvoie une tâche Iced ainsi qu'un chemin - /// de dépôt sélectionné le cas échéant. - pub fn update(&mut self, message: Message) -> (Task, Option) { - match message { - Message::SearchChanged(value) => { - // Stocker le texte immédiatement pour l'affichage du champ - self.search = value; - // Incrémenter la version pour invalider les debounces précédents - self.search_debounce += 1; - let version = self.search_debounce; - // Retourner une tâche qui attend 250ms puis envoie DebouncedSearch - let task = Task::perform( - async move { - tokio::time::sleep(std::time::Duration::from_millis(250)).await; - }, - move |_| Message::DebouncedSearch(version), - ); - (task, None) - } - Message::DebouncedSearch(version) => { - // Appliquer uniquement si aucune frappe plus récente n'a eu lieu - if version == self.search_debounce { - self.search_applied = self.search.clone(); - } - (Task::none(), None) - } - Message::BrowseClicked => (pick_folder(None).map(Message::BrowseResult), None), - Message::BrowseResult(Some(path)) => { - self.search.clear(); - self.search_applied.clear(); - (Task::none(), Some(path)) - } - Message::BrowseResult(None) => (Task::none(), None), - Message::RepoSelected(path) => { - self.search.clear(); - self.search_applied.clear(); - (Task::none(), Some(path)) - } - Message::QuickAccessClicked(path) => { - self.search.clear(); - self.search_applied.clear(); - (Task::none(), Some(path)) - } - } - } - - /// Construit la vue Iced du panneau des dépôts récents. - pub fn view<'a>(&'a self, theme: &'a Theme, config: &'a AppConfig) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - // En-tête : titre et description. - let heading = text("Recently opened") - .size(typo.heading) - .color(palette.text_primary); - - let description = text("Search and reopen workspaces you've used recently.") - .size(typo.body) - .color(palette.text_secondary); - - // Barre de recherche et bouton parcourir. - let filter_label = text("Filter").size(typo.body).color(palette.text_secondary); - - let search_input = text_input("Type to filter by name or path", &self.search) - .on_input(Message::SearchChanged) - .width(Length::Fixed(320.0)); - - let browse_btn = button( - text("Browse...") - .size(typo.body) - .color(palette.text_primary), - ) - .on_press(Message::BrowseClicked); - - let filter_row = row![filter_label, search_input, browse_btn] - .spacing(theme.spacing.sm) - .align_y(Alignment::Center); - - // Contenu principal : liste des dépôts ou message d'état vide. - let content = if config.recent_repos().is_empty() { - self.view_empty_state(theme) - } else { - self.view_repo_list(theme, config) - }; - - let body = scrollable(content).width(Length::Fill).height(Length::Fill); - - // Assemblage final de la colonne. - column![ - heading, - description, - Space::with_height(8.0), - filter_row, - Space::with_height(8.0), - body - ] - .spacing(theme.spacing.xs) - .width(Length::Fill) - .into() - } - - /// Construit la liste filtrée des dépôts récents. - fn view_repo_list<'a>( - &'a self, - theme: &'a Theme, - config: &'a AppConfig, - ) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - let query = self.search_applied.to_lowercase(); - - let mut items = column![].spacing(theme.spacing.xs); - - for entry in config.recent_repos() { - let path = Path::new(&entry.path); - let name = path - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or(&entry.path); - - // Appliquer le filtre de recherche. - let matches = query.is_empty() - || entry.path.to_lowercase().contains(&query) - || name.to_lowercase().contains(&query); - - if !matches { - continue; - } - - let label = column![ - text(name.to_string()) - .size(typo.body) - .color(palette.text_primary), - text(entry.path.clone()) - .size(typo.label) - .color(palette.text_secondary), - ] - .spacing(2.0); - - let repo_btn = button(label) - .width(Length::Fixed(520.0)) - .on_press(Message::RepoSelected(entry.path.clone())); - - items = items.push(repo_btn); - } - - container(items).width(Length::Fill).into() - } - - /// Construit la vue affichée lorsque la liste de dépôts récents est vide. - fn view_empty_state<'a>(&'a self, theme: &'a Theme) -> Element<'a, Message> { - let palette = &theme.palette; - let typo = &theme.typography; - - let hint = text("Your recent repositories will appear here once you open a workspace.") - .size(typo.body) - .color(palette.text_secondary); - - let open_btn = button( - text("Open a workspace folder") - .size(typo.body) - .color(palette.text_primary), - ) - .width(Length::Fixed(520.0)) - .on_press(Message::BrowseClicked); - - let mut col = column![hint, Space::with_height(8.0), open_btn].spacing(theme.spacing.xs); - - // Raccourcis d'accès rapide vers les répertoires courants. - if !self.common_paths.is_empty() { - col = col.push(Space::with_height(8.0)); - col = col.push( - text("Quick access") - .size(typo.body) - .color(palette.text_secondary), - ); - - for (label, path) in &self.common_paths { - let quick_btn = button( - text(format!("{label}: {path}")) - .size(typo.label) - .color(palette.text_secondary), - ) - .on_press(Message::QuickAccessClicked(path.clone())); - - col = col.push(quick_btn); - } - } - - container(col).width(Length::Fill).into() - } -} - -impl Default for RecentList { - fn default() -> Self { - Self::new() - } -} - -/// Renvoie les chemins courants disponibles sur le système (accueil, bureau, etc.). -fn common_paths() -> Vec<(String, String)> { - let mut paths = Vec::new(); - let mut seen = HashSet::new(); - - let candidates = [ - ("Home", dirs::home_dir()), - ("Desktop", dirs::desktop_dir()), - ("Documents", dirs::document_dir()), - ("Downloads", dirs::download_dir()), - ]; - - for (label, path) in candidates { - if let Some(path) = path { - if path.exists() { - let display = path.display().to_string(); - if seen.insert(display.clone()) { - paths.push((label.to_string(), display)); - } - } - } - } - - paths -} - -/// Ouvre le sélecteur de dossier natif hors du thread UI, dans `start` s'il est donné. -pub fn pick_folder(start: Option) -> Task> { - Task::perform( - async move { - tokio::task::spawn_blocking(move || { - let mut dialog = rfd::FileDialog::new(); - if let Some(start) = start { - dialog = dialog.set_directory(start); - } - dialog.pick_folder().map(|p| p.display().to_string()) - }) - .await - .ok() - .flatten() - }, - std::convert::identity, - ) -} diff --git a/src/ui/repo_header.rs b/src/ui/repo_header.rs new file mode 100644 index 0000000..d0cf7f2 --- /dev/null +++ b/src/ui/repo_header.rs @@ -0,0 +1,693 @@ +//! The repository header: name, branch and divergence chips, folder and terminal buttons, +//! Fetch, Pull and Push, the remotes menu, and the section tabs below it. + +use std::ffi::OsStr; +use std::io::ErrorKind; +use std::path::Path; +use std::process::Command as ProcessCommand; +use std::sync::Arc; + +use colony_ui::theme::Palette; +use colony_ui::Typography; +use iced::widget::{column, container, row, text, Space}; +use iced::{Alignment, Element, Length, Padding, Task}; + +use crate::auth::AuthManager; +use crate::config::NetworkOptions; +use crate::git::remote::{ + fetch_remote, list_remotes, pull_branch, push_branch, PullOutcome, RemoteInfo, +}; +use crate::git::status::{read_repo_status, RepoStatus}; +use crate::i18n::{t, tf}; +use crate::ui::context::RepoContext; +use crate::ui::widgets::button; +use crate::ui::widgets::chip::{chip, Tone}; +use crate::ui::widgets::menu::{self, Entry, MenuItem}; +use crate::ui::widgets::tabs::tabs; +use crate::ui::widgets::toast::Toast; + +const FOLDER_GLYPH: &str = "\u{f07c}"; +const TERMINAL_GLYPH: &str = "\u{f120}"; +const MORE_GLYPH: &str = "\u{f141}"; + +/// The sections of an open repository. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RepoTab { + Changes, + History, + Branches, + Stashes, +} + +impl RepoTab { + pub const ALL: [RepoTab; 4] = [ + RepoTab::Changes, + RepoTab::History, + RepoTab::Branches, + RepoTab::Stashes, + ]; + + fn label(self) -> &'static str { + match self { + RepoTab::Changes => t("tab_changes"), + RepoTab::History => t("tab_history"), + RepoTab::Branches => t("tab_branches"), + RepoTab::Stashes => t("tab_stashes"), + } + } +} + +/// The counts shown after the Changes and Stashes tab labels. +#[derive(Debug, Clone, Copy, Default)] +pub struct TabCounts { + pub changes: usize, + pub stashes: usize, +} + +/// A network operation on one of the repository's remotes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RemoteAction { + Fetch, + /// The fetch the auto-fetch timer starts: only a failure is reported. + AutoFetch, + Pull, + Push, +} + +impl RemoteAction { + fn label(self) -> &'static str { + match self { + RemoteAction::Fetch | RemoteAction::AutoFetch => t("header_fetch"), + RemoteAction::Pull => t("header_pull"), + RemoteAction::Push => t("header_push"), + } + } + + fn progress(self) -> &'static str { + match self { + RemoteAction::Fetch | RemoteAction::AutoFetch => t("header_fetching"), + RemoteAction::Pull => t("header_pulling"), + RemoteAction::Push => t("header_pushing"), + } + } + + fn failed(self) -> &'static str { + match self { + RemoteAction::Fetch => t("header_fetch_failed"), + RemoteAction::AutoFetch => t("header_auto_fetch_failed"), + RemoteAction::Pull => t("header_pull_failed"), + RemoteAction::Push => t("header_push_failed"), + } + } +} + +/// The button drawn in the accent colour: Push when there is something to push, else Pull +/// when there is something to pull. +fn primary_action(ahead: usize, behind: usize) -> Option { + if ahead > 0 { + Some(RemoteAction::Push) + } else if behind > 0 { + Some(RemoteAction::Pull) + } else { + None + } +} + +#[derive(Debug, Clone)] +pub enum Message { + /// Status and remotes read for the repository `path`. + StateLoaded { + path: Arc, + status: Result, + remotes: Result, String>, + }, + /// Fetch one remote from the remotes menu, or the upstream's remote with `None`. + Fetch(Option), + Pull, + Push, + /// A network operation on the repository `path` ended. + ActionFinished { + path: Arc, + action: RemoteAction, + result: Result, + }, + OpenFolder, + OpenTerminal, + /// Opens or closes the remotes menu. + RemotesMenu(bool), + /// Handled by the application, which owns the selected tab. + SelectTab(RepoTab), +} + +/// The remote and branches a network operation works on. +#[derive(Debug, Clone)] +struct RemoteSelection { + remote_name: String, + /// URL used to look up the token, `None` when the remote has none. + url: Option, + /// The checked-out branch. + branch: Option, + /// The branch it tracks on the remote, when an upstream is set. + upstream_branch: Option, +} + +pub struct RepoHeader { + repo: Option, + status: Option, + remotes: Vec, + network: NetworkOptions, + /// The status and remotes of a newly opened repository are being read; nothing runs + /// before they are known. + loading: bool, + /// The network operation running on `repo`. + running: Option, + menu_open: bool, +} + +impl RepoHeader { + pub fn new(network: NetworkOptions) -> Self { + Self { + repo: None, + status: None, + remotes: Vec::new(), + network, + loading: false, + running: None, + menu_open: false, + } + } + + pub fn set_network_preferences(&mut self, network: NetworkOptions) { + self.network = network; + } + + /// True while the state loads or a network operation runs on the open repository. + pub fn is_busy(&self) -> bool { + self.loading || self.running.is_some() + } + + /// Reads the status and remotes of `repo` off the UI thread. Another repository starts + /// from an empty state. Reading the open one again keeps the buttons usable and leaves + /// the auto-fetch timer running, so a reload on window focus does not delay auto-fetch. + pub fn load(&mut self, repo: &RepoContext) -> Task { + if self.repo.as_ref().map(RepoContext::path) != Some(repo.path()) { + *self = Self::new(self.network.clone()); + self.repo = Some(repo.clone()); + self.loading = true; + } + + let path = repo.path_arc(); + Task::perform( + async move { + let repo_path = Arc::clone(&path); + let (status, remotes) = tokio::task::spawn_blocking(move || { + let status = read_repo_status(&*repo_path).map_err(|err| err.to_string()); + let remotes = list_remotes(&*repo_path).map_err(|err| err.to_string()); + (status, remotes) + }) + .await + .unwrap_or_else(|err| (Err(err.to_string()), Err(err.to_string()))); + Message::StateLoaded { + path, + status, + remotes, + } + }, + std::convert::identity, + ) + } + + /// Handles a message; the toast, if any, is for the application to show. + pub fn update( + &mut self, + message: Message, + auth: &AuthManager, + ) -> (Task, Option) { + let Some(repo) = self.repo.clone() else { + return (Task::none(), None); + }; + match message { + Message::Fetch(remote) => { + self.menu_open = false; + self.start_action(auth, RemoteAction::Fetch, remote) + } + Message::Pull => self.start_action(auth, RemoteAction::Pull, None), + Message::Push => self.start_action(auth, RemoteAction::Push, None), + Message::OpenFolder => ( + Task::none(), + open_folder(repo.path()) + .err() + .map(|err| Toast::error(t("open_folder_failed"), err)), + ), + Message::OpenTerminal => ( + Task::none(), + open_terminal(repo.path()) + .err() + .map(|err| Toast::error(t("open_terminal_failed"), err)), + ), + Message::RemotesMenu(open) => { + self.menu_open = open; + (Task::none(), None) + } + Message::SelectTab(_) => (Task::none(), None), + Message::StateLoaded { + path, + status, + remotes, + } => { + if *path != *repo.path() { + return (Task::none(), None); + } + self.loading = false; + let mut error = None; + self.status = status.map_err(|err| error = Some(err)).ok(); + self.remotes = remotes + .map_err(|err| { + error.get_or_insert(err); + }) + .unwrap_or_default(); + let toast = error.map(|err| Toast::error(t("header_status_failed"), err)); + (Task::none(), toast) + } + Message::ActionFinished { + path, + action, + result, + } => { + let here = *path == *repo.path(); + if here { + self.running = None; + } + // A result for a repository that is no longer open says which one it was. + let located = |text: String| { + if here { + text + } else { + format!("{path}: {text}") + } + }; + match result { + Ok(_) if action == RemoteAction::AutoFetch => { + (self.reload_if(here, &repo), None) + } + Ok(done) => ( + self.reload_if(here, &repo), + Some(Toast::success(located(done))), + ), + Err(_) if action == RemoteAction::AutoFetch && !here => (Task::none(), None), + Err(err) => ( + Task::none(), + Some(Toast::error(action.failed(), located(err))), + ), + } + } + } + } + + fn reload_if(&mut self, here: bool, repo: &RepoContext) -> Task { + if here { + self.load(repo) + } else { + Task::none() + } + } + + /// Starts a fetch for the auto-fetch timer. Does nothing, and says nothing, while + /// something runs, before the state of `repo` is read, or when it has no remote. + pub fn auto_fetch(&mut self, repo: &RepoContext, auth: &AuthManager) -> Task { + if self.is_busy() + || self.repo.as_ref().map(RepoContext::path) != Some(repo.path()) + || self.resolve_remote_selection(false, None).is_err() + { + return Task::none(); + } + self.start_action(auth, RemoteAction::AutoFetch, None).0 + } + + /// Runs fetch, pull or push off the UI thread. The token is resolved inside the task: + /// reading the keyring and refreshing an OAuth token can block. + fn start_action( + &mut self, + auth: &AuthManager, + action: RemoteAction, + remote: Option, + ) -> (Task, Option) { + let Some(repo) = &self.repo else { + return (Task::none(), None); + }; + if self.is_busy() { + return (Task::none(), None); + } + let selection = match self.resolve_remote_selection(action == RemoteAction::Push, remote) { + Ok(selection) => selection, + Err(err) => return (Task::none(), Some(Toast::error(action.failed(), err))), + }; + self.running = Some(action); + + let path = repo.path_arc(); + let auth = auth.clone(); + let network = self.network.clone(); + let task = Task::perform( + async move { + let repo_path = Arc::clone(&path); + let result = tokio::task::spawn_blocking(move || { + let token = selection + .url + .as_deref() + .and_then(|url| auth.resolve_for_url(url)); + run_remote_action(&repo_path, action, &selection, &network, token) + }) + .await + .unwrap_or_else(|err| Err(err.to_string())); + Message::ActionFinished { + path, + action, + result, + } + }, + std::convert::identity, + ); + (task, None) + } + + /// The remote and branches to use: `remote` when given, else the upstream's remote, else + /// the first one. `push` picks the remote's push URL for the token lookup. + fn resolve_remote_selection( + &self, + push: bool, + remote: Option, + ) -> Result { + let status = self.status.clone().unwrap_or_default(); + let upstream = status.upstream.as_deref().and_then(split_upstream); + let (remote_name, upstream_branch) = match (remote, upstream) { + (Some(remote), _) => (remote, None), + (None, Some((remote, branch))) => (remote.to_string(), Some(branch.to_string())), + (None, None) => { + let remote = self + .remotes + .first() + .map(|r| r.name.clone()) + .ok_or_else(|| t("header_no_remote").to_string())?; + (remote, None) + } + }; + + let url = self + .remotes + .iter() + .find(|r| r.name == remote_name) + .map(|remote| match &remote.push_url { + Some(push_url) if push => push_url.clone(), + _ => remote.url.clone(), + }) + .filter(|url| url != "(no url)"); + + Ok(RemoteSelection { + remote_name, + url, + branch: status.branch, + upstream_branch, + }) + } + + pub fn view(&self, tab: RepoTab, counts: TabCounts) -> Element<'_, Message> { + let Some(repo) = &self.repo else { + return Space::new().into(); + }; + let typo = Typography::current(); + + let mut top = row![text(repo.name.clone()).size(typo.sz(17)).font(typo.bold)] + .spacing(10) + .align_y(Alignment::Center); + if let Some(status) = &self.status { + let branch = match (&status.branch, &status.detached_at) { + (Some(branch), _) => Some(branch.clone()), + (None, Some(hash)) => Some(tf("header_detached", &[("hash", hash)])), + (None, None) => None, + }; + if let Some(branch) = branch { + let tip = match &status.upstream { + Some(upstream) => tf("header_upstream", &[("upstream", upstream)]), + None => t("header_no_upstream").to_string(), + }; + top = top.push(button::with_tip(chip(&branch, Tone::Neutral), &tip)); + } + if let (Some(_), Some(ahead), Some(behind)) = + (&status.upstream, status.ahead, status.behind) + { + let tone = if behind > 0 { + Tone::Warning + } else { + Tone::Success + }; + top = top.push(chip(&format!("↑{ahead} ↓{behind}"), tone)); + } + } + top = top + .push(button::icon( + FOLDER_GLYPH, + Some(Message::OpenFolder), + t("sidebar_open_folder"), + )) + .push(button::icon( + TERMINAL_GLYPH, + Some(Message::OpenTerminal), + t("sidebar_open_terminal"), + )) + .push(Space::new().width(Length::Fill)); + + let primary = self.status.as_ref().and_then(|status| { + primary_action(status.ahead.unwrap_or(0), status.behind.unwrap_or(0)) + }); + let actions = [ + (RemoteAction::Fetch, Message::Fetch(None)), + (RemoteAction::Pull, Message::Pull), + (RemoteAction::Push, Message::Push), + ]; + let mut buttons = row![].spacing(6); + for (action, message) in actions { + let running = match self.running { + Some(RemoteAction::AutoFetch) => action == RemoteAction::Fetch, + running => running == Some(action), + }; + let label = if running { + action.progress() + } else { + action.label() + }; + let press = (!self.is_busy()).then_some(message); + buttons = buttons.push(if primary == Some(action) { + button::primary(label, press) + } else { + button::secondary(label, press) + }); + } + top = top.push(buttons).push(menu::popup( + button::icon( + MORE_GLYPH, + Some(Message::RemotesMenu(!self.menu_open)), + t("header_remotes"), + ), + self.menu_open, + self.remote_entries(), + Message::RemotesMenu(false), + )); + + let items: Vec<(String, Option)> = RepoTab::ALL + .iter() + .map(|&each| { + let count = match each { + RepoTab::Changes => counts.changes, + RepoTab::Stashes => counts.stashes, + RepoTab::History | RepoTab::Branches => 0, + }; + (each.label().to_string(), (count > 0).then_some(count)) + }) + .collect(); + let selected = RepoTab::ALL + .iter() + .position(|&each| each == tab) + .unwrap_or(0); + let strip = tabs(&items, selected, |index| { + Message::SelectTab(RepoTab::ALL[index]) + }); + + let divider = + container(Space::new().width(Length::Fill).height(1)).style(|_| container::Style { + background: Some(Palette::DIVIDER().into()), + ..Default::default() + }); + + column![ + container(top).padding(Padding { + top: 12.0, + right: 18.0, + bottom: 8.0, + left: 18.0, + }), + container(strip).padding(Padding { + top: 0.0, + right: 18.0, + bottom: 8.0, + left: 18.0, + }), + divider, + ] + .into() + } + + /// One "Fetch " entry per remote, with its URL on the right. + fn remote_entries(&self) -> Vec> { + if self.remotes.is_empty() { + return vec![Entry::Item(MenuItem { + label: t("header_no_remotes").to_string(), + shortcut: None, + on_select: Message::RemotesMenu(false), + danger: false, + })]; + } + self.remotes + .iter() + .map(|remote| { + Entry::Item(MenuItem { + label: tf("header_fetch_remote", &[("remote", &remote.name)]), + shortcut: Some(remote.url.clone()), + on_select: Message::Fetch(Some(remote.name.clone())), + danger: false, + }) + }) + .collect() + } +} + +/// Opens a terminal in the folder `path`, without waiting for it to close. +pub fn open_terminal(path: &str) -> Result<(), String> { + let dir = Path::new(path); + if !dir.is_dir() { + return Err(tf("header_folder_missing", &[("path", path)])); + } + + let mut error = None; + for mut command in terminal_commands(dir) { + match command.spawn() { + Ok(_) => return Ok(()), + Err(err) => error = Some(err), + } + } + Err(match error { + Some(err) if err.kind() != ErrorKind::NotFound => err.to_string(), + _ => t("header_no_terminal").to_string(), + }) +} + +/// Opens a folder in the system file manager, without waiting for it to close. +pub fn open_folder(path: &str) -> Result<(), String> { + open::that_detached(path).map_err(|err| err.to_string()) +} + +/// Runs fetch, pull or push. Blocking: call it off the UI thread. +fn run_remote_action( + path: &str, + action: RemoteAction, + selection: &RemoteSelection, + network: &NetworkOptions, + token: Option, +) -> Result { + let remote = &selection.remote_name; + if matches!(action, RemoteAction::Fetch | RemoteAction::AutoFetch) { + fetch_remote(path, remote, network, token).map_err(|err| err.to_string())?; + return Ok(tf("header_fetched", &[("remote", remote)])); + } + let branch = selection + .branch + .as_deref() + .ok_or_else(|| t("header_no_branch").to_string())?; + let upstream = selection.upstream_branch.as_deref().unwrap_or(branch); + let names = [("branch", branch), ("remote", remote.as_str())]; + if action == RemoteAction::Pull { + let outcome = pull_branch(path, remote, branch, upstream, network, token) + .map_err(|err| err.to_string())?; + return Ok(match outcome { + PullOutcome::UpToDate => t("header_up_to_date").to_string(), + PullOutcome::FastForward => tf("header_pulled", &names), + }); + } + push_branch(path, remote, branch, upstream, network, token).map_err(|err| err.to_string())?; + Ok(tf("header_pushed", &names)) +} + +/// The terminal emulators to try, in order, each opening in `path`. +/// +/// The path is only ever the working directory or a whole argument, never part of a shell +/// command line, so characters such as `&`, `'` or spaces in it cannot run anything. +fn terminal_commands(path: &Path) -> Vec { + #[cfg(target_os = "windows")] + let candidates: Vec<(&str, Vec<&OsStr>)> = vec![("cmd", Vec::new())]; + + #[cfg(target_os = "macos")] + let candidates: Vec<(&str, Vec<&OsStr>)> = vec![( + "open", + vec!["-a".as_ref(), "Terminal".as_ref(), path.as_os_str()], + )]; + + #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))] + let dir = path.as_os_str(); + #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))] + let candidates: Vec<(&str, Vec<&OsStr>)> = vec![ + ("x-terminal-emulator", Vec::new()), + ("gnome-terminal", vec!["--working-directory".as_ref(), dir]), + ("konsole", vec!["--workdir".as_ref(), dir]), + ("xfce4-terminal", vec!["--working-directory".as_ref(), dir]), + ("xterm", Vec::new()), + ("alacritty", vec!["--working-directory".as_ref(), dir]), + ("kitty", vec!["--directory".as_ref(), dir]), + ("wezterm", vec!["start".as_ref(), "--cwd".as_ref(), dir]), + ]; + + candidates + .into_iter() + .map(|(program, args)| { + let mut command = ProcessCommand::new(program); + command.args(args).current_dir(path); + command + }) + .collect() +} + +/// Splits an upstream "remote/branch" into its two parts. +fn split_upstream(upstream: &str) -> Option<(&str, &str)> { + upstream.split_once('/') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn primary_action_follows_divergence() { + assert_eq!(primary_action(2, 0), Some(RemoteAction::Push)); + assert_eq!(primary_action(0, 1), Some(RemoteAction::Pull)); + assert_eq!(primary_action(0, 0), None); + assert_eq!(primary_action(2, 1), Some(RemoteAction::Push)); + } + + #[test] + fn terminal_commands_never_put_the_path_in_a_command_line() { + for path in ["/tmp/R&D/it's here", "/tmp/a;b $(touch x)", r"C:\R&D\x y"] { + let path = Path::new(path); + let commands = terminal_commands(path); + assert!(!commands.is_empty()); + for command in &commands { + assert_eq!(command.get_current_dir(), Some(path)); + for arg in command.get_args() { + assert!( + arg == path.as_os_str() + || !arg.to_string_lossy().contains(&*path.to_string_lossy()), + "{:?} embeds the path in {arg:?}", + command.get_program() + ); + } + } + } + } +} diff --git a/src/ui/repo_list.rs b/src/ui/repo_list.rs new file mode 100644 index 0000000..c3ea7e9 --- /dev/null +++ b/src/ui/repo_list.rs @@ -0,0 +1,230 @@ +//! The sidebar's repository list as data: which rows show, in which group and order. + +use std::collections::HashMap; +use std::ops::Range; +use std::path::Path; +use std::sync::Arc; + +use crate::config::RepoEntry; +use crate::git::status::QuickStatus; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Row { + pub path: Arc, + /// The folder name. + pub name: String, + pub pinned: bool, + /// `None` until the background scan has looked at the repository. + pub status: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Group { + pub label_key: &'static str, + pub rows: Vec, +} + +/// With an empty `query`: pinned repositories by name, then the others by last opened +/// (never-opened ones last, by name). With a query: one group of the repositories whose +/// folder name contains it, ignoring case, in the same order. Hidden entries never show. +pub fn groups( + entries: &[RepoEntry], + statuses: &HashMap, + query: &str, +) -> Vec { + let query = query.trim(); + let mut rows: Vec<(Row, Option)> = entries + .iter() + .filter(|entry| !entry.hidden) + .map(|entry| { + let row = Row { + path: Arc::from(entry.path.as_str()), + name: folder_name(&entry.path), + pinned: entry.pinned, + status: statuses.get(&entry.path).cloned(), + }; + (row, entry.last_opened) + }) + .filter(|(row, _)| query.is_empty() || !match_ranges(&row.name, query).is_empty()) + .collect(); + rows.sort_by(|(a, a_opened), (b, b_opened)| { + b.pinned + .cmp(&a.pinned) + // Pinned rows keep their name order; for the others the newest opening comes first. + .then_with(|| match a.pinned { + true => std::cmp::Ordering::Equal, + false => b_opened.cmp(a_opened), + }) + .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())) + .then_with(|| a.path.cmp(&b.path)) + }); + let rows: Vec = rows.into_iter().map(|(row, _)| row).collect(); + + if !query.is_empty() { + return vec![Group { + label_key: "sidebar_results", + rows, + }]; + } + let (pinned, recent): (Vec, Vec) = rows.into_iter().partition(|row| row.pinned); + [("sidebar_pinned", pinned), ("sidebar_recent", recent)] + .into_iter() + .filter(|(_, rows)| !rows.is_empty()) + .map(|(label_key, rows)| Group { label_key, rows }) + .collect() +} + +/// Byte ranges of every non-overlapping occurrence of `query` in `name`, ignoring case. +pub fn match_ranges(name: &str, query: &str) -> Vec> { + let mut ranges = Vec::new(); + if query.is_empty() { + return ranges; + } + let mut start = 0; + while start < name.len() { + match match_len(&name[start..], query) { + Some(len) => { + ranges.push(start..start + len); + start += len; + } + None => start += name[start..].chars().next().map_or(1, char::len_utf8), + } + } + ranges +} + +/// The byte length of the prefix of `haystack` that equals `needle` ignoring case, if any. +/// Compared char by char, so a letter whose lower case has another byte length still lines up. +fn match_len(haystack: &str, needle: &str) -> Option { + let mut chars = haystack.char_indices(); + for wanted in needle.chars() { + let (_, found) = chars.next()?; + if !found.to_lowercase().eq(wanted.to_lowercase()) { + return None; + } + } + Some(chars.next().map_or(haystack.len(), |(at, _)| at)) +} + +fn folder_name(path: &str) -> String { + Path::new(path).file_name().map_or_else( + || path.to_string(), + |name| name.to_string_lossy().into_owned(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(path: &str, pinned: bool, last_opened: Option) -> RepoEntry { + RepoEntry { + path: path.to_string(), + pinned, + last_opened, + ..RepoEntry::default() + } + } + + fn layout(groups: &[Group]) -> Vec<(&str, Vec<&str>)> { + groups + .iter() + .map(|group| { + let names = group.rows.iter().map(|row| row.name.as_str()).collect(); + (group.label_key, names) + }) + .collect() + } + + #[test] + fn groups_put_pinned_first_then_recent_by_last_opened() { + let entries = [ + entry("/r/old", false, Some(10)), + entry("/r/zeta", true, Some(1)), + entry("/r/new", false, Some(30)), + entry("/r/Alpha", true, Some(5)), + entry("/r/mid", false, Some(20)), + ]; + let mut statuses = HashMap::new(); + let dirty = QuickStatus { + changed: 3, + ..QuickStatus::default() + }; + statuses.insert("/r/new".to_string(), dirty.clone()); + + let groups = groups(&entries, &statuses, ""); + assert_eq!( + layout(&groups), + [ + ("sidebar_pinned", vec!["Alpha", "zeta"]), + ("sidebar_recent", vec!["new", "mid", "old"]), + ] + ); + assert_eq!(&*groups[1].rows[0].path, "/r/new"); + assert_eq!(groups[1].rows[0].status, Some(dirty)); + assert_eq!(groups[1].rows[1].status, None); + } + + #[test] + fn never_opened_discovered_repos_sort_last_by_name() { + let entries = [ + RepoEntry { + discovered: true, + ..entry("/c/beta", false, None) + }, + entry("/r/opened", false, Some(1)), + RepoEntry { + discovered: true, + ..entry("/c/Alpha", false, None) + }, + ]; + assert_eq!( + layout(&groups(&entries, &HashMap::new(), "")), + [("sidebar_recent", vec!["opened", "Alpha", "beta"])] + ); + } + + #[test] + fn hidden_repos_are_not_listed() { + let entries = [ + RepoEntry { + discovered: true, + hidden: true, + ..entry("/c/gone", true, Some(9)) + }, + entry("/r/kept", false, Some(1)), + ]; + assert_eq!( + layout(&groups(&entries, &HashMap::new(), "")), + [("sidebar_recent", vec!["kept"])] + ); + assert!(groups(&entries, &HashMap::new(), "gone")[0].rows.is_empty()); + } + + #[test] + fn query_filters_case_insensitively_into_one_group() { + let entries = [ + entry("/r/Colony", false, Some(1)), + entry("/r/colony-ui", true, Some(2)), + entry("/r/GitSpace", false, Some(3)), + entry("/r/Colony-Camera", false, None), + ]; + assert_eq!( + layout(&groups(&entries, &HashMap::new(), " COL ")), + [( + "sidebar_results", + vec!["colony-ui", "Colony", "Colony-Camera"] + )] + ); + } + + #[test] + fn match_ranges_find_every_occurrence() { + assert_eq!(match_ranges("colony-Colony", "col"), [0..3, 7..10]); + assert_eq!(match_ranges("aaaa", "aa"), [0..2, 2..4]); + assert!(match_ranges("GitSpace", "x").is_empty()); + assert!(match_ranges("GitSpace", "").is_empty()); + // "É" is two bytes; the match after it still lands on char boundaries. + assert_eq!(match_ranges("Été-été", "été"), [0..5, 6..11]); + } +} diff --git a/src/ui/repo_overview.rs b/src/ui/repo_overview.rs deleted file mode 100644 index 0a19c8a..0000000 --- a/src/ui/repo_overview.rs +++ /dev/null @@ -1,630 +0,0 @@ -// Panneau de vue d'ensemble du dépôt — migration Iced 0.13 -// Affiche le statut, les remotes, les actions rapides et le contexte d'auto-fetch. - -use std::ffi::OsStr; -use std::io::ErrorKind; -use std::path::Path; -use std::process::Command as ProcessCommand; -use std::sync::Arc; - -use iced::widget::{button, container, horizontal_rule, text, Column, Row}; -use iced::{Element, Length, Task}; - -use crate::ui::theme::Theme; - -use crate::auth::AuthManager; -use crate::config::NetworkOptions; -use crate::git::remote::{ - fetch_remote, list_remotes, pull_branch, push_branch, PullOutcome, RemoteInfo, -}; -use crate::git::status::{read_repo_status, RepoStatus}; -use crate::ui::context::RepoContext; - -// ── Structures auxiliaires ───────────────────────────────────────────────── - -/// Opération réseau lancée sur le remote du dépôt. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum RemoteAction { - Fetch, - Pull, - Push, -} - -impl RemoteAction { - pub fn label(self) -> &'static str { - match self { - Self::Fetch => "Fetch", - Self::Pull => "Pull", - Self::Push => "Push", - } - } -} - -/// Sélection résolue d'un remote et d'une branche. -#[derive(Debug, Clone)] -struct RemoteSelection { - remote_name: String, - /// URL used to look up the token, `None` when the remote has none. - url: Option, - /// The checked-out branch. - branch: Option, - /// The branch it tracks on the remote, when an upstream is set. - upstream_branch: Option, -} - -// ── Messages du panneau ──────────────────────────────────────────────────── - -/// Messages émis par le panneau de vue d'ensemble. -#[derive(Debug, Clone)] -pub enum Message { - /// Lancer un fetch. - Fetch, - /// Lancer un pull. - Pull, - /// Lancer un push. - Push, - /// Ouvrir un terminal dans le dépôt. - OpenTerminal, - /// Ouvrir l'explorateur de fichiers dans le dépôt. - OpenFileExplorer, - /// Statut et remotes lus pour le dépôt `path`. - StateLoaded { - path: Arc, - status: Result, - remotes: Result, String>, - }, - /// Fin d'une opération réseau sur le dépôt `path`. `auto` marque un auto-fetch. - ActionFinished { - path: Arc, - action: RemoteAction, - auto: bool, - result: Result, - }, -} - -// ── Panneau principal ────────────────────────────────────────────────────── - -pub struct RepoOverviewPanel { - status: Option, - remotes: Vec, - last_repo: Option, - error: Option, - action_status: Option, - network: NetworkOptions, - /// A state load or a network operation is running for `last_repo`. - busy: bool, -} - -impl RepoOverviewPanel { - /// Crée un nouveau panneau de vue d'ensemble. - pub fn new(network: NetworkOptions) -> Self { - Self { - status: None, - remotes: Vec::new(), - last_repo: None, - error: None, - action_status: None, - network, - busy: false, - } - } - - /// Met à jour les préférences réseau. - pub fn set_network_preferences(&mut self, network: NetworkOptions) { - self.network = network; - } - - /// Vrai pendant un chargement d'état ou une opération réseau sur le dépôt courant. - pub fn is_busy(&self) -> bool { - self.busy - } - - /// Traite un message et retourne une commande Iced. - pub fn update( - &mut self, - message: Message, - repo: Option<&RepoContext>, - auth: &AuthManager, - ) -> Task { - let Some(repo) = repo else { - return Task::none(); - }; - match message { - Message::Fetch => self.start_action(repo, auth, RemoteAction::Fetch, false), - Message::Pull => self.start_action(repo, auth, RemoteAction::Pull, false), - Message::Push => self.start_action(repo, auth, RemoteAction::Push, false), - Message::OpenTerminal => { - self.action_status = Some(match self.open_terminal(repo) { - Ok(msg) => msg, - Err(err) => format!("Terminal failed: {err}"), - }); - Task::none() - } - Message::OpenFileExplorer => { - self.action_status = Some(match open_folder(repo.path()) { - Ok(()) => "File explorer opened".to_string(), - Err(err) => format!("File explorer failed: {err}"), - }); - Task::none() - } - Message::StateLoaded { - path, - status, - remotes, - } => { - if *path != *repo.path() { - return Task::none(); - } - self.busy = false; - self.error = None; - self.status = status - .map_err(|err| { - self.error = Some(format!("Failed to read repository status: {err}")); - }) - .ok(); - self.remotes = remotes - .map_err(|err| { - self.error - .get_or_insert_with(|| format!("Failed to read remotes: {err}")); - }) - .unwrap_or_default(); - Task::none() - } - Message::ActionFinished { - path, - action, - auto, - result, - } => { - if *path != *repo.path() { - return Task::none(); - } - self.busy = false; - let prefix = if auto { "Auto-fetch" } else { action.label() }; - match result { - Ok(msg) => { - self.action_status = Some(if auto { - format!("{prefix}: {msg}") - } else { - msg - }); - self.reload_repo_state(repo) - } - Err(err) => { - self.action_status = Some(format!("{prefix} failed: {err}")); - Task::none() - } - } - } - } - } - - /// Construit la vue du panneau. - pub fn view<'a>( - &'a self, - _theme: &'a Theme, - repo: Option<&'a RepoContext>, - ) -> Element<'a, Message> { - let mut content = Column::new().spacing(8).padding(10).width(Length::Fill); - - // ── En-tête + statut d'action ─────────────────────────────────── - let mut header = Row::new().spacing(12); - header = header.push(text("Repository overview").size(20)); - if let Some(action_status) = &self.action_status { - header = header.push(text(action_status.clone()).size(13)); - } - content = content.push(header); - - // Vérifier si un dépôt est ouvert - let repo = match repo { - Some(r) => r, - None => { - content = content.push( - text("Select or clone a repository to see its Git status, remotes, and quick actions.") - .size(13), - ); - return container(content) - .width(Length::Fill) - .height(Length::Fill) - .into(); - } - }; - - // Afficher les erreurs éventuelles - if let Some(error) = &self.error { - content = content.push(text(error.clone()).size(13)); - } - - // ── Résumé : nom + chemin ─────────────────────────────────────── - content = content.push(self.build_summary(repo)); - content = content.push(horizontal_rule(1)); - - // ── Section branche ───────────────────────────────────────────── - content = content.push(self.build_branch_section()); - content = content.push(horizontal_rule(1)); - - // ── Section remotes ───────────────────────────────────────────── - content = content.push(self.build_remotes_section()); - content = content.push(horizontal_rule(1)); - - // ── Actions rapides ───────────────────────────────────────────── - content = content.push(self.build_quick_actions()); - - container(content) - .width(Length::Fill) - .height(Length::Fill) - .into() - } - - // ── Construction des sous-vues ───────────────────────────────────── - - /// Résumé du dépôt : nom et chemin. - fn build_summary<'a>(&'a self, repo: &'a RepoContext) -> Element<'a, Message> { - let col = Column::new() - .spacing(2) - .push(text(&repo.name).size(18)) - .push(text(repo.path()).size(12)); - col.into() - } - - /// Section de la branche courante avec upstream et ahead/behind. - fn build_branch_section(&self) -> Element<'_, Message> { - let status = self.status.clone().unwrap_or_default(); - let branch = status.branch.unwrap_or_else(|| "(detached)".to_string()); - let upstream = status.upstream.unwrap_or_else(|| "No upstream".to_string()); - let ahead = status.ahead.unwrap_or(0); - let behind = status.behind.unwrap_or(0); - - let mut col = Column::new().spacing(4).padding(8); - - col = col.push(text("Branch").size(16)); - - // Informations de la branche - let branch_info = Column::new() - .spacing(2) - .push(text(branch).size(14)) - .push(text(format!("Upstream: {upstream}")).size(12)); - - // Statistiques ahead/behind - let stats = Row::new() - .spacing(12) - .push(text(format!("Ahead: {ahead}")).size(13)) - .push(text(format!("Behind: {behind}")).size(13)); - - let branch_row = Row::new() - .spacing(16) - .width(Length::Fill) - .push(branch_info) - .push(stats); - - col = col.push(container(branch_row).width(Length::Fill).padding(10)); - - col.into() - } - - /// Section listant les remotes configurés. - fn build_remotes_section(&self) -> Element<'_, Message> { - let mut col = Column::new().spacing(4); - - col = col.push(text("Remotes").size(16)); - - if self.remotes.is_empty() { - col = col.push(text("No remotes configured for this repository.").size(12)); - return col.into(); - } - - for remote in &self.remotes { - let card = container( - Row::new() - .spacing(8) - .push(text(&remote.name).size(13)) - .push(text(&remote.url).size(12)), - ) - .width(Length::Fill) - .padding(8); - - col = col.push(card); - } - - col.into() - } - - /// Ligne de boutons d'actions rapides. - fn build_quick_actions(&self) -> Element<'_, Message> { - let mut col = Column::new().spacing(4); - - col = col.push(text("Quick actions").size(16)); - - let network_button = |label, message| { - button(text(label).size(13)) - .on_press_maybe((!self.busy).then_some(message)) - .padding(6) - }; - - let actions_row = Row::new() - .spacing(8) - .push(network_button("Fetch", Message::Fetch)) - .push(network_button("Pull", Message::Pull)) - .push(network_button("Push", Message::Push)) - .push( - button(text("Open terminal").size(13)) - .on_press(Message::OpenTerminal) - .padding(6), - ) - .push( - button(text("Open file explorer").size(13)) - .on_press(Message::OpenFileExplorer) - .padding(6), - ); - - col = col.push(actions_row); - col.into() - } - - // ── Rafraîchissement de l'état ───────────────────────────────────── - - /// Rafraîchit l'état du dépôt si le chemin a changé. - pub fn refresh(&mut self, repo: &RepoContext) -> Task { - if self.last_repo.as_deref() == Some(repo.path()) { - return Task::none(); - } - self.action_status = None; - self.reload_repo_state(repo) - } - - /// Relit le statut et les remotes du dépôt hors du thread UI. - pub fn reload_repo_state(&mut self, repo: &RepoContext) -> Task { - if self.last_repo.as_deref() != Some(repo.path()) { - self.last_repo = Some(repo.path().to_string()); - self.status = None; - self.remotes.clear(); - self.error = None; - } - self.busy = true; - - let path = repo.path_arc(); - Task::perform( - async move { - let repo_path = Arc::clone(&path); - let (status, remotes) = tokio::task::spawn_blocking(move || { - let status = read_repo_status(&*repo_path).map_err(|err| err.to_string()); - let remotes = list_remotes(&*repo_path).map_err(|err| err.to_string()); - (status, remotes) - }) - .await - .unwrap_or_else(|err| (Err(err.to_string()), Err(err.to_string()))); - Message::StateLoaded { - path, - status, - remotes, - } - }, - std::convert::identity, - ) - } - - // ── Opérations git ───────────────────────────────────────────────── - - /// Lance un fetch en arrière-plan pour l'auto-fetch. Ne fait rien, sans message, si une - /// opération est en cours, si l'état du dépôt n'est pas encore lu ou s'il n'a pas de remote. - pub fn auto_fetch(&mut self, repo: &RepoContext, auth: &AuthManager) -> Task { - if self.busy - || self.last_repo.as_deref() != Some(repo.path()) - || self.resolve_remote_selection(false).is_err() - { - return Task::none(); - } - self.start_action(repo, auth, RemoteAction::Fetch, true) - } - - /// Lance fetch, pull ou push hors du thread UI. Le token est résolu dans la tâche : - /// la lecture du trousseau et le rafraîchissement OAuth peuvent bloquer. - fn start_action( - &mut self, - repo: &RepoContext, - auth: &AuthManager, - action: RemoteAction, - auto: bool, - ) -> Task { - if self.busy { - return Task::none(); - } - let selection = match self.resolve_remote_selection(action == RemoteAction::Push) { - Ok(selection) => selection, - Err(err) => { - self.action_status = Some(format!("{} failed: {err}", action.label())); - return Task::none(); - } - }; - self.busy = true; - self.action_status = Some(format!("{} {}...", action.label(), selection.remote_name)); - - let path = repo.path_arc(); - let auth = auth.clone(); - let network = self.network.clone(); - Task::perform( - async move { - let repo_path = Arc::clone(&path); - let result = tokio::task::spawn_blocking(move || { - let token = selection - .url - .as_deref() - .and_then(|url| auth.resolve_for_url(url)); - run_remote_action(&repo_path, action, &selection, &network, token) - }) - .await - .unwrap_or_else(|err| Err(err.to_string())); - Message::ActionFinished { - path, - action, - auto, - result, - } - }, - std::convert::identity, - ) - } - - /// Résout le remote et la branche à utiliser pour les opérations réseau, avec l'URL de - /// push quand `push` est vrai. - fn resolve_remote_selection(&self, push: bool) -> Result { - let status = self.status.clone().unwrap_or_default(); - let upstream = status.upstream.as_deref().and_then(split_upstream); - let (remote_name, upstream_branch) = if let Some((remote, branch)) = upstream { - (remote.to_string(), Some(branch.to_string())) - } else { - let remote = self - .remotes - .first() - .map(|r| r.name.clone()) - .ok_or_else(|| "No remotes configured for this repository.".to_string())?; - (remote, None) - }; - - let url = self - .remotes - .iter() - .find(|r| r.name == remote_name) - .map(|remote| match &remote.push_url { - Some(push_url) if push => push_url.clone(), - _ => remote.url.clone(), - }) - .filter(|url| url != "(no url)"); - - Ok(RemoteSelection { - remote_name, - url, - branch: status.branch, - upstream_branch, - }) - } - - // ── Actions système ──────────────────────────────────────────────── - - /// Ouvre un terminal dans le répertoire du dépôt. - fn open_terminal(&self, repo: &RepoContext) -> Result { - let path = Path::new(repo.path()); - if !path.is_dir() { - return Err(format!("Repository folder not found: {}", repo.path())); - } - - let mut error = None; - for mut command in terminal_commands(path) { - match command.spawn() { - Ok(_) => return Ok("Terminal opened".to_string()), - Err(err) => error = Some(err), - } - } - Err(match error { - Some(err) if err.kind() != ErrorKind::NotFound => err.to_string(), - _ => "No supported terminal emulator found on PATH".to_string(), - }) - } -} - -// ── Fonctions utilitaires ────────────────────────────────────────────────── - -/// Ouvre un dossier dans le gestionnaire de fichiers du système, sans attendre sa fermeture. -pub fn open_folder(path: &str) -> Result<(), String> { - open::that_detached(path).map_err(|err| err.to_string()) -} - -/// Exécute fetch, pull ou push. Bloquant : à appeler hors du thread UI. -fn run_remote_action( - path: &str, - action: RemoteAction, - selection: &RemoteSelection, - network: &NetworkOptions, - token: Option, -) -> Result { - let remote = &selection.remote_name; - if action == RemoteAction::Fetch { - fetch_remote(path, remote, network, token).map_err(|err| err.to_string())?; - return Ok(format!("Fetched {remote}")); - } - let branch = selection.branch.as_deref().ok_or_else(|| { - format!( - "No branch checked out for {}.", - action.label().to_lowercase() - ) - })?; - let upstream = selection.upstream_branch.as_deref().unwrap_or(branch); - if action == RemoteAction::Pull { - let outcome = pull_branch(path, remote, branch, upstream, network, token) - .map_err(|err| err.to_string())?; - return Ok(match outcome { - PullOutcome::UpToDate => "Already up to date.".to_string(), - PullOutcome::FastForward => format!("Pulled {branch} from {remote}"), - }); - } - push_branch(path, remote, branch, upstream, network, token).map_err(|err| err.to_string())?; - Ok(format!("Pushed {branch} to {remote}")) -} - -/// The terminal emulators to try, in order, each opening in `path`. -/// -/// The path is only ever the working directory or a whole argument, never part of a shell -/// command line, so characters such as `&`, `'` or spaces in it cannot run anything. -fn terminal_commands(path: &Path) -> Vec { - #[cfg(target_os = "windows")] - let candidates: Vec<(&str, Vec<&OsStr>)> = vec![("cmd", Vec::new())]; - - #[cfg(target_os = "macos")] - let candidates: Vec<(&str, Vec<&OsStr>)> = vec![( - "open", - vec!["-a".as_ref(), "Terminal".as_ref(), path.as_os_str()], - )]; - - #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))] - let dir = path.as_os_str(); - #[cfg(all(not(target_os = "windows"), not(target_os = "macos")))] - let candidates: Vec<(&str, Vec<&OsStr>)> = vec![ - ("x-terminal-emulator", Vec::new()), - ("gnome-terminal", vec!["--working-directory".as_ref(), dir]), - ("konsole", vec!["--workdir".as_ref(), dir]), - ("xfce4-terminal", vec!["--working-directory".as_ref(), dir]), - ("xterm", Vec::new()), - ("alacritty", vec!["--working-directory".as_ref(), dir]), - ("kitty", vec!["--directory".as_ref(), dir]), - ("wezterm", vec!["start".as_ref(), "--cwd".as_ref(), dir]), - ]; - - candidates - .into_iter() - .map(|(program, args)| { - let mut command = ProcessCommand::new(program); - command.args(args).current_dir(path); - command - }) - .collect() -} - -/// Sépare un upstream "remote/branch" en ses deux composants. -fn split_upstream(upstream: &str) -> Option<(&str, &str)> { - upstream.split_once('/') -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn terminal_commands_never_put_the_path_in_a_command_line() { - for path in ["/tmp/R&D/it's here", "/tmp/a;b $(touch x)", r"C:\R&D\x y"] { - let path = Path::new(path); - let commands = terminal_commands(path); - assert!(!commands.is_empty()); - for command in &commands { - assert_eq!(command.get_current_dir(), Some(path)); - for arg in command.get_args() { - assert!( - arg == path.as_os_str() - || !arg.to_string_lossy().contains(&*path.to_string_lossy()), - "{:?} embeds the path in {arg:?}", - command.get_program() - ); - } - } - } - } -} diff --git a/src/ui/sidebar.rs b/src/ui/sidebar.rs new file mode 100644 index 0000000..66daa00 --- /dev/null +++ b/src/ui/sidebar.rs @@ -0,0 +1,574 @@ +//! The left column: GitSpace's name, the repository list with its search, and the way to +//! add a repository. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::sync::Arc; + +use colony_ui::theme::{contrast_on, Palette}; +use colony_ui::widgets::{icons, identity_button, nav_hint, nav_label, selection_style}; +use colony_ui::{fonts, Typography}; +use iced::widget::text::Span; +use iced::widget::{ + button, column, container, hover, mouse_area, rich_text, row, scrollable, span, text, + text_input, Column, Space, +}; +use iced::{Alignment, Border, Element, Font, Length, Task}; + +use crate::config::RepoEntry; +use crate::git::status::QuickStatus; +use crate::i18n::{t, tf}; +use crate::ui::repo_list::{self, Row}; +use crate::ui::widgets::{button as gs_button, menu}; + +/// The search field, focused when the search opens. +const SEARCH_ID: &str = "sidebar-search"; // i18n: not user-visible + +const SEARCH_GLYPH: &str = "\u{f002}"; +const PIN_GLYPH: &str = "\u{f08d}"; + +#[derive(Debug, Clone)] +pub enum Message { + ToggleSearch, + Query(String), + MoveSelection(i32), + Activate, + Select(Arc), + Pin(Arc, bool), + Hide(Arc), + OpenFolder(Arc), + OpenTerminal(Arc), + ContextMenu(Option>), + AddRepository, + TogglePreferences, + /// A status refresh's number and the statuses it read. + StatusesLoaded(u64, HashMap), +} + +#[derive(Debug, Default)] +pub struct Sidebar { + searching: bool, + query: String, + /// The row Up/Down reached while searching; Enter opens it. + cursor: Option>, + /// The repository whose right-click menu is open. + menu: Option>, + /// The row Alt+Up/Down step from: the last one asked to open, even while it loads or + /// after it failed to open. + anchor: Option>, + /// Each entry's last opening when a run of Alt+Up/Down began. Until another row is + /// picked, the list keeps that order, so the row just opened does not jump to the top + /// of RECENT and the next step goes on from where it is. + stepping: Option>>, +} + +impl Sidebar { + pub fn is_searching(&self) -> bool { + self.searching + } + + pub fn is_menu_open(&self) -> bool { + self.menu.is_some() + } + + pub fn set_menu(&mut self, path: Option>) { + self.menu = path; + } + + /// The row Enter opens while searching. + pub fn cursor(&self) -> Option> { + self.cursor.clone().filter(|_| self.searching) + } + + /// Opens the search field with the focus in it, or closes and clears it. + pub fn toggle_search(&mut self, entries: &[RepoEntry]) -> Task { + if self.searching { + self.close_search(); + return Task::none(); + } + self.searching = true; + self.stepping = None; + self.set_query(String::new(), entries); + iced::widget::operation::focus(SEARCH_ID) + } + + pub fn close_search(&mut self) { + self.searching = false; + self.query.clear(); + self.cursor = None; + } + + /// Filters the list; the first result becomes the one Enter opens. + pub fn set_query(&mut self, query: String, entries: &[RepoEntry]) { + self.query = query; + self.cursor = self.paths(entries).into_iter().next(); + } + + /// Records the repository just asked to open; Alt+Up/Down step from it. Another row than + /// the one stepped to ends the run of steps. + pub fn set_anchor(&mut self, path: &str) { + if self.anchor.as_deref() != Some(path) { + self.stepping = None; + } + self.anchor = Some(path.into()); + } + + /// Moves `delta` rows from the search cursor, or from the anchor when not searching, + /// and returns the row reached. Stops at either end of the list. + pub fn step(&mut self, delta: i32, entries: &[RepoEntry]) -> Option> { + if !self.searching && self.stepping.is_none() { + let opened = entries + .iter() + .map(|entry| (entry.path.clone(), entry.last_opened)) + .collect(); + self.stepping = Some(opened); + } + let paths = self.paths(entries); + let from = if self.searching { + self.cursor.as_deref() + } else { + self.anchor.as_deref() + }; + let last = paths.len().checked_sub(1)?; + let index = match from.and_then(|from| paths.iter().position(|path| &**path == from)) { + Some(index) => index.saturating_add_signed(delta as isize).min(last), + None if delta < 0 => last, + None => 0, + }; + let target = paths[index].clone(); + if self.searching { + self.cursor = Some(target.clone()); + } else { + self.anchor = Some(target.clone()); + } + Some(target) + } + + /// Every listed row, top to bottom. + fn paths(&self, entries: &[RepoEntry]) -> Vec> { + repo_list::groups(&self.listed(entries), &HashMap::new(), &self.query) + .into_iter() + .flat_map(|group| group.rows) + .map(|row| row.path) + .collect() + } + + /// `entries` with the last openings seen when the current run of steps began. + fn listed<'e>(&self, entries: &'e [RepoEntry]) -> Cow<'e, [RepoEntry]> { + let Some(opened) = &self.stepping else { + return Cow::Borrowed(entries); + }; + entries + .iter() + .map(|entry| RepoEntry { + last_opened: opened + .get(&entry.path) + .copied() + .unwrap_or(entry.last_opened), + ..entry.clone() + }) + .collect() + } + + pub fn view( + &self, + entries: &[RepoEntry], + statuses: &HashMap, + current: Option<&str>, + preferences_open: bool, + ) -> Element<'_, Message> { + let typo = Typography::current(); + let groups = repo_list::groups(&self.listed(entries), statuses, &self.query); + let selected = if self.searching { + self.cursor.as_deref() + } else { + current + }; + + let mut list = Column::new().spacing(2); + for group in groups { + let label = match group.label_key { + "sidebar_results" if group.rows.len() == 1 => t("sidebar_results_one").to_owned(), + key => tf(key, &[("count", &group.rows.len().to_string())]), + }; + list = list.push( + container( + text(label) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()), + ) + .padding(iced::Padding { + top: 10.0, + right: 10.0, + bottom: 2.0, + left: 10.0, + }), + ); + for repo in group.rows { + let is_selected = selected == Some(&*repo.path); + let menu_open = self.menu.as_deref() == Some(&*repo.path); + list = list.push(row_view(repo, &self.query, is_selected, menu_open)); + } + } + + let visible = entries.iter().filter(|entry| !entry.hidden).count(); + let add = button( + text(t("sidebar_add")) + .size(typo.sz(13)) + .font(typo.regular) + .color(Palette::ACCENT()), + ) + .on_press(Message::AddRepository) + .width(Length::Fill) + .padding([8, 10]) + .style(|_, status| button::Style { + background: matches!(status, button::Status::Hovered | button::Status::Pressed) + .then(|| Palette::BG_CARD_HOVER().into()), + border: Border::default().rounded(6), + ..Default::default() + }); + let divider = + container(Space::new().width(Length::Fill).height(1)).style(|_| container::Style { + background: Some(Palette::DIVIDER().into()), + ..Default::default() + }); + let hint = if self.searching { + t("sidebar_search_hint") + } else { + t("sidebar_hint") + }; + + let content = column![ + identity_button( + &typo, + "GitSpace", // i18n: not user-visible (program name) + 22, + preferences_open, + Message::TogglePreferences + ), + Space::new().height(6), + self.label_row(&typo, visible), + scrollable(list).height(Length::Fill), + divider, + add, + container(nav_hint(&typo, hint)).padding([4, 10]), + ] + .spacing(2) + .padding([14, 10]); + + container(content) + .width(240) + .height(Length::Fill) + .style(|_| container::Style { + background: Some(Palette::BG_SIDEBAR().into()), + ..Default::default() + }) + .into() + } + + /// "Repositories · N" with the magnifier, or the search field in its place. Both are + /// the same height, so opening the search moves nothing below. + fn label_row(&self, typo: &Typography, count: usize) -> Element<'_, Message> { + let height = typo.sz(30); + if !self.searching { + let label = tf("sidebar_repositories", &[("count", &count.to_string())]); + return container( + row![ + nav_label(typo, &label), + Space::new().width(Length::Fill), + gs_button::icon( + SEARCH_GLYPH, + Some(Message::ToggleSearch), + t("sidebar_search_tip") + ), + ] + .align_y(Alignment::Center), + ) + .height(height) + .padding([0, 8]) + .align_y(Alignment::Center) + .into(); + } + + let field = text_input(t("sidebar_search_placeholder"), &self.query) + .id(SEARCH_ID) + .on_input(Message::Query) + .on_submit(Message::Activate) + .size(typo.sz(13)) + .font(typo.regular) + .padding(0) + .style(|_, _| text_input::Style { + background: iced::Color::TRANSPARENT.into(), + border: Border::default(), + icon: Palette::TEXT_DIMMER(), + placeholder: Palette::TEXT_PLACEHOLDER(), + value: Palette::TEXT_PRIMARY(), + selection: Palette::ACCENT().scale_alpha(0.35), + }); + container( + row![ + text(SEARCH_GLYPH) + .size(typo.sz(13)) + .font(fonts::glyph_font()) + .color(Palette::TEXT_DIMMER()), + field, + gs_button::icon( + icons::CLOSE, + Some(Message::ToggleSearch), + t("sidebar_search_close") + ), + ] + .spacing(8) + .align_y(Alignment::Center), + ) + .height(height) + .padding([0, 8]) + .align_y(Alignment::Center) + .style(|_| container::Style { + background: Some(Palette::BG_INPUT().into()), + border: Border::default().rounded(6), + ..Default::default() + }) + .into() + } +} + +/// What the right end of a row shows. +#[derive(Debug, PartialEq, Eq)] +enum Badge { + /// A label from the i18n table. + Label(&'static str), + /// Changed files, then ↑ ahead and ↓ behind, each only when not zero. + Counts(String), + Nothing, +} + +fn badge(status: Option<&QuickStatus>) -> Badge { + let Some(status) = status else { + return Badge::Nothing; + }; + if status.missing { + return Badge::Label("sidebar_missing"); + } + let parts: Vec = [ + (status.changed > 0).then(|| status.changed.to_string()), + (status.ahead > 0).then(|| format!("↑{}", status.ahead)), + (status.behind > 0).then(|| format!("↓{}", status.behind)), + ] + .into_iter() + .flatten() + .collect(); + if parts.is_empty() { + Badge::Nothing + } else { + Badge::Counts(parts.join(" ")) + } +} + +fn row_view<'a>(repo: Row, query: &str, selected: bool, menu_open: bool) -> Element<'a, Message> { + let typo = Typography::current(); + let missing = repo.status.as_ref().is_some_and(|status| status.missing); + let on_accent = contrast_on(Palette::ACCENT()); + let name_color = if selected { + on_accent + } else if missing { + Palette::TEXT_DIMMER() + } else { + Palette::TEXT_MUTED() + }; + + let mut spans: Vec> = Vec::new(); + let mut at = 0; + for range in repo_list::match_ranges(&repo.name, query.trim()) { + spans.push(span(repo.name[at..range.start].to_owned()).color(name_color)); + let matched = span(repo.name[range.clone()].to_owned()).font(typo.bold); + spans.push(if selected { + matched.color(on_accent).underline(true) + } else { + matched.color(Palette::ACCENT()) + }); + at = range.end; + } + spans.push(span(repo.name[at..].to_owned()).color(name_color)); + + let badge_color = if selected { + on_accent.scale_alpha(0.7) + } else { + Palette::TEXT_DIMMEST() + }; + let badge_text = match badge(repo.status.as_ref()) { + Badge::Label(key) => t(key).to_owned(), + Badge::Counts(counts) => counts, + Badge::Nothing => String::new(), + }; + + let content = row![ + rich_text(spans) + .size(typo.sz(13)) + .font(typo.regular) + .width(Length::Fill), + text(badge_text) + .size(typo.sz(10)) + .font(typo.regular) + .color(badge_color), + ] + .spacing(8) + .align_y(Alignment::Center); + + let item = mouse_area( + button(content) + .on_press(Message::Select(repo.path.clone())) + .padding([6, 10]) + .width(Length::Fill) + .style(selection_style(selected)), + ) + .on_right_press(Message::ContextMenu(Some(repo.path.clone()))); + + let pin_tip = if repo.pinned { + t("sidebar_unpin") + } else { + t("sidebar_pin") + }; + let pin = container(gs_button::icon( + PIN_GLYPH, + Some(Message::Pin(repo.path.clone(), !repo.pinned)), + pin_tip, + )) + .width(Length::Fill) + .height(Length::Fill) + .align_x(Alignment::End) + .align_y(Alignment::Center); + + let mut entries = vec![menu::Entry::Item(menu::MenuItem { + label: pin_tip.to_owned(), + shortcut: None, + on_select: Message::Pin(repo.path.clone(), !repo.pinned), + danger: false, + })]; + // A folder that is gone cannot be opened; the menu then only offers to remove it. + if !missing { + for (key, message) in [ + ( + "sidebar_open_folder", + Message::OpenFolder(repo.path.clone()), + ), + ( + "sidebar_open_terminal", + Message::OpenTerminal(repo.path.clone()), + ), + ] { + entries.push(menu::Entry::Item(menu::MenuItem { + label: t(key).to_owned(), + shortcut: None, + on_select: message, + danger: false, + })); + } + } + entries.push(menu::Entry::Separator); + entries.push(menu::Entry::Item(menu::MenuItem { + label: t("sidebar_remove").to_owned(), + shortcut: None, + on_select: Message::Hide(repo.path), + danger: false, + })); + + menu::popup( + hover(item, pin), + menu_open, + entries, + Message::ContextMenu(None), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn missing_repo_row_is_marked() { + let missing = QuickStatus { + missing: true, + ..QuickStatus::default() + }; + assert_eq!(badge(Some(&missing)), Badge::Label("sidebar_missing")); + assert_ne!(t("sidebar_missing"), "sidebar_missing"); + + let busy = QuickStatus { + changed: 4, + ahead: 2, + ..QuickStatus::default() + }; + assert_eq!(badge(Some(&busy)), Badge::Counts("4 ↑2".into())); + assert_eq!(badge(Some(&QuickStatus::default())), Badge::Nothing); + assert_eq!(badge(None), Badge::Nothing); + } + + fn entry(path: &str, last_opened: i64) -> RepoEntry { + RepoEntry { + path: path.to_string(), + last_opened: Some(last_opened), + ..RepoEntry::default() + } + } + + #[test] + fn step_moves_from_the_anchor_and_stops_at_the_ends() { + let entries = [entry("/a", 3), entry("/b", 2), entry("/c", 1)]; + let mut sidebar = Sidebar::default(); + assert_eq!(sidebar.step(-1, &entries).as_deref(), Some("/c")); + assert_eq!(sidebar.step(1, &entries).as_deref(), Some("/c")); + sidebar.set_anchor("/a"); + assert_eq!(sidebar.step(1, &entries).as_deref(), Some("/b")); + + let _ = sidebar.toggle_search(&entries); + assert_eq!(sidebar.cursor().as_deref(), Some("/a")); + sidebar.step(1, &entries); + assert_eq!(sidebar.cursor().as_deref(), Some("/b")); + sidebar.close_search(); + assert_eq!(sidebar.cursor(), None); + } + + #[test] + fn step_walks_recent_although_each_open_moves_the_row_to_the_top() { + let mut config = crate::config::AppConfig::default(); + for (path, at) in [("/d", 1), ("/c", 2), ("/b", 3), ("/a", 4)] { + config.open_repo(path, at); + } + let mut sidebar = Sidebar::default(); + sidebar.set_anchor("/a"); + let mut visited = Vec::new(); + for (delta, now) in [(1, 10), (1, 11), (1, 12), (-1, 13)] { + let path = sidebar.step(delta, config.repos()).expect("a row"); + // What opening the row does: the anchor is set again and RECENT puts it first. + sidebar.set_anchor(&path); + config.open_repo(&path, now); + visited.push(path.to_string()); + } + assert_eq!(visited, ["/b", "/c", "/d", "/c"]); + let order = |sidebar: &Sidebar, config: &crate::config::AppConfig| { + let paths = sidebar.paths(config.repos()); + paths + .iter() + .map(|path| path.to_string()) + .collect::>() + }; + assert_eq!(order(&sidebar, &config), ["/a", "/b", "/c", "/d"]); + + // Picking another row ends the run: RECENT is by last opening again. + sidebar.set_anchor("/a"); + assert_eq!(order(&sidebar, &config), ["/c", "/d", "/b", "/a"]); + } + + #[test] + fn step_goes_past_a_row_that_failed_or_is_still_loading() { + // /a is open, /b's folder is gone: its load fails and /a stays the open repository. + let entries = [entry("/a", 3), entry("/b", 2), entry("/c", 1)]; + let mut sidebar = Sidebar::default(); + sidebar.set_anchor("/a"); + assert_eq!(sidebar.step(1, &entries).as_deref(), Some("/b")); + assert_eq!(sidebar.step(1, &entries).as_deref(), Some("/c")); + assert_eq!(sidebar.step(-1, &entries).as_deref(), Some("/b")); + } +} diff --git a/src/ui/stage.rs b/src/ui/stage.rs deleted file mode 100644 index bfcc5f0..0000000 --- a/src/ui/stage.rs +++ /dev/null @@ -1,1035 +0,0 @@ -// Panneau de staging et commits — migration Iced 0.13 -// Gère les fichiers staged/unstaged, les diffs, le commit editor et les stashes. -// Les appels git tournent en tâche de fond ; view() ne lit que l'état du panneau. - -use std::collections::BTreeSet; -use std::path::Path; -use std::sync::Arc; - -use git2::{Repository, Status, StatusOptions, StatusShow}; -use iced::widget::{ - button, checkbox, container, horizontal_rule, pick_list, scrollable, text, text_input, Button, - Column, Row, -}; -use iced::{Element, Length, Task}; - -use crate::ui::theme::Theme; - -use crate::git::branch::restore_file_from_branch; -use crate::git::commit::commit_index; -use crate::git::diff::diff_file; -use crate::git::stash::{apply_stash, create_stash, drop_stash, list_stashes, StashEntry}; -use crate::git::status::read_repo_status; -use crate::ui::context::RepoContext; - -/// Runs `job` for the repository at `repo` on the blocking thread pool and passes its result, -/// with the repository path, to `done`. Panels compare that path with their current repository -/// and drop results that arrive after a switch. Shared by the stage, branch and history panels. -pub(crate) fn git_task( - repo: Arc, - job: impl FnOnce(&str) -> Result + Send + 'static, - done: impl Fn(Arc, Result) -> M + Send + 'static, -) -> Task -where - M: Send + 'static, - T: Send + 'static, -{ - Task::perform( - async move { - let path = Arc::clone(&repo); - let result = tokio::task::spawn_blocking(move || job(&path)) - .await - .unwrap_or_else(|err| Err(err.to_string())); - (repo, result) - }, - move |(repo, result)| done(repo, result), - ) -} - -// ── Structures de données ────────────────────────────────────────────────── - -/// Représente un fichier dans l'index ou l'arbre de travail. -#[derive(Debug, Clone)] -pub struct FileEntry { - path: String, - status_label: String, -} - -/// État du dépôt lu en tâche de fond. -#[derive(Debug, Clone)] -pub struct Snapshot { - staged: Vec, - unstaged: Vec, - stashes: Vec, - branch: Option, - signoff_line: Option, -} - -/// Messages émis par le panneau de staging. -#[derive(Debug, Clone)] -pub enum Message { - /// Désindexer un fichier (chemin). - ToggleStaged(String), - /// Indexer un fichier (chemin). - ToggleUnstaged(String), - /// Afficher le diff d'un fichier (is_staged, chemin). - ViewDiff(bool, String), - /// Le message de commit a changé. - CommitMessageChanged(String), - /// Un template de commit a été sélectionné (index). - TemplateSelected(usize), - /// Activer/désactiver la ligne Signed-off-by. - ToggleSignoff(bool), - /// Committer l'index. - Commit, - /// Le message du stash a changé. - StashMessageChanged(String), - /// Inclure ou non les fichiers non suivis dans le stash. - ToggleIncludeUntracked(bool), - /// Créer un nouveau stash. - CreateStash, - /// Appliquer un stash existant (index). - ApplyStash(usize), - /// Demander la suppression d'un stash (index). - DropStash(usize), - /// Confirmer la suppression demandée. - ConfirmDropStash, - /// Annuler la suppression demandée. - CancelDropStash, - /// Ouvrir la boîte de dialogue de restauration. - OpenRestoreDialog(String), - /// Fermer la boîte de dialogue de restauration. - CloseRestoreDialog, - /// Confirmer la restauration du fichier sélectionné. - ConfirmRestore, - /// Sélectionner un fichier dans le dialogue de restauration. - SelectRestoreFile(String), - /// Résultat de la lecture du dépôt. - Loaded(Arc, Result), - /// Patch du fichier sélectionné ((is_staged, chemin), patch). - DiffLoaded(Arc, (bool, String), Result), - /// Fin d'une action git (message de statut ou erreur). - ActionDone(Arc, Result), - /// Fin d'un commit. - Committed(Arc, Result), -} - -// ── Templates de commit ──────────────────────────────────────────────────── - -const COMMIT_TEMPLATES: &[(&str, &str)] = &[ - ("WIP", "WIP: describe the work in progress"), - ( - "Feature", - "feat: short summary\n\n- describe the change\n- add context or links", - ), - ( - "Fix", - "fix: bug summary\n\nExplain root cause and how it was addressed.", - ), -]; - -/// Noms des templates pour le sélecteur. -fn template_names() -> Vec { - COMMIT_TEMPLATES - .iter() - .map(|(name, _)| name.to_string()) - .collect() -} - -// ── Panneau principal ────────────────────────────────────────────────────── - -pub struct StagePanel { - repo: Option>, - staged: Vec, - unstaged: Vec, - selected_diff: Option<(bool, String)>, - /// Patch du fichier sélectionné, `None` pendant le chargement. - diff: Option, - branch: Option, - status: Option, - error: Option, - /// Une action git est en cours : les boutons d'action sont désactivés. - busy: bool, - commit_message: String, - include_signoff: bool, - selected_template: usize, - /// Ligne Signed-off-by tirée de la configuration Git, si l'identité est définie. - signoff_line: Option, - stash_message: String, - stashes: Vec, - include_untracked_in_stash: bool, - /// Index du stash dont la suppression attend une confirmation. - confirm_drop: Option, - restore_dialog_open: bool, - restore_selection: Option, -} - -impl StagePanel { - /// Crée un nouveau panneau de staging. - pub fn new() -> Self { - Self { - repo: None, - staged: Vec::new(), - unstaged: Vec::new(), - selected_diff: None, - diff: None, - branch: None, - status: None, - error: None, - busy: false, - commit_message: String::new(), - include_signoff: false, - selected_template: 0, - signoff_line: None, - stash_message: String::from("WIP changes"), - stashes: Vec::new(), - include_untracked_in_stash: true, - confirm_drop: None, - restore_dialog_open: false, - restore_selection: None, - } - } - - /// Oublie le dépôt précédent et charge `repo` en tâche de fond. - /// Reloading the same repository keeps the commit and stash drafts. - pub fn load(&mut self, repo: &RepoContext) -> Task { - let fresh = Self { - repo: Some(repo.path_arc()), - ..Self::new() - }; - let previous = std::mem::replace(self, fresh); - if previous.repo.as_deref() == Some(repo.path()) { - self.commit_message = previous.commit_message; - self.include_signoff = previous.include_signoff; - self.selected_template = previous.selected_template; - self.signoff_line = previous.signoff_line; - self.stash_message = previous.stash_message; - self.include_untracked_in_stash = previous.include_untracked_in_stash; - } - self.refresh() - } - - /// Traite un message et retourne une commande Iced. - pub fn update(&mut self, message: Message, _repo: Option<&RepoContext>) -> Task { - match message { - // ── Actions sur les fichiers ──────────────────────────────── - Message::ToggleStaged(path) => { - return self.run(move |repo| { - unstage_path(repo, &path) - .map(|()| format!("Unstaged {path}")) - .map_err(|err| format!("Failed to unstage {path}: {err}")) - }); - } - Message::ToggleUnstaged(path) => { - return self.run(move |repo| { - stage_path(repo, &path) - .map(|()| format!("Staged {path}")) - .map_err(|err| format!("Failed to stage {path}: {err}")) - }); - } - Message::ViewDiff(is_staged, path) => { - self.selected_diff = Some((is_staged, path)); - self.diff = None; - return self.load_diff(); - } - - // ── Éditeur de commit ─────────────────────────────────────── - Message::CommitMessageChanged(msg) => { - self.commit_message = msg; - } - Message::TemplateSelected(idx) => { - if idx < COMMIT_TEMPLATES.len() { - self.selected_template = idx; - self.commit_message = - self.decorate_commit_message(COMMIT_TEMPLATES[idx].1.to_string()); - } - } - Message::ToggleSignoff(enabled) => { - self.include_signoff = enabled; - self.apply_signoff(); - } - Message::Commit => { - let message = self.commit_message.clone(); - return self.run_with( - move |repo| { - commit_index(repo, &message) - .map(|oid| format!("Commit {:.8} créé", oid.to_string())) - .map_err(|err| format!("Échec du commit : {err}")) - }, - Message::Committed, - ); - } - - // ── Gestion du stash ──────────────────────────────────────── - Message::StashMessageChanged(msg) => { - self.stash_message = msg; - } - Message::ToggleIncludeUntracked(enabled) => { - self.include_untracked_in_stash = enabled; - } - Message::CreateStash => { - let message = self.stash_message.trim().to_string(); - let include_untracked = self.include_untracked_in_stash; - return self.run(move |repo| { - create_stash(repo, &message, include_untracked) - .map(|()| "Stashed working tree".to_string()) - .map_err(|err| format!("Échec du stash : {err}")) - }); - } - Message::ApplyStash(index) => { - let id = self.stash_id(index); - return self.run(move |repo| { - apply_stash(repo, index, &id) - .map(|()| format!("Applied stash #{index}")) - .map_err(|err| format!("Échec de l'application du stash #{index} : {err}")) - }); - } - Message::DropStash(index) => { - self.confirm_drop = Some(index); - } - Message::CancelDropStash => { - self.confirm_drop = None; - } - Message::ConfirmDropStash => { - if let Some(index) = self.confirm_drop.take() { - let id = self.stash_id(index); - return self.run(move |repo| { - drop_stash(repo, index, &id) - .map(|()| format!("Dropped stash #{index}")) - .map_err(|err| { - format!("Échec de la suppression du stash #{index} : {err}") - }) - }); - } - } - - // ── Dialogue de restauration ──────────────────────────────── - Message::OpenRestoreDialog(path) => { - self.restore_dialog_open = true; - self.restore_selection = Some(path); - } - Message::CloseRestoreDialog => { - self.restore_dialog_open = false; - self.restore_selection = None; - } - Message::ConfirmRestore => { - if let Some(path) = self.restore_selection.clone() { - let branch = self.restore_source().to_string(); - return self.run(move |repo| { - restore_file_from_branch(repo, &branch, &path) - .map(|()| format!("Restored {path} from {branch}")) - .map_err(|err| format!("Échec de la restauration de {path} : {err}")) - }); - } - } - Message::SelectRestoreFile(path) => { - self.restore_selection = Some(path); - } - - // ── Résultats des tâches de fond ──────────────────────────── - Message::Loaded(repo, result) => { - if !self.is_current(&repo) { - return Task::none(); - } - match result { - Ok(snapshot) => return self.apply_snapshot(snapshot), - Err(err) => self.error = Some(err), - } - } - Message::DiffLoaded(repo, key, result) => { - if self.is_current(&repo) && self.selected_diff.as_ref() == Some(&key) { - self.diff = - Some(result.unwrap_or_else(|err| format!("Échec du chargement : {err}"))); - } - } - Message::ActionDone(repo, result) => { - if self.is_current(&repo) { - return self.finish_action(result); - } - } - Message::Committed(repo, result) => { - if self.is_current(&repo) { - if result.is_ok() { - self.commit_message.clear(); - self.apply_signoff(); - } - return self.finish_action(result); - } - } - } - - Task::none() - } - - /// Construit la vue du panneau de staging. - pub fn view<'a>( - &'a self, - _theme: &'a Theme, - repo: Option<&'a RepoContext>, - ) -> Element<'a, Message> { - let mut content = Column::new().spacing(8).padding(10).width(Length::Fill); - - // Titre principal - content = content.push(text("Staging & commits").size(20)); - content = content.push( - text("Review unstaged and staged changes, preview diffs, and manage commits.").size(13), - ); - - // Vérifier si un dépôt est sélectionné - if repo.is_none() { - content = - content.push(text("Open a repository to inspect and stage its changes.").size(13)); - return container(content) - .width(Length::Fill) - .height(Length::Fill) - .into(); - } - - // Erreur éventuelle, au-dessus des contrôles ; effacée à la prochaine action - if let Some(error) = &self.error { - content = content.push(text(error.as_str()).size(13).style(text::danger)); - } - - if self.busy { - content = content.push(text("Opération en cours...").size(13)); - } else if let Some(status) = &self.status { - content = content.push(text(status.as_str()).size(13)); - } - - // ── Deux colonnes : unstaged | staged ────────────────────────── - let unstaged_col = self.build_file_list(false); - let staged_col = self.build_file_list(true); - - let files_row = Row::new() - .spacing(10) - .width(Length::Fill) - .push( - container(unstaged_col) - .width(Length::FillPortion(1)) - .height(Length::Fixed(260.0)), - ) - .push( - container(staged_col) - .width(Length::FillPortion(1)) - .height(Length::Fixed(260.0)), - ); - content = content.push(files_row); - - // ── Section de prévisualisation du diff ───────────────────────── - content = content.push(self.build_diff_preview()); - - // ── Éditeur de commit + contrôles du stash côte à côte ────────── - let commit_stash_row = Row::new() - .spacing(10) - .width(Length::Fill) - .push( - container(self.build_commit_editor()) - .width(Length::FillPortion(3)) - .padding(10), - ) - .push( - container(self.build_stash_controls()) - .width(Length::FillPortion(2)) - .padding(10), - ); - content = content.push(commit_stash_row); - - // ── Dialogue de restauration (intégré dans le panneau) ────────── - if self.restore_dialog_open { - content = content.push(horizontal_rule(1)); - content = content.push(self.build_restore_dialog()); - } - - container(content) - .width(Length::Fill) - .height(Length::Fill) - .into() - } - - // ── Construction des sous-vues ───────────────────────────────────── - - /// Bouton d'action, désactivé pendant une action git. - fn action_button(&self, label: &str, message: Message) -> Button<'_, Message> { - button(text(label.to_string()).size(12)) - .padding(4) - .on_press_maybe((!self.busy).then_some(message)) - } - - /// Construit la liste de fichiers staged ou unstaged. - fn build_file_list(&self, staged: bool) -> Element<'_, Message> { - let title = if staged { - "Staged files" - } else { - "Unstaged files" - }; - let list = if staged { &self.staged } else { &self.unstaged }; - - let mut col = Column::new().spacing(4).push(text(title).size(16)); - - if list.is_empty() { - col = col.push(text("No files in this section.").size(12)); - return scrollable(col).height(Length::Fill).into(); - } - - for entry in list { - let path = entry.path.clone(); - let label = format!("{} ({})", entry.path, entry.status_label); - - // Bouton pour stage/unstage - let toggle_btn = if staged { - self.action_button("Unstage", Message::ToggleStaged(path.clone())) - } else { - self.action_button("Stage", Message::ToggleUnstaged(path.clone())) - }; - - // Bouton pour voir le diff - let diff_btn = button(text("Diff").size(12)) - .on_press(Message::ViewDiff(staged, path.clone())) - .padding(4); - - // Bouton pour restaurer - let restore_btn = button(text("Restore").size(12)) - .on_press(Message::OpenRestoreDialog(path)) - .padding(4); - - let file_row = Row::new() - .spacing(6) - .push(text(label).size(13).width(Length::Fill)) - .push(toggle_btn) - .push(diff_btn) - .push(restore_btn); - - col = col.push(file_row); - } - - scrollable(col).height(Length::Fill).into() - } - - /// Construit la section de prévisualisation du diff. - fn build_diff_preview(&self) -> Element<'_, Message> { - let mut col = Column::new().spacing(4).padding(8); - - // En-tête du diff - let header_row = match &self.selected_diff { - Some((is_staged, path)) => { - let kind = if *is_staged { "staged" } else { "unstaged" }; - Row::new() - .spacing(8) - .push(text("Diff preview").size(16)) - .push(text(format!("— {path} ({kind})")).size(13)) - } - None => Row::new().push(text("Diff preview").size(16)), - }; - col = col.push(header_row); - col = col.push(horizontal_rule(1)); - - // Contenu du diff, chargé à la sélection - if self.selected_diff.is_some() { - let diff_text = self.diff.as_deref().unwrap_or("Chargement..."); - col = col.push(scrollable(text(diff_text).size(12)).height(Length::Fixed(180.0))); - } else { - col = col.push(text("Select a file to view its patch.").size(12)); - } - - container(col).width(Length::Fill).padding(8).into() - } - - /// Construit l'éditeur de commit. - fn build_commit_editor(&self) -> Element<'_, Message> { - let mut col = Column::new().spacing(6); - - col = col.push(text("Commit editor").size(16)); - - // Sélection de template via pick_list - let names = template_names(); - let selected = names.get(self.selected_template).cloned(); - let template_picker = pick_list(names, selected, move |name| { - // Retrouver l'index à partir du nom - let idx = COMMIT_TEMPLATES - .iter() - .position(|(n, _)| *n == name) - .unwrap_or(0); - Message::TemplateSelected(idx) - }) - .placeholder("Template..."); - - let template_row = Row::new() - .spacing(8) - .push(text("Template").size(13)) - .push(template_picker); - col = col.push(template_row); - - // Zone de texte pour le message de commit - col = col.push( - text_input("Write your commit message...", &self.commit_message) - .on_input(Message::CommitMessageChanged) - .padding(6), - ); - - // Case à cocher pour le signoff, inactive sans identité Git configurée - col = col.push( - checkbox("Add Signed-off-by", self.include_signoff).on_toggle_maybe( - self.signoff_line - .is_some() - .then_some(Message::ToggleSignoff), - ), - ); - - let can_commit = !self.commit_message.trim().is_empty() && !self.staged.is_empty(); - let mut commit_btn = self.action_button("Committer", Message::Commit); - if !can_commit { - commit_btn = commit_btn.on_press_maybe(None); - } - col = col.push(commit_btn); - - col.into() - } - - /// Construit les contrôles de gestion du stash. - fn build_stash_controls(&self) -> Element<'_, Message> { - let mut col = Column::new().spacing(6); - - col = col.push(text("Stash management").size(16)); - - // Ligne de saisie + options - let stash_input = text_input("Describe the stash...", &self.stash_message) - .on_input(Message::StashMessageChanged) - .padding(4); - - let untracked_checkbox = checkbox("Include untracked", self.include_untracked_in_stash) - .on_toggle(Message::ToggleIncludeUntracked); - - let create_btn = self.action_button("Create stash", Message::CreateStash); - - let stash_row = Row::new() - .spacing(6) - .push(stash_input) - .push(untracked_checkbox) - .push(create_btn); - col = col.push(stash_row); - - col = col.push(text("Apply or drop an existing stash.").size(12)); - - // Liste des stashes existants - if self.stashes.is_empty() { - col = col.push(text("No stashes available.").size(12)); - } else { - for stash in &self.stashes { - let idx = stash.index; - let label = format!("#{} — {}", stash.index, stash.message); - - let stash_row = Row::new() - .spacing(6) - .push(text(label).size(13).width(Length::Fill)) - .push(self.action_button("Apply", Message::ApplyStash(idx))) - .push(self.action_button("Drop", Message::DropStash(idx))); - col = col.push(stash_row); - - if self.confirm_drop == Some(idx) { - col = col.push( - Row::new() - .spacing(6) - .push( - text("Supprimer définitivement ce stash ?") - .size(12) - .width(Length::Fill), - ) - .push(self.action_button("Confirmer", Message::ConfirmDropStash)) - .push( - button(text("Annuler").size(12)) - .on_press(Message::CancelDropStash) - .padding(4), - ), - ); - } - } - } - - scrollable(col).height(Length::Shrink).into() - } - - /// Construit le dialogue de restauration (en ligne, pas une fenêtre modale). - fn build_restore_dialog(&self) -> Element<'_, Message> { - let candidates = self.restore_candidates(); - - let mut col = Column::new().spacing(6).padding(8); - - col = col.push(text("Restore file").size(16)); - col = col.push( - text(format!( - "Restore file from {} (discard local changes).", - self.restore_source() - )) - .size(13), - ); - - if candidates.is_empty() { - col = col.push(text("No modified files to restore.").size(12)); - } else { - // Liste sélectionnable de fichiers - let mut list_col = Column::new().spacing(2); - for path in &candidates { - let is_selected = self.restore_selection.as_deref() == Some(path.as_str()); - let label = if is_selected { - format!("> {path}") - } else { - path.clone() - }; - let p = path.clone(); - list_col = list_col.push( - button(text(label).size(12)) - .on_press(Message::SelectRestoreFile(p)) - .padding(4) - .width(Length::Fill), - ); - } - col = col.push(scrollable(list_col).height(Length::Fixed(180.0))); - } - - // Boutons d'action - let cancel_btn = button(text("Cancel").size(12)) - .on_press(Message::CloseRestoreDialog) - .padding(4); - - // Le bouton Restore n'est actif que si un fichier est sélectionné - let mut restore_btn = self.action_button("Restore", Message::ConfirmRestore); - if self.restore_selection.is_none() { - restore_btn = restore_btn.on_press_maybe(None); - } - - let actions_row = Row::new().spacing(8).push(cancel_btn).push(restore_btn); - col = col.push(actions_row); - - container(col).width(Length::Fill).padding(8).into() - } - - // ── Méthodes internes ────────────────────────────────────────────── - - fn is_current(&self, repo: &str) -> bool { - self.repo.as_deref() == Some(repo) - } - - /// Relit les statuts, les stashes et l'identité Git en tâche de fond. - fn refresh(&self) -> Task { - match self.repo.clone() { - Some(repo) => git_task(repo, read_snapshot, Message::Loaded), - None => Task::none(), - } - } - - /// Charge le patch du fichier sélectionné. - fn load_diff(&self) -> Task { - let (Some(repo), Some(key)) = (self.repo.clone(), self.selected_diff.clone()) else { - return Task::none(); - }; - let (staged, path) = key.clone(); - git_task( - repo, - move |repo| { - diff_file(repo, &path, staged) - .map(|diff| { - diff.map_or_else( - || "(no textual diff available)\n".to_string(), - |d| d.patch, - ) - }) - .map_err(|err| err.to_string()) - }, - move |repo, result| Message::DiffLoaded(repo, key.clone(), result), - ) - } - - /// Remplace les listes par `snapshot` et recharge le diff affiché s'il existe encore. - fn apply_snapshot(&mut self, snapshot: Snapshot) -> Task { - self.staged = snapshot.staged; - self.unstaged = snapshot.unstaged; - self.stashes = snapshot.stashes; - self.branch = snapshot.branch; - if snapshot.signoff_line.is_none() { - self.include_signoff = false; - } - self.signoff_line = snapshot.signoff_line; - - let still_listed = self.selected_diff.as_ref().is_some_and(|(staged, path)| { - let list = if *staged { - &self.staged - } else { - &self.unstaged - }; - list.iter().any(|entry| &entry.path == path) - }); - if still_listed { - self.load_diff() - } else { - self.selected_diff = None; - self.diff = None; - Task::none() - } - } - - /// Lance une action git si aucune n'est en cours, après avoir effacé l'erreur et le - /// statut précédents ; la liste est relue à la fin. - fn run( - &mut self, - job: impl FnOnce(&str) -> Result + Send + 'static, - ) -> Task { - self.run_with(job, Message::ActionDone) - } - - fn run_with( - &mut self, - job: impl FnOnce(&str) -> Result + Send + 'static, - done: fn(Arc, Result) -> Message, - ) -> Task { - let Some(repo) = self.repo.clone() else { - return Task::none(); - }; - if self.busy { - return Task::none(); - } - self.busy = true; - self.error = None; - self.status = None; - git_task(repo, job, done) - } - - /// Affiche le résultat d'une action puis relit le dépôt, y compris après une erreur - /// (par exemple une liste de stashes qui a changé). - fn finish_action(&mut self, result: Result) -> Task { - self.busy = false; - match result { - Ok(status) => { - self.status = Some(status); - self.restore_dialog_open = false; - self.restore_selection = None; - } - Err(err) => self.error = Some(err), - } - self.refresh() - } - - /// Identifiant du stash à `index` dans la liste affichée ; vide s'il a disparu, ce que - /// la couche git refuse. - fn stash_id(&self, index: usize) -> String { - self.stashes - .iter() - .find(|stash| stash.index == index) - .map(|stash| stash.id.clone()) - .unwrap_or_default() - } - - /// Branche d'où restaurer les fichiers. - fn restore_source(&self) -> &str { - self.branch.as_deref().unwrap_or("HEAD") - } - - /// Applique ou retire la ligne Signed-off-by du message. - fn apply_signoff(&mut self) { - let Some(line) = self.signoff_line.clone() else { - return; - }; - if self.include_signoff && !self.commit_message.contains(&line) { - if !self.commit_message.ends_with('\n') && !self.commit_message.is_empty() { - self.commit_message.push('\n'); - } - if !self.commit_message.ends_with('\n') { - self.commit_message.push('\n'); - } - self.commit_message.push_str(&line); - } else if !self.include_signoff { - if let Some(idx) = self.commit_message.find(&line) { - self.commit_message.replace_range(idx..idx + line.len(), ""); - self.commit_message = self.commit_message.trim_end().to_string(); - } - } - } - - /// Décore un message de commit avec la ligne signoff si activée. - fn decorate_commit_message(&self, message: String) -> String { - match &self.signoff_line { - Some(line) if self.include_signoff => { - let mut msg = message; - if !msg.ends_with('\n') { - msg.push('\n'); - } - msg.push_str(line); - msg - } - _ => message, - } - } - - /// Retourne la liste triée des fichiers modifiés (candidats à la restauration). - fn restore_candidates(&self) -> Vec { - let mut candidates = BTreeSet::new(); - for entry in self.staged.iter().chain(self.unstaged.iter()) { - candidates.insert(entry.path.clone()); - } - candidates.into_iter().collect() - } -} - -// ── Fonctions backend ────────────────────────────────────────────────────── - -/// Formate un label lisible à partir du statut git2. -fn format_status_label(status: Status) -> String { - if status.is_wt_new() || status.is_index_new() { - "added".to_string() - } else if status.is_wt_deleted() || status.is_index_deleted() { - "deleted".to_string() - } else if status.is_wt_modified() || status.is_index_modified() { - "modified".to_string() - } else if status.is_wt_renamed() || status.is_index_renamed() { - "renamed".to_string() - } else { - "changed".to_string() - } -} - -/// Lit les fichiers modifiés, les stashes, la branche et l'identité Git. Les patches ne sont -/// pas calculés ici : seul celui du fichier sélectionné est chargé. -fn read_snapshot(repo_path: &str) -> Result { - let repo = Repository::open(repo_path).map_err(|err| err.to_string())?; - let (staged, unstaged) = - read_statuses(&repo).map_err(|err| format!("Failed to read changes: {err}"))?; - let stashes = - list_stashes(repo_path).map_err(|err| format!("Failed to read stashes: {err}"))?; - let branch = read_repo_status(repo_path).ok().and_then(|s| s.branch); - let signoff_line = repo.signature().ok().map(|sig| { - format!( - "Signed-off-by: {} <{}>", - sig.name().unwrap_or_default(), - sig.email().unwrap_or_default() - ) - }); - Ok(Snapshot { - staged, - unstaged, - stashes, - branch, - signoff_line, - }) -} - -/// Lit les statuts staged et unstaged depuis le dépôt. -fn read_statuses(repo: &Repository) -> Result<(Vec, Vec), git2::Error> { - let mut status_opts = StatusOptions::new(); - status_opts - .show(StatusShow::IndexAndWorkdir) - .include_untracked(true) - .recurse_untracked_dirs(true) - .include_unmodified(false); - - let statuses = repo.statuses(Some(&mut status_opts))?; - - let mut staged = Vec::new(); - let mut unstaged = Vec::new(); - - for entry in statuses.iter() { - let path = entry.path().unwrap_or("(unknown)").to_string(); - let status = entry.status(); - - if status.is_index_new() - || status.is_index_modified() - || status.is_index_deleted() - || status.is_index_renamed() - || status.is_index_typechange() - { - staged.push(FileEntry { - status_label: format_status_label(status), - path: path.clone(), - }); - } - - if status.is_wt_new() - || status.is_wt_modified() - || status.is_wt_deleted() - || status.is_wt_renamed() - || status.is_wt_typechange() - { - unstaged.push(FileEntry { - status_label: format_status_label(status), - path, - }); - } - } - - Ok((staged, unstaged)) -} - -/// Indexe un fichier du dépôt : son contenu s'il existe dans l'arbre de travail, sinon sa -/// suppression. `path` est relatif à la racine du dépôt, pas au dossier courant du processus. -fn stage_path(repo_path: &str, path: &str) -> Result<(), git2::Error> { - let repo = Repository::open(repo_path)?; - let workdir = repo - .workdir() - .ok_or_else(|| git2::Error::from_str("bare repository has no working tree"))?; - let mut index = repo.index()?; - let path_ref = Path::new(path); - // symlink_metadata: a dangling symlink is still a file to add. - if workdir.join(path_ref).symlink_metadata().is_ok() { - index.add_path(path_ref)?; - } else { - index.remove_path(path_ref)?; - } - index.write() -} - -/// Désindexe un fichier du dépôt git. -fn unstage_path(repo_path: &str, path: &str) -> Result<(), git2::Error> { - let repo = Repository::open(repo_path)?; - repo.reset_default(None, [Path::new(path)]) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn stage_path_resolves_files_in_the_repository_not_the_process_cwd() { - let dir = tempfile::tempdir().unwrap(); - let repo = Repository::init(dir.path()).unwrap(); - let mut config = repo.config().unwrap(); - config.set_str("user.name", "Test User").unwrap(); - config.set_str("user.email", "test@example.com").unwrap(); - let repo_path = dir.path().to_str().unwrap(); - - // Cargo runs tests from the crate root, which has a Cargo.toml and no notes file. - // The old code checked these names there and got both of them wrong. - let modified = "only-in-the-test-repo.txt"; - let deleted = "Cargo.toml"; - let workdir = dir.path(); - std::fs::write(workdir.join(modified), "one").unwrap(); - std::fs::write(workdir.join(deleted), "[package]").unwrap(); - stage_path(repo_path, modified).unwrap(); - stage_path(repo_path, deleted).unwrap(); - commit_index(repo_path, "initial").unwrap(); - - std::fs::write(workdir.join(modified), "two").unwrap(); - std::fs::remove_file(workdir.join(deleted)).unwrap(); - stage_path(repo_path, modified).unwrap(); - stage_path(repo_path, deleted).unwrap(); - - let status = |name| repo.status_file(Path::new(name)).unwrap(); - assert_eq!(status(modified), Status::INDEX_MODIFIED); - assert_eq!(status(deleted), Status::INDEX_DELETED); - } - - #[test] - fn snapshot_lists_changes_without_patches_and_reads_the_signoff() { - let dir = tempfile::tempdir().unwrap(); - let repo = Repository::init(dir.path()).unwrap(); - let mut config = repo.config().unwrap(); - config.set_str("user.name", "Test User").unwrap(); - config.set_str("user.email", "test@example.com").unwrap(); - std::fs::write(dir.path().join("new.txt"), "x").unwrap(); - - let snapshot = read_snapshot(dir.path().to_str().unwrap()).unwrap(); - assert!(snapshot.staged.is_empty()); - assert_eq!(snapshot.unstaged[0].path, "new.txt"); - assert_eq!( - snapshot.signoff_line.as_deref(), - Some("Signed-off-by: Test User ") - ); - } -} diff --git a/src/ui/stashes.rs b/src/ui/stashes.rs new file mode 100644 index 0000000..349409e --- /dev/null +++ b/src/ui/stashes.rs @@ -0,0 +1,851 @@ +//! The Stashes tab: a bar that stashes the working tree, one card per stash with Apply and +//! a "⋯" menu, and the files and diff of the stash whose contents are shown. Git reads and +//! actions run in background tasks; `view` only reads the panel's state. + +use std::sync::Arc; + +use colony_ui::theme::{contrast_on, Palette}; +use colony_ui::widgets::icons; +use colony_ui::{fonts, Typography}; +use iced::widget::{button, column, container, row, scrollable, text, text_input, Column, Space}; +use iced::{Alignment, Border, Element, Length, Task}; + +use crate::git::diff::FileDiffSummary; +use crate::git::stash::{ + apply_stash, count_stashable, create_stash, drop_stash, list_stashes, stash_file_patch, + stash_files, StashEntry, +}; +use crate::i18n::{t, tf}; +use crate::ui::changes::{field, horizontal_divider, item, question, vertical_divider}; +use crate::ui::context::{git_task, RepoContext}; +use crate::ui::diff_view::{self, Diff}; +use crate::ui::history::relative_time; +use crate::ui::widgets::button as gs_button; +use crate::ui::widgets::menu::{self, Entry}; +use crate::ui::widgets::toast::Toast; + +const MORE_GLYPH: &str = "\u{f141}"; +/// Width of the stash list while a stash's contents are shown. +const LIST_WIDTH: f32 = 420.0; +/// The failure title of "Stash changes"; its success also clears the message field. +const CREATE_FAILED: &str = "stashes_create_failed"; + +/// The stashes and how many files a stash made now would take. +#[derive(Debug, Clone)] +pub struct Snapshot { + stashes: Vec, + stashable: usize, +} + +/// A step of "Apply and drop". +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Step { + Apply, + Drop, +} + +#[derive(Debug, Clone)] +#[expect( + clippy::enum_variant_names, + reason = "`Message(String)` edits the stash's message, the plan's name for it" +)] +pub enum Message { + /// A read of the stashes, numbered so that only the latest one is shown. + Loaded(Arc, u64, Result), + /// The new stash's message was edited. + Message(String), + ToggleUntracked, + Create, + Apply(usize, String), + ApplyAndDrop(usize, String), + /// Asks to confirm dropping a stash, or closes the question. + ConfirmDrop(Option<(usize, String)>), + Drop(usize, String), + /// Opens the "⋯" menu of the stash with this id, or closes it. + Menu(Option), + /// Shows the files and diff of a stash. + Show(usize, String), + CloseContents, + FilesLoaded(Arc, String, Result, String>), + SelectFile(String), + /// The patch of `(stash id, file)`. + PatchLoaded( + Arc, + (String, String), + Result, String>, + ), + /// The success message, or the error; the key names the failure title. + Done(Arc, &'static str, Result), +} + +pub struct StashesPanel { + repo: Option>, + stashes: Vec, + stashable: usize, + loaded: bool, + error: Option, + /// Number of the last read; older replies are dropped. + request: u64, + message: String, + include_untracked: bool, + menu: Option, + confirm_drop: Option<(usize, String)>, + busy: bool, + /// The stash whose contents are shown, by index and id. + shown: Option<(usize, String)>, + files: Vec, + files_error: Option, + selected_file: Option, + diff: Option, +} + +impl Default for StashesPanel { + fn default() -> Self { + Self { + repo: None, + stashes: Vec::new(), + stashable: 0, + loaded: false, + error: None, + request: 0, + message: String::new(), + include_untracked: true, + menu: None, + confirm_drop: None, + busy: false, + shown: None, + files: Vec::new(), + files_error: None, + selected_file: None, + diff: None, + } + } +} + +impl StashesPanel { + /// Reads the stashes of `repo` in the background. Reloading the same repository keeps + /// the message draft, the untracked toggle and the shown stash. + pub fn load(&mut self, repo: &RepoContext) -> Task { + if !self.is_current(repo.path()) { + // Keep request numbers growing so a reply from before the reset is dropped. + let request = self.request; + *self = Self { + repo: Some(repo.path_arc()), + request, + ..Self::default() + }; + } + self.refresh() + } + + /// The number of stashes, shown on the Stashes tab. + pub fn count(&self) -> usize { + self.stashes.len() + } + + /// Handles a message; the toast, if any, is for the application to show. + pub fn update(&mut self, message: Message) -> (Task, Option) { + match message { + Message::Loaded(repo, request, result) => { + if self.is_current(&repo) && request == self.request { + self.loaded = true; + match result { + Ok(snapshot) => self.apply_snapshot(snapshot), + Err(err) => self.error = Some(err), + } + } + } + Message::Message(value) => self.message = value, + Message::ToggleUntracked => { + self.include_untracked = !self.include_untracked; + return (self.refresh(), None); + } + Message::Create => { + if self.stashable == 0 { + return (Task::none(), None); + } + let message = self.message.trim().to_string(); + let include_untracked = self.include_untracked; + let task = self.run(CREATE_FAILED, move |repo| { + create_stash(repo, &message, include_untracked) + .map(|()| t("stashes_created").to_string()) + .map_err(|err| err.to_string()) + }); + return (task, None); + } + Message::Apply(index, id) => { + self.menu = None; + let task = self.run("stashes_apply_failed", move |repo| { + apply_stash(repo, index, &id) + .map(|conflicts| { + let key = if conflicts { + "stashes_applied_conflicts" + } else { + "stashes_applied" + }; + tf(key, &[("index", &index.to_string())]) + }) + .map_err(|err| err.to_string()) + }); + return (task, None); + } + Message::ApplyAndDrop(index, id) => { + self.menu = None; + let task = self.run("stashes_apply_drop_failed", move |repo| { + apply_and_drop(repo, index, &id) + }); + return (task, None); + } + Message::ConfirmDrop(target) => { + self.menu = None; + self.confirm_drop = target; + } + Message::Drop(index, id) => { + self.confirm_drop = None; + let task = self.run("stashes_drop_failed", move |repo| { + drop_stash(repo, index, &id) + .map(|()| tf("stashes_dropped", &[("index", &index.to_string())])) + .map_err(|err| err.to_string()) + }); + return (task, None); + } + Message::Menu(id) => self.menu = id, + Message::Show(index, id) => return (self.show(index, id), None), + Message::CloseContents => self.close_contents(), + Message::FilesLoaded(repo, id, result) => { + if self.is_current(&repo) && self.shown_id() == Some(id.as_str()) { + match result { + Ok(files) => { + self.files = files; + match self.files.first() { + Some(file) => { + let path = file.path.clone(); + return (self.select_file(path), None); + } + None => self.diff = Some(Diff::Empty), + } + } + Err(err) => { + self.files_error = Some(err); + self.diff = None; + // The stash list may have changed under the shown stash. + return (self.refresh(), None); + } + } + } + } + Message::SelectFile(path) => return (self.select_file(path), None), + Message::PatchLoaded(repo, (id, path), result) => { + if self.is_current(&repo) + && self.shown_id() == Some(id.as_str()) + && self.selected_file.as_ref() == Some(&path) + { + let failed = result.is_err(); + self.diff = Some(Diff::loaded(result)); + if failed { + return (self.refresh(), None); + } + } + } + Message::Done(repo, failed, result) => { + if self.is_current(&repo) { + self.busy = false; + let toast = match result { + Ok(message) => { + if failed == CREATE_FAILED { + self.message.clear(); + } + Toast::success(message) + } + Err(err) => Toast::error(t(failed), err), + }; + // Also reloads after a "list changed" error. + return (self.refresh(), Some(toast)); + } + } + } + (Task::none(), None) + } + + fn is_current(&self, repo: &str) -> bool { + self.repo.as_deref() == Some(repo) + } + + fn shown_id(&self) -> Option<&str> { + self.shown.as_ref().map(|(_, id)| id.as_str()) + } + + fn refresh(&mut self) -> Task { + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + self.request += 1; + let request = self.request; + let include_untracked = self.include_untracked; + git_task( + repo, + move |repo| read_snapshot(repo, include_untracked), + move |repo, result| Message::Loaded(repo, request, result), + ) + } + + /// Takes the new list. A stash still listed keeps its menu, question and contents at + /// its new index; those of a stash that is gone close. + fn apply_snapshot(&mut self, snapshot: Snapshot) { + self.error = None; + self.stashes = snapshot.stashes; + self.stashable = snapshot.stashable; + let index_of = |id: &str| { + self.stashes + .iter() + .find(|stash| stash.id == id) + .map(|stash| stash.index) + }; + self.confirm_drop = self + .confirm_drop + .take() + .and_then(|(_, id)| Some((index_of(&id)?, id))); + if self + .menu + .as_deref() + .is_some_and(|id| index_of(id).is_none()) + { + self.menu = None; + } + if let Some((_, id)) = self.shown.take() { + match index_of(&id) { + Some(index) => self.shown = Some((index, id)), + None => self.close_contents(), + } + } + } + + fn show(&mut self, index: usize, id: String) -> Task { + self.menu = None; + self.close_contents(); + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + self.shown = Some((index, id.clone())); + self.diff = Some(Diff::Loading); + let job_id = id.clone(); + git_task( + repo, + move |repo| stash_files(repo, index, &job_id).map_err(|err| err.to_string()), + move |repo, result| Message::FilesLoaded(repo, id.clone(), result), + ) + } + + fn close_contents(&mut self) { + self.shown = None; + self.files.clear(); + self.files_error = None; + self.selected_file = None; + self.diff = None; + } + + fn select_file(&mut self, path: String) -> Task { + let (Some(repo), Some((index, id))) = (self.repo.clone(), self.shown.clone()) else { + return Task::none(); + }; + self.selected_file = Some(path.clone()); + self.diff = Some(Diff::Loading); + let key = (id.clone(), path.clone()); + git_task( + repo, + move |repo| { + stash_file_patch(repo, index, &id, &path) + .map(|diff| diff.map(|diff| (diff.patch, diff.truncated))) + .map_err(|err| err.to_string()) + }, + move |repo, result| Message::PatchLoaded(repo, key.clone(), result), + ) + } + + /// Runs a git action unless one is running; the list is read again when it ends. + fn run( + &mut self, + failed: &'static str, + job: impl FnOnce(&str) -> Result + Send + 'static, + ) -> Task { + let Some(repo) = self.repo.clone() else { + return Task::none(); + }; + if self.busy { + return Task::none(); + } + self.busy = true; + git_task(repo, job, move |repo, result| { + Message::Done(repo, failed, result) + }) + } + + pub fn view(&self) -> Element<'_, Message> { + let list = column![self.new_stash_bar(), self.cards()] + .spacing(14) + .padding([18, 22]) + .height(Length::Fill); + if self.shown.is_none() { + return list.width(Length::Fill).into(); + } + row![ + list.width(Length::Fixed(LIST_WIDTH)), + vertical_divider(), + self.contents() + ] + .height(Length::Fill) + .into() + } + + /// The message field, the untracked toggle and "Stash changes", then the number of + /// files a stash would take. + fn new_stash_bar(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let ready = !self.busy && self.stashable > 0; + let input = field( + text_input(t("stashes_message_placeholder"), &self.message) + .on_input(Message::Message) + .on_submit_maybe(ready.then_some(Message::Create)), + None, + ); + let bar = container( + row![ + input, + self.untracked_toggle(), + gs_button::primary(t("stashes_create"), ready.then_some(Message::Create)), + ] + .spacing(8) + .align_y(Alignment::Center), + ) + .padding(10) + .width(Length::Fill) + .style(|_| container::Style { + background: Some(Palette::BG_SIDEBAR().into()), + border: Border::default().rounded(10), + ..Default::default() + }); + let count = match self.stashable { + 0 => t("stashes_nothing_to_stash").to_string(), + 1 => t("stashes_will_stash_one").to_string(), + count => tf("stashes_will_stash_many", &[("count", &count.to_string())]), + }; + let mut content = column![bar].spacing(8); + if self.loaded { + content = content.push( + text(count) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + ); + } + content.into() + } + + /// "Include untracked files" with a check box drawn like the Changes tab's. + fn untracked_toggle(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let on = self.include_untracked; + let accent = Palette::ACCENT(); + let check = container( + text(if on { icons::CHECK } else { "" }) + .size(typo.sz(9)) + .font(fonts::glyph_font()) + .color(contrast_on(accent)) + .center(), + ) + .width(14) + .height(14) + .style(move |_| container::Style { + background: on.then(|| accent.into()), + border: Border::default().rounded(4).width(1).color(if on { + accent + } else { + Palette::BG_SELECTED() + }), + ..Default::default() + }); + button( + row![ + check, + text(t("stashes_include_untracked")) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIM()), + ] + .spacing(6) + .align_y(Alignment::Center), + ) + .padding([4, 6]) + .on_press_maybe((!self.busy).then_some(Message::ToggleUntracked)) + .style(|_, _| button::Style::default()) + .into() + } + + /// One card per stash, each followed by its drop question when open; or the empty + /// state. + fn cards(&self) -> Element<'_, Message> { + let typo = Typography::current(); + if let Some(err) = &self.error { + return note_line(tf("stashes_load_failed", &[("error", err)])); + } + if self.loaded && self.stashes.is_empty() { + return container( + column![ + text(t("stashes_empty_title")) + .size(typo.sz(15)) + .font(typo.bold) + .color(Palette::TEXT_PRIMARY()), + text(t("stashes_empty_detail")) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + ] + .spacing(6) + .align_x(Alignment::Center), + ) + .center(Length::Fill) + .into(); + } + let now = chrono::Utc::now().timestamp(); + let mut cards = Column::new().spacing(8); + for stash in &self.stashes { + cards = cards.push(self.card(stash, now)); + if let Some((index, id)) = &self.confirm_drop { + if *id == stash.id { + cards = cards.push(question( + vec![text(tf( + "stashes_drop_confirm", + &[ + ("index", &index.to_string()), + ("message", stash_title(&stash.message)), + ], + )) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY()) + .into()], + gs_button::danger( + t("stashes_drop_button"), + (!self.busy).then(|| Message::Drop(*index, id.clone())), + ), + Message::ConfirmDrop(None), + )); + } + } + } + scrollable(cards).height(Length::Fill).into() + } + + /// "#0", the message over "on · · N files", Apply and "⋯". + fn card<'a>(&'a self, stash: &'a StashEntry, now: i64) -> Element<'a, Message> { + let typo = Typography::current(); + let (index, id) = (stash.index, &stash.id); + let mut meta = vec![match &stash.branch { + Some(branch) => tf("stashes_on_branch", &[("branch", branch)]), + None => t("stashes_detached").to_string(), + }]; + meta.push(relative_time(stash.time, now)); + meta.push(if stash.file_count == 1 { + t("stashes_one_file").to_string() + } else { + tf("stashes_files", &[("count", &stash.file_count.to_string())]) + }); + + let menu_open = self.menu.as_ref() == Some(id); + let entries = vec![ + item( + t("stashes_show_contents"), + Message::Show(index, id.clone()), + false, + ), + item( + t("stashes_apply_and_drop"), + Message::ApplyAndDrop(index, id.clone()), + false, + ), + Entry::Separator, + item( + t("stashes_drop"), + Message::ConfirmDrop(Some((index, id.clone()))), + true, + ), + ]; + let more = menu::popup( + gs_button::icon( + MORE_GLYPH, + Some(Message::Menu((!menu_open).then(|| id.clone()))), + t("stashes_actions"), + ), + menu_open, + entries, + Message::Menu(None), + ); + let shown = self.shown_id() == Some(id.as_str()); + container( + row![ + text(format!("#{index}")) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .width(28), + column![ + text(stash_title(&stash.message)) + .size(typo.sz(13)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()), + text(meta.join(" · ")) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()), + ] + .spacing(3) + .width(Length::Fill), + gs_button::secondary( + t("stashes_apply"), + (!self.busy).then(|| Message::Apply(index, id.clone())), + ), + more, + ] + .spacing(14) + .align_y(Alignment::Center), + ) + .padding([12, 14]) + .width(Length::Fill) + .style(move |_| container::Style { + background: Some( + if shown { + Palette::BG_CARD_HOVER() + } else { + Palette::BG_SIDEBAR() + } + .into(), + ), + border: Border::default().rounded(10), + ..Default::default() + }) + .into() + } + + /// The shown stash's title with a close button, its files, then the selected file's diff. + fn contents(&self) -> Element<'_, Message> { + let typo = Typography::current(); + let Some((index, id)) = &self.shown else { + return Space::new().into(); + }; + let title = self + .stashes + .iter() + .find(|stash| &stash.id == id) + .map_or("", |stash| stash_title(&stash.message)); + let header = row![ + text(format!("#{index} {title}")) + .size(typo.sz(13)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()) + .width(Length::Fill), + gs_button::icon( + icons::CLOSE, + Some(Message::CloseContents), + t("stashes_close_contents"), + ), + ] + .spacing(10) + .align_y(Alignment::Center) + .padding([10, 16]); + + let mut files = Column::new().spacing(1); + if let Some(err) = &self.files_error { + files = files.push(note_line(err.clone())); + } + for file in &self.files { + files = files.push(self.file_row(file)); + } + column![ + header, + horizontal_divider(), + container(scrollable(files.padding([6, 10]))).max_height(180.0), + horizontal_divider(), + diff_view::pane(self.diff.as_ref(), t("stashes_select_file")), + ] + .width(Length::Fill) + .height(Length::Fill) + .into() + } + + /// A file of the shown stash: its name and folder, then +N −N. + fn file_row<'a>(&'a self, file: &'a FileDiffSummary) -> Element<'a, Message> { + let typo = Typography::current(); + let selected = self.selected_file.as_deref() == Some(file.path.as_str()); + let (folder, name) = file + .path + .rsplit_once('/') + .unwrap_or(("", file.path.as_str())); + let mut content = row![ + text(name) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_PRIMARY()), + text(folder) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()) + .width(Length::Fill), + ] + .spacing(8) + .align_y(Alignment::Center); + if file.additions > 0 { + content = content.push( + text(format!("+{}", file.additions)) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::SUCCESS()), + ); + } + if file.deletions > 0 { + content = content.push( + text(format!("−{}", file.deletions)) + .size(typo.sz(10)) + .font(typo.regular) + .color(Palette::ERROR()), + ); + } + button(content) + .on_press(Message::SelectFile(file.path.clone())) + .padding([5, 8]) + .width(Length::Fill) + .style(move |_, status| button::Style { + background: (selected + || matches!(status, button::Status::Hovered | button::Status::Pressed)) + .then(|| Palette::BG_CARD_HOVER().into()), + border: Border::default().rounded(6), + ..Default::default() + }) + .into() + } +} + +/// Applies the stash, then drops it unless the apply left conflicts, as `git stash pop` does. +fn apply_and_drop(repo: &str, index: usize, id: &str) -> Result { + apply_then_drop(|step| match step { + Step::Apply => match apply_stash(repo, index, id) { + Ok(false) => Ok(()), + Ok(true) => Err(t("stashes_conflicts_kept").to_string()), + Err(err) => Err(err.to_string()), + }, + Step::Drop => drop_stash(repo, index, id).map_err(|err| err.to_string()), + }) + .map(|()| tf("stashes_applied_dropped", &[("index", &index.to_string())])) +} + +/// Applies a stash, then drops it. The drop runs only once the apply succeeded, so a +/// failed apply keeps the stash. +fn apply_then_drop(mut run: impl FnMut(Step) -> Result<(), String>) -> Result<(), String> { + run(Step::Apply)?; + run(Step::Drop).map_err(|err| tf("stashes_applied_not_dropped", &[("error", &err)])) +} + +/// The message without git's "On : " or "WIP on : " prefix, which the +/// card's second line already shows. Branch names cannot contain ':'. +fn stash_title(message: &str) -> &str { + if message.starts_with("On ") || message.starts_with("WIP on ") { + if let Some((_, rest)) = message.split_once(": ") { + return rest; + } + } + message +} + +fn read_snapshot(repo: &str, include_untracked: bool) -> Result { + let stashes = list_stashes(repo).map_err(|err| err.to_string())?; + let stashable = count_stashable(repo, include_untracked).map_err(|err| err.to_string())?; + Ok(Snapshot { stashes, stashable }) +} + +fn note_line<'a>(label: String) -> Element<'a, Message> { + let typo = Typography::current(); + text(label) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMER()) + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn apply_and_drop_runs_drop_only_after_apply_succeeds() { + let mut steps = Vec::new(); + let result = apply_then_drop(|step| { + steps.push(step); + Ok(()) + }); + assert!(result.is_ok()); + assert_eq!(steps, [Step::Apply, Step::Drop]); + + let mut steps = Vec::new(); + let result = apply_then_drop(|step| { + steps.push(step); + match step { + Step::Apply => Err("conflict".to_string()), + Step::Drop => Ok(()), + } + }); + assert_eq!(result, Err("conflict".to_string())); + assert_eq!(steps, [Step::Apply], "a failed apply keeps the stash"); + + let result = apply_then_drop(|step| match step { + Step::Apply => Ok(()), + Step::Drop => Err("locked".to_string()), + }); + let err = result.unwrap_err(); + assert!(err.contains("locked"), "{err}"); + assert_ne!(err, "locked", "says the stash was applied"); + } + + #[test] + fn apply_and_drop_keeps_a_stash_that_left_conflicts() { + let dir = tempfile::tempdir().unwrap(); + let mut options = git2::RepositoryInitOptions::new(); + options.initial_head("main"); + let repo = git2::Repository::init_opts(dir.path(), &options).unwrap(); + let path = dir.path().to_str().unwrap(); + let file = dir.path().join("a.txt"); + let commit = |contents: &str| { + std::fs::write(&file, contents).unwrap(); + let mut index = repo.index().unwrap(); + index.add_path(std::path::Path::new("a.txt")).unwrap(); + index.write().unwrap(); + let tree = repo.find_tree(index.write_tree().unwrap()).unwrap(); + let sig = git2::Signature::now("Tester", "tester@example.com").unwrap(); + let parent = repo.head().ok().and_then(|head| head.peel_to_commit().ok()); + let parents: Vec<_> = parent.iter().collect(); + repo.commit(Some("HEAD"), &sig, &sig, "edit", &tree, &parents) + .unwrap(); + }; + commit("base"); + std::fs::write(&file, "stashed").unwrap(); + create_stash(path, "a", false).unwrap(); + commit("committed"); + + let stash = list_stashes(path).unwrap().remove(0); + let err = apply_and_drop(path, stash.index, &stash.id).unwrap_err(); + + assert_eq!(err, t("stashes_conflicts_kept")); + assert_eq!(list_stashes(path).unwrap().len(), 1, "the stash is kept"); + } + + #[test] + fn stash_title_drops_the_branch_prefix() { + assert_eq!( + stash_title("On main: WIP badge colours"), + "WIP badge colours" + ); + assert_eq!( + stash_title("WIP on feature/x: 1a2b3c4 summary"), + "1a2b3c4 summary" + ); + assert_eq!(stash_title("custom: message"), "custom: message"); + } +} diff --git a/src/ui/theme.rs b/src/ui/theme.rs deleted file mode 100644 index 8206423..0000000 --- a/src/ui/theme.rs +++ /dev/null @@ -1,164 +0,0 @@ -//! Système de thèmes Catppuccin pour GitSpace avec Iced. -//! -//! Fournit les palettes Latte, Frappé, Macchiato et Mocha en tant que -//! thèmes custom Iced, avec les tokens de typographie et d'espacement. - -use iced::Color; - -use crate::config::ThemeMode; - -/// Palette de couleurs Catppuccin. -#[derive(Debug, Clone)] -pub struct Palette { - pub background: Color, - pub surface: Color, - pub surface_highlight: Color, - pub text_primary: Color, - pub text_secondary: Color, - pub accent: Color, - pub accent_weak: Color, -} - -impl Palette { - pub fn latte() -> Self { - Self { - background: color_from_rgb(0xef, 0xf1, 0xf5), - surface: color_from_rgb(0xe6, 0xe9, 0xef), - surface_highlight: color_from_rgb(0xcc, 0xd0, 0xda), - text_primary: color_from_rgb(0x4c, 0x4f, 0x69), - text_secondary: color_from_rgb(0x5c, 0x5f, 0x77), - accent: color_from_rgb(0x1e, 0x66, 0xf5), - accent_weak: color_from_rgb(0x20, 0x9f, 0xb5), - } - } - - pub fn frappe() -> Self { - Self { - background: color_from_rgb(0x23, 0x26, 0x34), - surface: color_from_rgb(0x29, 0x2c, 0x3c), - surface_highlight: color_from_rgb(0x41, 0x45, 0x59), - text_primary: color_from_rgb(0xc6, 0xd0, 0xf5), - text_secondary: color_from_rgb(0xb5, 0xbf, 0xe2), - accent: color_from_rgb(0x8c, 0xaa, 0xee), - accent_weak: color_from_rgb(0x85, 0xc1, 0xdc), - } - } - - pub fn macchiato() -> Self { - Self { - background: color_from_rgb(0x18, 0x19, 0x26), - surface: color_from_rgb(0x1e, 0x20, 0x30), - surface_highlight: color_from_rgb(0x36, 0x3a, 0x4f), - text_primary: color_from_rgb(0xca, 0xd3, 0xf5), - text_secondary: color_from_rgb(0xb8, 0xc0, 0xe0), - accent: color_from_rgb(0x8a, 0xad, 0xf4), - accent_weak: color_from_rgb(0x7d, 0xc4, 0xe4), - } - } - - pub fn mocha() -> Self { - Self { - background: color_from_rgb(0x11, 0x11, 0x1b), - surface: color_from_rgb(0x18, 0x18, 0x25), - surface_highlight: color_from_rgb(0x31, 0x32, 0x44), - text_primary: color_from_rgb(0xcd, 0xd6, 0xf4), - text_secondary: color_from_rgb(0xba, 0xc2, 0xde), - accent: color_from_rgb(0x89, 0xb4, 0xfa), - accent_weak: color_from_rgb(0x74, 0xc7, 0xec), - } - } -} - -/// Tokens de typographie. -#[derive(Debug, Clone)] -pub struct Typography { - pub heading: f32, - pub title: f32, - pub body: f32, - pub label: f32, -} - -impl Default for Typography { - fn default() -> Self { - Self { - heading: 28.0, - title: 20.0, - body: 16.0, - label: 14.0, - } - } -} - -/// Tokens d'espacement. -#[derive(Debug, Clone, Copy)] -pub struct Spacing { - pub xs: f32, - pub sm: f32, - pub md: f32, - pub lg: f32, -} - -impl Default for Spacing { - fn default() -> Self { - Self { - xs: 4.0, - sm: 8.0, - md: 12.0, - lg: 16.0, - } - } -} - -/// Thème GitSpace complet avec palette, typographie et espacement. -#[derive(Debug, Clone)] -pub struct Theme { - pub palette: Palette, - pub typography: Typography, - pub spacing: Spacing, -} - -impl Theme { - fn with_palette(palette: Palette) -> Self { - Self { - palette, - typography: Typography::default(), - spacing: Spacing::default(), - } - } - - pub fn from_mode(mode: ThemeMode) -> Self { - match mode { - ThemeMode::Latte => Self::with_palette(Palette::latte()), - ThemeMode::Frappe => Self::with_palette(Palette::frappe()), - ThemeMode::Macchiato => Self::with_palette(Palette::macchiato()), - ThemeMode::Mocha => Self::with_palette(Palette::mocha()), - } - } - - /// Convertit le thème GitSpace en thème Iced natif. - pub fn to_iced_theme(&self) -> iced::Theme { - let iced_palette = iced::theme::Palette { - background: self.palette.background, - text: self.palette.text_primary, - primary: self.palette.accent, - success: color_from_rgb(0xa6, 0xe3, 0xa1), - danger: color_from_rgb(0xf3, 0x8b, 0xa8), - }; - iced::Theme::custom_with_fn("Catppuccin".to_string(), iced_palette, |palette| { - iced::theme::palette::Extended::generate(palette) - }) - } -} - -/// Convertit des composantes RGB (0-255) en `iced::Color`. -fn color_from_rgb(r: u8, g: u8, b: u8) -> Color { - Color::from_rgb8(r, g, b) -} - -/// Applique une opacité alpha à une couleur Iced. -pub fn with_alpha(color: Color, alpha: f32) -> Color { - Color { - a: alpha.clamp(0.0, 1.0), - ..color - } -} diff --git a/src/ui/widgets/button.rs b/src/ui/widgets/button.rs new file mode 100644 index 0000000..f8a56df --- /dev/null +++ b/src/ui/widgets/button.rs @@ -0,0 +1,138 @@ +//! Push buttons in four strengths, plus a glyph button with a tooltip. +//! +//! `on_press: None` draws the button disabled. + +use colony_ui::theme::{contrast_on, Palette}; +use colony_ui::{fonts, Typography}; +use iced::widget::{button, container, text, tooltip}; +use iced::{Border, Color, Element}; + +#[derive(Clone, Copy)] +enum Kind { + Primary, + Secondary, + Danger, + Ghost, +} + +/// The accent button: the one action a screen expects next. +pub fn primary<'a, M: Clone + 'a>(label: &str, on_press: Option) -> Element<'a, M> { + labelled(label, on_press, Kind::Primary) +} + +pub fn secondary<'a, M: Clone + 'a>(label: &str, on_press: Option) -> Element<'a, M> { + labelled(label, on_press, Kind::Secondary) +} + +/// For actions that lose work; they still go through a confirmation. +pub fn danger<'a, M: Clone + 'a>(label: &str, on_press: Option) -> Element<'a, M> { + labelled(label, on_press, Kind::Danger) +} + +/// No background until hovered. +pub fn ghost<'a, M: Clone + 'a>(label: &str, on_press: Option) -> Element<'a, M> { + labelled(label, on_press, Kind::Ghost) +} + +/// A Nerd Font glyph drawn as a ghost button, with `tip` shown on hover. +pub fn icon<'a, M: Clone + 'a>(glyph: &str, on_press: Option, tip: &str) -> Element<'a, M> { + let typo = Typography::current(); + let glyph = text(glyph.to_string()) + .size(typo.sz(14)) + .font(fonts::glyph_font()); + let body = button(glyph) + .on_press_maybe(on_press) + .padding([4, 6]) + .style(style(Kind::Ghost)); + with_tip(body, tip) +} + +/// Shows `tip` below `body` on hover. +pub fn with_tip<'a, M: 'a>(body: impl Into>, tip: &str) -> Element<'a, M> { + let typo = Typography::current(); + tooltip( + body, + container( + text(tip.to_string()) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY()), + ) + .padding([4, 8]) + .style(|_| container::Style { + background: Some(Palette::BG_SIDEBAR().into()), + border: Border::default() + .rounded(6) + .width(1) + .color(Palette::BG_SELECTED()), + ..Default::default() + }), + tooltip::Position::Bottom, + ) + .gap(4) + .into() +} + +fn labelled<'a, M: Clone + 'a>(label: &str, on_press: Option, kind: Kind) -> Element<'a, M> { + let typo = Typography::current(); + button(text(label.to_string()).size(typo.sz(12)).font(typo.regular)) + .on_press_maybe(on_press) + .padding([6, 12]) + .style(style(kind)) + .into() +} + +fn style(kind: Kind) -> impl Fn(&iced::Theme, button::Status) -> button::Style { + move |_theme, status| { + let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed); + let (background, text_color) = match kind { + Kind::Primary => { + let accent = Palette::ACCENT(); + let bg = if hovered { + accent.scale_alpha(0.85) + } else { + accent + }; + (bg, contrast_on(accent)) + } + Kind::Secondary => ( + if hovered { + Palette::BG_SELECTED() + } else { + Palette::BG_CARD_HOVER() + }, + Palette::TEXT_SECONDARY(), + ), + Kind::Danger => ( + if hovered { + Palette::BTN_DANGER_HOVER() + } else { + Palette::BTN_DANGER_BG() + }, + Palette::ERROR(), + ), + Kind::Ghost => ( + if hovered { + Palette::BG_CARD_HOVER() + } else { + Color::TRANSPARENT + }, + Palette::TEXT_DIMMER(), + ), + }; + let disabled = matches!(status, button::Status::Disabled); + let dim = |color: Color| { + if disabled { + color.scale_alpha(0.5) + } else { + color + } + }; + button::Style { + background: Some(dim(background).into()), + text_color: dim(text_color), + border: Border::default().rounded(6), + ..Default::default() + } + } +} diff --git a/src/ui/widgets/chip.rs b/src/ui/widgets/chip.rs new file mode 100644 index 0000000..a60f853 --- /dev/null +++ b/src/ui/widgets/chip.rs @@ -0,0 +1,64 @@ +//! Small rounded labels: branch names, ahead/behind counts, ref badges. + +use colony_ui::theme::Palette; +use colony_ui::Typography; +use iced::widget::{container, text}; +use iced::{Border, Color, Element}; + +/// What a chip's text colour says about it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tone { + Neutral, + Accent, + Success, + Warning, + /// Remote branches. + Remote, + /// Tags. + Tag, +} + +impl Tone { + /// The palette role of the chip's text, read from the active theme. + pub fn color(self) -> Color { + match self { + Tone::Neutral => Palette::TEXT_SECONDARY(), + Tone::Accent => Palette::ACCENT(), + Tone::Success => Palette::SUCCESS(), + Tone::Warning | Tone::Tag => Palette::WARNING(), + Tone::Remote => Palette::ACCENT_ICON(), + } + } +} + +pub fn chip<'a, M: 'a>(label: &str, tone: Tone) -> Element<'a, M> { + let typo = Typography::current(); + container( + text(label.to_string()) + .size(typo.sz(11)) + .font(typo.regular) + .color(tone.color()), + ) + .padding([3, 9]) + .style(|_| container::Style { + background: Some(Palette::BG_CARD_HOVER().into()), + border: Border::default().rounded(20), + ..Default::default() + }) + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tone_maps_to_palette_roles() { + // The tests never change the active theme, so this is the default one. + assert_eq!(Tone::Remote.color(), Palette::ACCENT_ICON()); + assert_eq!(Tone::Tag.color(), Palette::WARNING()); + assert_eq!(Tone::Success.color(), Palette::SUCCESS()); + assert_eq!(Tone::Accent.color(), Palette::ACCENT()); + assert_eq!(Tone::Neutral.color(), Palette::TEXT_SECONDARY()); + } +} diff --git a/src/ui/widgets/ellipsis.rs b/src/ui/widgets/ellipsis.rs new file mode 100644 index 0000000..4071d5e --- /dev/null +++ b/src/ui/widgets/ellipsis.rs @@ -0,0 +1,190 @@ +//! One line of text that ends in "…" when the space it gets is too narrow for all of it. +//! +//! A row lays it out last, with the width the other widgets (badges, a hash) leave, like a +//! `Length::Fill` child, so they keep their size and the text gives way. It is only as wide +//! as the text it shows, so the widgets after it in the row follow the text. + +use iced::advanced::layout::{self, Layout}; +use iced::advanced::text::paragraph::Plain; +use iced::advanced::text::{self, Paragraph as _}; +use iced::advanced::widget::{self, tree, Tree, Widget}; +use iced::advanced::{mouse, renderer}; +use iced::alignment::Vertical; +use iced::{Color, Element, Font, Length, Rectangle, Renderer, Size, Theme}; + +const ELLIPSIS: &str = "\u{2026}"; + +type Paragraph = ::Paragraph; + +/// `content` on one line in `font` at `size`, cut with "…" to the width it gets. +pub fn ellipsis<'a, M: 'a>( + content: impl Into, + size: f32, + font: Font, + color: Color, +) -> Element<'a, M> { + Element::new(Ellipsis { + content: content.into(), + size, + font, + color, + }) +} + +struct Ellipsis { + content: String, + size: f32, + font: Font, + color: Color, +} + +#[derive(Default)] +struct State { + /// All of the text, measured once per change of text, size or font. + full: Plain, + /// The text drawn: all of it, or its cut start and "…". + shown: Plain, + /// The width `shown` was cut for. + width: f32, +} + +impl Ellipsis { + fn text<'b>(&self, content: &'b str) -> text::Text<&'b str, Font> { + text::Text { + content, + bounds: Size::INFINITE, + size: self.size.into(), + line_height: text::LineHeight::default(), + font: self.font, + align_x: text::Alignment::Default, + align_y: Vertical::Top, + shaping: text::Shaping::default(), + wrapping: text::Wrapping::None, + } + } +} + +impl Widget for Ellipsis { + fn tag(&self) -> tree::Tag { + tree::Tag::of::() + } + + fn state(&self) -> tree::State { + tree::State::new(State::default()) + } + + fn size(&self) -> Size { + Size::new(Length::Fill, Length::Shrink) + } + + fn layout( + &mut self, + tree: &mut Tree, + _renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + let state = tree.state.downcast_mut::(); + let width = limits.max().width; + // Each try shapes text again, so the cut is only searched when the text, its format + // or the width changed. + if state.full.update(self.text(&self.content)) || state.width != width { + state.width = width; + let full = state.full.min_width(); + let shown = fit(&self.content, width, |candidate| { + if candidate == self.content { + full + } else { + Paragraph::with_text(self.text(candidate)).min_width() + } + }); + state.shown.update(self.text(&shown)); + } + let shown = state.shown.min_bounds(); + layout::Node::new(Size::new( + shown.width.min(width), + shown.height.min(limits.max().height), + )) + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + _theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + _cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + // Clipped to its own bounds: even "…" alone can be wider than a tiny space. + let Some(clip) = layout.bounds().intersection(viewport) else { + return; + }; + let state = tree.state.downcast_ref::(); + widget::text::draw( + renderer, + style, + layout.bounds(), + state.shown.raw(), + widget::text::Style { + color: Some(self.color), + }, + &clip, + ); + } + + fn operate( + &mut self, + _tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn widget::Operation, + ) { + operation.text(None, layout.bounds(), &self.content); + } +} + +/// `content` when `width_of` it fits in `max_width`, or else the longest start of it, without +/// trailing spaces, that fits with "…" after it. Only "…" is left when nothing fits. +fn fit(content: &str, max_width: f32, width_of: impl Fn(&str) -> f32) -> String { + if content.is_empty() || width_of(content) <= max_width { + return content.to_string(); + } + let starts: Vec = content.char_indices().map(|(at, _)| at).collect(); + let cut = |chars: usize| format!("{}{ELLIPSIS}", content[..starts[chars]].trim_end()); + // Binary search between a char count known to fit (or zero) and one known not to. + let (mut fits, mut too_wide) = (0, starts.len()); + while too_wide - fits > 1 { + let middle = (fits + too_wide) / 2; + if width_of(&cut(middle)) <= max_width { + fits = middle; + } else { + too_wide = middle; + } + } + cut(fits) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Ten pixels per character. + fn width(text: &str) -> f32 { + text.chars().count() as f32 * 10.0 + } + + #[test] + fn a_summary_too_wide_for_its_space_ends_in_an_ellipsis() { + // "feat: add file 3" is 160 px wide. + assert_eq!(fit("feat: add file 3", 160.0, width), "feat: add file 3"); + // The space before the cut is dropped, not drawn before "…". + assert_eq!(fit("feat: add file 3", 159.0, width), "feat: add file…"); + assert_eq!(fit("feat: add file 3", 100.0, width), "feat: add…"); + assert_eq!(fit("feat: add file 3", 99.0, width), "feat: ad…"); + assert_eq!(fit("feat: add file 3", 5.0, width), "…"); + assert_eq!(fit("", 0.0, width), ""); + // Cut on character boundaries, never inside one. + assert_eq!(fit("été très chaud", 60.0, width), "été t…"); + } +} diff --git a/src/ui/widgets/menu.rs b/src/ui/widgets/menu.rs new file mode 100644 index 0000000..c9dd154 --- /dev/null +++ b/src/ui/widgets/menu.rs @@ -0,0 +1,380 @@ +//! Popup menus: the "⋯" menus and right-click menus. +//! +//! The menu is an iced overlay drawn below its anchor, flipped above or moved left when +//! it would leave the window. A click outside it or Escape sends `on_close`; choosing an +//! item sends only that item's message, so the caller closes the menu when handling it. + +use colony_ui::theme::Palette; +use colony_ui::Typography; +use iced::advanced::widget::{tree, Tree, Widget}; +use iced::advanced::{layout, overlay, renderer, Clipboard, Layout, Shell}; +use iced::widget::{button, container, row, text, Column, Space}; +use iced::{ + keyboard, mouse, Border, Color, Element, Event, Length, Point, Rectangle, Renderer, Shadow, + Size, Theme, Vector, +}; + +/// Space between the anchor and the menu. +const GAP: f32 = 4.0; + +pub struct MenuItem { + pub label: String, + pub shortcut: Option, + pub on_select: M, + /// Drawn in the error colour; the action still asks for confirmation. + pub danger: bool, +} + +pub enum Entry { + Item(MenuItem), + Separator, +} + +/// Draws `anchor`, and the menu over everything else while `open` is true. +pub fn popup<'a, M: Clone + 'a>( + anchor: Element<'a, M>, + open: bool, + entries: Vec>, + on_close: M, +) -> Element<'a, M> { + Element::new(Popup { + anchor, + menu: open.then(|| list(entries)), + on_close, + }) +} + +fn list<'a, M: Clone + 'a>(entries: Vec>) -> Element<'a, M> { + let typo = Typography::current(); + let rows = entries.into_iter().map(|entry| -> Element<'a, M> { + match entry { + Entry::Separator => container( + container(Space::new().width(Length::Fill).height(1)).style(|_| container::Style { + background: Some(Palette::DIVIDER().into()), + ..Default::default() + }), + ) + .padding([5, 2]) + .into(), + Entry::Item(item) => { + let color = if item.danger { + Palette::ERROR() + } else { + Palette::TEXT_SECONDARY() + }; + let mut content = row![ + text(item.label) + .size(typo.sz(12)) + .font(typo.regular) + .color(color), + Space::new().width(Length::Fill), + ]; + if let Some(shortcut) = item.shortcut { + content = content.push( + text(shortcut) + .size(typo.sz(11)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()), + ); + } + button(content.spacing(12)) + .on_press(item.on_select) + .width(Length::Fill) + .padding([7, 10]) + .style(|_theme, status| button::Style { + background: matches!( + status, + button::Status::Hovered | button::Status::Pressed + ) + .then(|| Palette::BG_CARD_HOVER().into()), + border: Border::default().rounded(5), + ..Default::default() + }) + .into() + } + } + }); + container(Column::with_children(rows).width(230)) + .padding(6) + .style(|_| container::Style { + background: Some(Palette::BG_SIDEBAR().into()), + border: Border::default() + .rounded(8) + .width(1) + .color(Palette::BG_SELECTED()), + shadow: Shadow { + color: Color::BLACK.scale_alpha(0.45), + offset: Vector::new(0.0, 10.0), + blur_radius: 30.0, + }, + ..Default::default() + }) + .into() +} + +struct Popup<'a, M> { + anchor: Element<'a, M>, + menu: Option>, + on_close: M, +} + +impl Widget for Popup<'_, M> { + fn children(&self) -> Vec { + std::iter::once(&self.anchor) + .chain(&self.menu) + .map(Tree::new) + .collect() + } + + fn diff(&self, tree: &mut Tree) { + match &self.menu { + Some(menu) => tree.diff_children(&[self.anchor.as_widget(), menu.as_widget()]), + None => tree.diff_children(&[self.anchor.as_widget()]), + } + } + + fn tag(&self) -> tree::Tag { + tree::Tag::stateless() + } + + fn size(&self) -> Size { + self.anchor.as_widget().size() + } + + fn size_hint(&self) -> Size { + self.anchor.as_widget().size_hint() + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + self.anchor + .as_widget_mut() + .layout(&mut tree.children[0], renderer, limits) + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, M>, + viewport: &Rectangle, + ) { + self.anchor.as_widget_mut().update( + &mut tree.children[0], + event, + layout, + cursor, + renderer, + clipboard, + shell, + viewport, + ); + } + + fn mouse_interaction( + &self, + tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + renderer: &Renderer, + ) -> mouse::Interaction { + self.anchor.as_widget().mouse_interaction( + &tree.children[0], + layout, + cursor, + viewport, + renderer, + ) + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + self.anchor.as_widget().draw( + &tree.children[0], + renderer, + theme, + style, + layout, + cursor, + viewport, + ); + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + renderer: &Renderer, + operation: &mut dyn iced::advanced::widget::Operation, + ) { + self.anchor + .as_widget_mut() + .operate(&mut tree.children[0], layout, renderer, operation); + } + + fn overlay<'b>( + &'b mut self, + tree: &'b mut Tree, + layout: Layout<'b>, + renderer: &Renderer, + viewport: &Rectangle, + translation: Vector, + ) -> Option> { + let (anchor_tree, rest) = tree.children.split_at_mut(1); + match (&mut self.menu, rest.first_mut()) { + (Some(menu), Some(menu_tree)) => Some(overlay::Element::new(Box::new(Overlay { + menu, + tree: menu_tree, + anchor: layout.bounds() + translation, + on_close: self.on_close.clone(), + }))), + // The anchor's own overlays (a tooltip) only show while the menu is closed. + _ => self.anchor.as_widget_mut().overlay( + &mut anchor_tree[0], + layout, + renderer, + viewport, + translation, + ), + } + } +} + +struct Overlay<'a, 'b, M> { + menu: &'b mut Element<'a, M>, + tree: &'b mut Tree, + anchor: Rectangle, + on_close: M, +} + +impl overlay::Overlay for Overlay<'_, '_, M> { + fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node { + let node = self.menu.as_widget_mut().layout( + self.tree, + renderer, + &layout::Limits::new(Size::ZERO, bounds), + ); + let size = node.size(); + node.move_to(place(self.anchor, size, bounds)) + } + + fn draw( + &self, + renderer: &mut Renderer, + theme: &Theme, + style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + ) { + self.menu.as_widget().draw( + self.tree, + renderer, + theme, + style, + layout, + cursor, + &layout.bounds(), + ); + } + + fn update( + &mut self, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, M>, + ) { + let outside_click = matches!(event, Event::Mouse(mouse::Event::ButtonPressed(_))) + && !cursor.is_over(layout.bounds()); + let escape = matches!( + event, + Event::Keyboard(keyboard::Event::KeyPressed { + key: keyboard::Key::Named(keyboard::key::Named::Escape), + .. + }) + ); + if outside_click || escape { + shell.publish(self.on_close.clone()); + shell.capture_event(); + return; + } + self.menu.as_widget_mut().update( + self.tree, + event, + layout, + cursor, + renderer, + clipboard, + shell, + &layout.bounds(), + ); + } + + fn mouse_interaction( + &self, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + ) -> mouse::Interaction { + self.menu.as_widget().mouse_interaction( + self.tree, + layout, + cursor, + &layout.bounds(), + renderer, + ) + } +} + +/// Below the anchor and left-aligned with it when that fits the window; otherwise +/// right-aligned and/or above it, never past the top-left corner. +fn place(anchor: Rectangle, menu: Size, window: Size) -> Point { + let x = if anchor.x + menu.width <= window.width { + anchor.x + } else { + anchor.x + anchor.width - menu.width + }; + let below = anchor.y + anchor.height + GAP; + let y = if below + menu.height <= window.height { + below + } else { + anchor.y - GAP - menu.height + }; + Point::new(x.max(0.0), y.max(0.0)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn menu_stays_inside_the_window() { + let window = Size::new(800.0, 600.0); + let menu = Size::new(230.0, 200.0); + + let top_left = Rectangle::new(Point::new(10.0, 10.0), Size::new(20.0, 20.0)); + assert_eq!(place(top_left, menu, window), Point::new(10.0, 34.0)); + + let bottom_right = Rectangle::new(Point::new(760.0, 560.0), Size::new(30.0, 20.0)); + assert_eq!(place(bottom_right, menu, window), Point::new(560.0, 356.0)); + } +} diff --git a/src/ui/widgets/mod.rs b/src/ui/widgets/mod.rs new file mode 100644 index 0000000..081a9a1 --- /dev/null +++ b/src/ui/widgets/mod.rs @@ -0,0 +1,69 @@ +//! GitSpace widgets the kit does not have yet, written the way colony-ui's are. +//! +//! Every widget reads `Palette` and `Typography::current()` when it is drawn, so a change +//! of theme, accent, text size or font shows on the next frame. They can move to +//! colony-ui later without changes. + +pub mod button; +pub mod chip; +pub mod ellipsis; +pub mod menu; +pub mod segmented; +pub mod tabs; +pub mod toast; + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + + fn rust_files(dir: &Path, out: &mut Vec) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + rust_files(&path, out); + } else if path.extension().is_some_and(|ext| ext == "rs") { + out.push(path); + } + } + } + + /// True when `line` holds `marker` followed by six hex digits. + fn has_hex_after(line: &str, marker: &str) -> bool { + line.match_indices(marker).any(|(at, _)| { + let rest = &line[at + marker.len()..]; + rest.len() >= 6 && rest.chars().take(6).all(|c| c.is_ascii_hexdigit()) + }) + } + + #[test] + fn ui_has_no_hex_colours() { + let mut files = Vec::new(); + rust_files( + &Path::new(env!("CARGO_MANIFEST_DIR")).join("src/ui"), + &mut files, + ); + + let mut offenders = Vec::new(); + for file in files { + let source = std::fs::read_to_string(&file).unwrap(); + for (number, line) in crate::ui::non_test_lines(&source) { + if line.contains("Color::from_rgb") + || has_hex_after(line, "0x") + || has_hex_after(line, "#") + { + offenders.push(format!( + "{}:{}: {}", + file.display(), + number + 1, + line.trim() + )); + } + } + } + assert!( + offenders.is_empty(), + "hex colours in the UI:\n{}", + offenders.join("\n") + ); + } +} diff --git a/src/ui/widgets/segmented.rs b/src/ui/widgets/segmented.rs new file mode 100644 index 0000000..7a5f1cc --- /dev/null +++ b/src/ui/widgets/segmented.rs @@ -0,0 +1,54 @@ +//! A row of joined buttons where exactly one is selected. + +use colony_ui::theme::Palette; +use colony_ui::Typography; +use iced::widget::{button, container, text, Row}; +use iced::{border, Border, Element}; + +pub fn segmented<'a, M: Clone + 'a>( + items: &[String], + selected: usize, + on_select: impl Fn(usize) -> M, +) -> Element<'a, M> { + let typo = Typography::current(); + let last = items.len().saturating_sub(1); + let segments = items.iter().enumerate().map(|(index, label)| { + let is_selected = index == selected; + // Only the outer corners are rounded; the 1 px gaps show the frame as dividers. + let mut radius = border::radius(0); + if index == 0 { + radius = radius.left(7); + } + if index == last { + radius = radius.right(7); + } + button(text(label.clone()).size(typo.sz(12)).font(typo.regular)) + .on_press(on_select(index)) + .padding([7, 14]) + .style(move |_theme, status| { + let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed); + let (background, text_color) = if is_selected { + (Palette::BG_SELECTED(), Palette::TEXT_PRIMARY()) + } else if hovered { + (Palette::BG_CARD_HOVER(), Palette::TEXT_MUTED()) + } else { + (Palette::BG_SIDEBAR(), Palette::TEXT_MUTED()) + }; + button::Style { + background: Some(background.into()), + text_color, + border: Border::default().rounded(radius), + ..Default::default() + } + }) + .into() + }); + container(Row::with_children(segments).spacing(1)) + .padding(1) + .style(|_| container::Style { + background: Some(Palette::BG_SELECTED().into()), + border: Border::default().rounded(8), + ..Default::default() + }) + .into() +} diff --git a/src/ui/widgets/tabs.rs b/src/ui/widgets/tabs.rs new file mode 100644 index 0000000..741a5b7 --- /dev/null +++ b/src/ui/widgets/tabs.rs @@ -0,0 +1,49 @@ +//! A strip of tabs with an optional count after each label. + +use colony_ui::theme::Palette; +use colony_ui::Typography; +use iced::widget::{button, row, text, Row}; +use iced::{Alignment, Border, Color, Element}; + +/// `items` are labels with an optional count, shown dimmed after the label. +pub fn tabs<'a, M: Clone + 'a>( + items: &[(String, Option)], + selected: usize, + on_select: impl Fn(usize) -> M, +) -> Element<'a, M> { + let typo = Typography::current(); + let tabs = items.iter().enumerate().map(|(index, (label, count))| { + let is_selected = index == selected; + let mut content = row![text(label.clone()).size(typo.sz(12)).font(typo.regular)] + .spacing(6) + .align_y(Alignment::Center); + if let Some(count) = count { + content = content.push( + text(count.to_string()) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_DIMMEST()), + ); + } + button(content) + .on_press(on_select(index)) + .padding([6, 12]) + .style(move |_theme, status| { + let (background, text_color) = match status { + _ if is_selected => (Palette::BG_SELECTED(), Palette::TEXT_PRIMARY()), + button::Status::Hovered | button::Status::Pressed => { + (Palette::BG_CARD_HOVER(), Palette::TEXT_MUTED()) + } + _ => (Color::TRANSPARENT, Palette::TEXT_MUTED()), + }; + button::Style { + background: Some(background.into()), + text_color, + border: Border::default().rounded(6), + ..Default::default() + } + }) + .into() + }); + Row::with_children(tabs).spacing(4).into() +} diff --git a/src/ui/widgets/toast.rs b/src/ui/widgets/toast.rs new file mode 100644 index 0000000..a5273b1 --- /dev/null +++ b/src/ui/widgets/toast.rs @@ -0,0 +1,324 @@ +//! Toasts: short success messages and error reports with actions. +//! +//! Success toasts use the kit's `toast`; error toasts add a body and action buttons, +//! which the kit's widget does not have. + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use colony_ui::theme::Palette; +use colony_ui::widgets::icons; +use colony_ui::{fonts, Typography}; +use iced::widget::{button as iced_button, column, container, mouse_area, row, text, Space}; +use iced::{mouse, Alignment, Border, Element, Length}; + +use super::button; +use crate::i18n::t; + +/// At most this many toasts are shown; the oldest goes first. +const MAX_TOASTS: usize = 5; + +/// The end of a toast's life, during which it fades out. Longer than the app's 1 s expiry +/// tick, so a tick always lands in it and the app switches to per-frame ticks. +const FADE: Duration = Duration::from_millis(1500); + +const WIDTH: f32 = 340.0; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ToastKind { + Success, + Error, +} + +impl ToastKind { + fn lifetime(self) -> Duration { + match self { + ToastKind::Success => Duration::from_secs(8), + ToastKind::Error => Duration::from_secs(20), + } + } +} + +/// A button on an error toast. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ToastAction { + Retry, + CopyLogPath(PathBuf), +} + +#[derive(Debug, Clone)] +pub struct Toast { + /// Set by [`Toasts::push`]; stable while other toasts come and go. + pub id: u64, + pub kind: ToastKind, + pub title: String, + pub body: String, + pub actions: Vec, + pub created: Instant, +} + +impl Toast { + pub fn success(message: impl Into) -> Self { + Self::new(ToastKind::Success, message.into(), String::new()) + } + + pub fn error(title: impl Into, body: impl Into) -> Self { + Self::new(ToastKind::Error, title.into(), body.into()) + } + + fn new(kind: ToastKind, title: String, body: String) -> Self { + Self { + id: 0, + kind, + title, + body, + actions: Vec::new(), + created: Instant::now(), + } + } + + pub fn with_action(mut self, action: ToastAction) -> Self { + self.actions.push(action); + self + } + + fn expires(&self) -> Instant { + self.created + self.kind.lifetime() + } + + /// 1.0 until the last moments of the toast's life, then down to 0; always 1.0 without effects. + fn opacity(&self, now: Instant) -> f32 { + if !colony_ui::effects_enabled() { + return 1.0; + } + let left = self.expires().saturating_duration_since(now); + (left.as_secs_f32() / FADE.as_secs_f32()).min(1.0) + } +} + +#[derive(Debug, Default)] +pub struct Toasts { + queue: Vec, + next_id: u64, +} + +impl Toasts { + /// Shows a toast and returns its id. + pub fn push(&mut self, mut toast: Toast) -> u64 { + toast.id = self.next_id; + self.next_id += 1; + self.queue.push(toast); + if self.queue.len() > MAX_TOASTS { + self.queue.remove(0); + } + self.next_id - 1 + } + + pub fn dismiss(&mut self, id: u64) { + self.queue.retain(|toast| toast.id != id); + } + + /// Removes the toasts whose time is up at `now`. + pub fn expire(&mut self, now: Instant) { + self.queue.retain(|toast| toast.expires() > now); + } + + pub fn is_empty(&self) -> bool { + self.queue.is_empty() + } + + /// True while a toast is fading, so the caller can redraw every frame. + pub fn is_fading(&self, now: Instant) -> bool { + self.queue.iter().any(|toast| toast.opacity(now) < 1.0) + } + + /// The toasts stacked in a fixed-width column, newest last. + pub fn view<'a, M: Clone + 'a>( + &'a self, + on_dismiss: impl Fn(u64) -> M, + on_action: impl Fn(u64, ToastAction) -> M, + ) -> Element<'a, M> { + if self.queue.is_empty() { + return Space::new().into(); + } + let typo = Typography::current(); + let now = Instant::now(); + let toasts = self.queue.iter().map(|toast| match toast.kind { + ToastKind::Success => { + colony_ui::widgets::toast(&typo, &toast.title, on_dismiss(toast.id)) + } + ToastKind::Error => error_toast(&typo, toast, now, &on_dismiss, &on_action), + }); + column(toasts).spacing(8).width(WIDTH).into() + } +} + +fn error_toast<'a, M: Clone + 'a>( + typo: &Typography, + toast: &'a Toast, + now: Instant, + on_dismiss: &impl Fn(u64) -> M, + on_action: &impl Fn(u64, ToastAction) -> M, +) -> Element<'a, M> { + let alpha = toast.opacity(now); + let close = iced_button( + text(icons::CLOSE) + .size(typo.sz(12)) + .font(fonts::glyph_font()) + .color(Palette::TEXT_DIMMER().scale_alpha(alpha)), + ) + .on_press(on_dismiss(toast.id)) + .padding(2) + .style(|_theme, _status| iced_button::Style::default()); + + let mut content = column![row![ + text(toast.title.as_str()) + .size(typo.sz(13)) + .font(typo.bold) + .color(Palette::ERROR().scale_alpha(alpha)), + Space::new().width(Length::Fill), + close, + ] + .align_y(Alignment::Center),] + .spacing(4); + if !toast.body.is_empty() { + content = content.push( + text(toast.body.as_str()) + .size(typo.sz(12)) + .font(typo.regular) + .color(Palette::TEXT_SECONDARY().scale_alpha(alpha)), + ); + } + if !toast.actions.is_empty() { + let actions = toast.actions.iter().map(|action| { + let label = match action { + ToastAction::Retry => t("retry"), + ToastAction::CopyLogPath(_) => t("copy_log_path"), + }; + button::secondary(label, Some(on_action(toast.id, action.clone()))) + }); + content = content.push(row(actions).spacing(6)); + } + + let card = container(content) + .padding([10, 14]) + .width(Length::Fill) + .style(move |_| container::Style { + background: Some(Palette::ERROR_BG().scale_alpha(alpha).into()), + border: Border::default() + .rounded(8) + .width(1) + .color(Palette::ERROR().scale_alpha(alpha * 0.5)), + ..Default::default() + }); + // The window's stack hands the cursor to the controls below unless the toast reports an + // interaction; text and padding report none, so a click would go through to them. + mouse_area(card) + .interaction(mouse::Interaction::Idle) + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn push_at(toasts: &mut Toasts, toast: Toast, created: Instant) -> u64 { + toasts.push(Toast { created, ..toast }) + } + + #[test] + fn toasts_expire_by_kind() { + let start = Instant::now(); + let mut toasts = Toasts::default(); + push_at(&mut toasts, Toast::success("Pushed"), start); + push_at(&mut toasts, Toast::error("Push failed", "rejected"), start); + + toasts.expire(start + Duration::from_secs(7)); + assert_eq!(toasts.queue.len(), 2); + + toasts.expire(start + Duration::from_secs(8)); + assert_eq!(toasts.queue.len(), 1); + assert_eq!(toasts.queue[0].kind, ToastKind::Error); + + toasts.expire(start + Duration::from_secs(19)); + assert_eq!(toasts.queue.len(), 1); + + toasts.expire(start + Duration::from_secs(20)); + assert!(toasts.is_empty()); + } + + #[test] + fn dismiss_removes_only_that_toast() { + let mut toasts = Toasts::default(); + let first = toasts.push(Toast::error("First", "")); + let second = toasts.push(Toast::error("Second", "")); + let third = toasts.push(Toast::success("Third")); + assert_ne!(first, second); + + toasts.dismiss(second); + let left: Vec = toasts.queue.iter().map(|toast| toast.id).collect(); + assert_eq!(left, [first, third]); + } + + #[test] + fn the_oldest_toast_goes_past_the_limit() { + let mut toasts = Toasts::default(); + for i in 0..MAX_TOASTS + 2 { + toasts.push(Toast::error(format!("Toast {i}"), "")); + } + assert_eq!(toasts.queue.len(), MAX_TOASTS); + assert_eq!(toasts.queue[0].title, "Toast 2"); + } + + #[tokio::test] + async fn an_error_toast_keeps_the_pointer_from_the_controls_under_it() { + use iced::advanced::renderer::Headless; + use iced::advanced::widget::Tree; + use iced::advanced::{layout, Layout}; + + let renderer = ::new( + iced::Font::default(), + iced::Pixels(16.0), + Some("tiny-skia"), + ) + .await + .expect("tiny-skia renderer"); + let mut toasts = Toasts::default(); + toasts.push(Toast::error("Background fetch failed", "offline")); + let mut element: Element<'_, ()> = toasts.view(|_| (), |_, _| ()); + let mut tree = Tree::new(&element); + let limits = layout::Limits::new(iced::Size::ZERO, iced::Size::new(400.0, 400.0)); + let node = element + .as_widget_mut() + .layout(&mut tree, &renderer, &limits); + let bounds = node.bounds(); + + // The bottom-left padding of the toast: no button there. + let cursor = mouse::Cursor::Available(iced::Point::new(4.0, bounds.height - 4.0)); + let interaction = element.as_widget().mouse_interaction( + &tree, + Layout::new(&node), + cursor, + &bounds, + &renderer, + ); + assert_ne!(interaction, mouse::Interaction::None); + } + + #[test] + fn toasts_fade_only_with_effects() { + let start = Instant::now(); + let toast = Toast { + created: start, + ..Toast::success("Fetched") + }; + let near_end = start + ToastKind::Success.lifetime() - FADE / 2; + assert_eq!(toast.opacity(start), 1.0); + + colony_ui::set_effects(true); + assert!(toast.opacity(near_end) < 1.0); + colony_ui::set_effects(false); + assert_eq!(toast.opacity(near_end), 1.0); + colony_ui::set_effects(true); + } +}