A visual git client, simple to use yet powerful. Light, fast and debloated.
Rust
feat: undo/redo, stash, search, conflict editor, richer diffs and more
Ivánc262e5440039
diff --git a/Cargo.lock b/Cargo.lockindex de005d2..5d4472d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -137,6 +137,15 @@ dependencies = ["zerocopy",]+[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]+[[package]]name = "allocator-api2"version = "0.2.21"@@ -416,15 +425,45 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"++[[package]]+name = "bincode"+version = "1.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"+dependencies = [+ "serde",+]++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec 0.8.0",+]+[[package]]name = "bit-set"version = "0.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d"dependencies = [- "bit-vec",+ "bit-vec 0.9.1",]+[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"+[[package]]name = "bit-vec"version = "0.9.1"@@ -633,6 +672,12 @@ dependencies = ["bytemuck",]+[[package]]+name = "color_quant"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"+[[package]]name = "colored"version = "2.2.0"@@ -754,6 +799,12 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"+[[package]]+name = "deranged"+version = "0.5.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"+[[package]]name = "dify"version = "0.8.0"@@ -785,6 +836,17 @@ dependencies = ["objc2 0.6.5",]+[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]+[[package]]name = "dlib"version = "0.5.3"@@ -1135,6 +1197,17 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "fancy-regex"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f"+dependencies = [+ "bit-set 0.8.0",+ "regex-automata",+ "regex-syntax",+]+[[package]]name = "fastrand"version = "2.5.0"@@ -1196,6 +1269,12 @@ version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"+[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"+[[package]]name = "foldhash"version = "0.2.0"@@ -1239,6 +1318,15 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"+[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]+[[package]]name = "futures-core"version = "0.3.34"@@ -1313,6 +1401,17 @@ dependencies = ["unicode-width",]+[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi",+]+[[package]]name = "getrandom"version = "0.3.4"@@ -1336,6 +1435,16 @@ dependencies = ["r-efi 6.0.0",]+[[package]]+name = "gif"+version = "0.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"+dependencies = [+ "color_quant",+ "weezl",+]+[[package]]name = "gitcraft"version = "0.1.0"@@ -1344,9 +1453,17 @@ dependencies = ["egui","egui_extras","egui_kittest",+ "image",+ "md5",+ "notify",+ "notify-rust",+ "open","portable-pty","rfd","serde",+ "serde_json",+ "syntect",+ "ureq","vt100",]@@ -1534,6 +1651,110 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "icu_collections"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"++[[package]]+name = "icu_properties"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"++[[package]]+name = "icu_provider"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]+[[package]]name = "image"version = "0.25.10"@@ -1542,10 +1763,25 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"dependencies = ["bytemuck","byteorder-lite",+ "color_quant",+ "gif",+ "image-webp","moxcms","num-traits","png 0.18.1","tiff",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "image-webp"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"+dependencies = [+ "byteorder-lite",+ "quick-error",][[package]]@@ -1564,6 +1800,26 @@ dependencies = ["hashbrown 0.17.1",]+[[package]]+name = "inotify"+version = "0.11.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cc00ea907cab49550b7da656f80ebb97be1b997d931fbcd28d39734e17ce592"+dependencies = [+ "bitflags 2.13.2",+ "inotify-sys",+ "libc",+]++[[package]]+name = "inotify-sys"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"+dependencies = [+ "libc",+]+[[package]]name = "is-docker"version = "0.2.0"@@ -1704,6 +1960,26 @@ dependencies = ["accesskit_consumer 0.35.0",]+[[package]]+name = "kqueue"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d763e5b24120b4ddf50de6c92308156765aabfbbccebf401da7cff2d70a41ea"+dependencies = [+ "kqueue-sys",+ "libc",+]++[[package]]+name = "kqueue-sys"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"+dependencies = [+ "bitflags 2.13.2",+ "libc",+]+[[package]]name = "kurbo"version = "0.11.3"@@ -1773,6 +2049,12 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"+[[package]]+name = "linked-hash-map"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"+[[package]]name = "linux-raw-sys"version = "0.4.15"@@ -1785,6 +2067,12 @@ version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"+[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"+[[package]]name = "litrs"version = "1.0.1"@@ -1806,6 +2094,26 @@ version = "0.4.34"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"+[[package]]+name = "mac-notification-sys"+version = "0.6.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd604973958ddcc11b561193c0fb96ba146506ef2f231ef2e7c35fd2cbc9beca"+dependencies = [+ "cc",+ "log",+ "objc2 0.6.5",+ "objc2-foundation 0.3.2",+ "time",+ "uuid",+]++[[package]]+name = "md5"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"+[[package]]name = "memchr"version = "2.8.3"@@ -1850,6 +2158,18 @@ dependencies = ["simd-adler32",]+[[package]]+name = "mio"+version = "1.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"+dependencies = [+ "libc",+ "log",+ "wasi",+ "windows-sys 0.61.2",+]+[[package]]name = "moxcms"version = "0.8.1"@@ -1867,7 +2187,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130"dependencies = ["arrayvec",- "bit-set",+ "bit-set 0.10.0","bitflags 2.13.2","cfg-if","cfg_aliases 0.2.2",@@ -1946,6 +2266,54 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"+[[package]]+name = "notify"+version = "8.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f812702fbc75d35416d3f884e04925be7e9498f4eceea2e24ba34559284674"+dependencies = [+ "bitflags 2.13.2",+ "inotify",+ "kqueue",+ "libc",+ "log",+ "mio",+ "notify-types",+ "objc2-core-foundation",+ "objc2-core-services",+ "walkdir",+ "windows-sys 0.61.2",+]++[[package]]+name = "notify-rust"+version = "4.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4587364a9a0074333429b3df75a30a205340c56a536ca3eb6ca0e59b87bbf8af"+dependencies = [+ "futures-lite",+ "log",+ "mac-notification-sys",+ "serde",+ "tauri-winrt-notification",+ "zbus",+]++[[package]]+name = "notify-types"+version = "2.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"+dependencies = [+ "bitflags 2.13.2",+]++[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"+[[package]]name = "num-traits"version = "0.2.19"@@ -2117,6 +2485,16 @@ dependencies = ["objc2-foundation 0.2.2",]+[[package]]+name = "objc2-core-services"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "583300ad934cba24ff5292aee751ecc070f7ca6b39a574cc21b7b5e588e06a0b"+dependencies = [+ "libc",+ "objc2-core-foundation",+]+[[package]]name = "objc2-encode"version = "4.1.0"@@ -2144,6 +2522,7 @@ checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"dependencies = ["bitflags 2.13.2","block2 0.6.2",+ "libc","objc2 0.6.5","objc2-core-foundation",]@@ -2480,6 +2859,19 @@ version = "0.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"+[[package]]+name = "plist"+version = "1.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285"+dependencies = [+ "base64 0.23.1",+ "indexmap",+ "quick-xml 0.42.0",+ "serde",+ "time",+]+[[package]]name = "png"version = "0.17.16"@@ -2577,6 +2969,21 @@ dependencies = ["winreg",]+[[package]]+name = "potential_utf"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"+dependencies = [+ "zerovec",+]++[[package]]+name = "powerfmt"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"+[[package]]name = "presser"version = "0.3.1"@@ -2628,6 +3035,15 @@ dependencies = ["memchr",]+[[package]]+name = "quick-xml"+version = "0.42.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"+dependencies = [+ "memchr",+]+[[package]]name = "quote"version = "1.0.47"@@ -2731,6 +3147,23 @@ dependencies = ["bitflags 2.13.2",]+[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"+[[package]]name = "renderdoc-sys"version = "1.1.0"@@ -2787,6 +3220,20 @@ dependencies = ["bytemuck",]+[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]+[[package]]name = "ron"version = "0.12.2"@@ -2854,6 +3301,41 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "rustls"+version = "0.23.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"+dependencies = [+ "log",+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"+dependencies = [+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]+[[package]]name = "rustversion"version = "1.0.23"@@ -2923,6 +3405,19 @@ dependencies = ["syn 3.0.9",]+[[package]]+name = "serde_json"+version = "1.0.154"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]+[[package]]name = "serde_repr"version = "0.1.21"@@ -3138,6 +3633,12 @@ dependencies = ["bitflags 2.13.2",]+[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"+[[package]]name = "static_assertions"version = "1.1.0"@@ -3153,6 +3654,12 @@ dependencies = ["float-cmp",]+[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]name = "svgtypes"version = "0.15.3"@@ -3185,6 +3692,49 @@ dependencies = ["unicode-ident",]+[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "syntect"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"+dependencies = [+ "bincode",+ "fancy-regex",+ "flate2",+ "fnv",+ "once_cell",+ "plist",+ "regex-syntax",+ "serde",+ "serde_derive",+ "serde_json",+ "thiserror 2.0.21",+ "walkdir",+ "yaml-rust",+]++[[package]]+name = "tauri-winrt-notification"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f37a6c354fd28fc9e322ed9bd47e3959576dad28c9d58ea1cf888cce1c7ccb36"+dependencies = [+ "thiserror 2.0.21",+ "windows",+ "windows-version",+]+[[package]]name = "tempfile"version = "3.27.0"@@ -3261,6 +3811,36 @@ dependencies = ["zune-jpeg",]+[[package]]+name = "time"+version = "0.3.55"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"+dependencies = [+ "deranged",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"++[[package]]+name = "time-macros"+version = "0.2.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"+dependencies = [+ "num-conv",+ "time-core",+]+[[package]]name = "tiny-skia"version = "0.11.4"@@ -3287,6 +3867,16 @@ dependencies = ["strict-num",]+[[package]]+name = "tinystr"+version = "0.8.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a"+dependencies = [+ "displaydoc",+ "zerovec",+]+[[package]]name = "tokio"version = "1.54.1"@@ -3421,13 +4011,47 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"+[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "ureq"+version = "2.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"+dependencies = [+ "base64 0.22.1",+ "flate2",+ "log",+ "once_cell",+ "rustls",+ "rustls-pki-types",+ "url",+ "webpki-roots 0.26.11",+]++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]+[[package]]name = "usvg"version = "0.45.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef"dependencies = [- "base64",+ "base64 0.22.1","data-url","flate2","imagesize",@@ -3443,12 +4067,19 @@ dependencies = ["xmlwriter",]+[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"+[[package]]name = "uuid"version = "1.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"dependencies = [+ "getrandom 0.4.3","js-sys","serde_core","wasm-bindgen",@@ -3518,6 +4149,12 @@ dependencies = ["winapi-util",]+[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"+[[package]]name = "wasip2"version = "1.0.4+wasi-0.2.12"@@ -3702,7 +4339,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"dependencies = ["proc-macro2",- "quick-xml",+ "quick-xml 0.41.0","quote",]@@ -3738,6 +4375,24 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "webpki-roots"+version = "0.26.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"+dependencies = [+ "webpki-roots 1.0.11",+]++[[package]]+name = "webpki-roots"+version = "1.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171"+dependencies = [+ "rustls-pki-types",+]+[[package]]name = "weezl"version = "0.1.12"@@ -3781,8 +4436,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14"dependencies = ["arrayvec",- "bit-set",- "bit-vec",+ "bit-set 0.10.0",+ "bit-vec 0.9.1","bitflags 2.13.2","bytemuck","cfg_aliases 0.2.2",@@ -3854,7 +4509,7 @@ dependencies = ["android_system_properties","arrayvec","ash",- "bit-set",+ "bit-set 0.10.0","bitflags 2.13.2","block2 0.6.2","bytemuck",@@ -4111,6 +4766,15 @@ dependencies = ["windows-link",]+[[package]]+name = "windows-version"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"+dependencies = [+ "windows-link",+]+[[package]]name = "windows_aarch64_gnullvm"version = "0.52.6"@@ -4234,6 +4898,12 @@ version = "0.57.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"+[[package]]+name = "writeable"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"+[[package]]name = "x11-dl"version = "2.21.0"@@ -4303,6 +4973,38 @@ version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"+[[package]]+name = "yaml-rust"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"+dependencies = [+ "linked-hash-map",+]++[[package]]+name = "yoke"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "synstructure",+]+[[package]]name = "zbus"version = "5.19.0"@@ -4429,12 +5131,78 @@ dependencies = ["syn 2.0.119",]+[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]+[[package]]name = "zlib-rs"version = "0.6.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"+[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"+[[package]]name = "zune-core"version = "0.5.3"diff --git a/Cargo.toml b/Cargo.tomlindex 03bcdca..8baf494 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -11,9 +11,17 @@ publish = falseeframe = { version = "0.36", default-features = false, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] }egui = "0.36"egui_extras = { version = "0.36", default-features = false, features = ["svg", "image"] }+image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "bmp", "webp"] }+md5 = "0.7"+notify = "8"+notify-rust = "4"+open = "5"portable-pty = "0.9"rfd = "0.17"serde = { version = "1", features = ["derive"] }+serde_json = "1"+syntect = { version = "5", default-features = false, features = ["default-fancy"] }+ureq = "2"vt100 = "0.18"[lints.rust]diff --git a/README.md b/README.mdindex db7cf17..5e73b74 100644--- a/README.md+++ b/README.md@@ -5,44 +5,74 @@ Rust + [egui/eframe](https://github.com/emilk/egui), the same stack and look asPhotoCraft, so it builds on Windows, Linux and macOS. It drives the installed `git` command line,so your config, credentials and hooks apply as usual.-+## Features-- **Start page**: checks that `git` is installed; open an existing repository, create one- (`git init`) or clone one; recent repositories.-- **Tabs** like a browser, one per repository. `+` / Ctrl+T opens a start page, Ctrl+W closes,- middle-click closes. Open tabs, recents and the theme are remembered.-- **Branches** (left): local branches with ahead/behind counts, remote branches per remote, tags,- a filter. Click jumps to the commit; double-click checks out. Right-click: check out, merge into- the current branch, create a branch, copy the name, delete (with force option), delete from the- remote, delete a tag.-- **Worktrees** (left): every worktree with its branch, marked main / locked / missing. Add one- (on an existing or a new branch) with `+`, double-click or *Open in a tab* to work in it,- lock/unlock, remove (with force), prune missing ones. A branch checked out in another worktree- shows a worktree icon, and double-clicking it opens that worktree. *Check out in a new- worktree…* on a branch's menu.-- **Graph** (centre): every branch, coloured lanes, up to 5000 commits, ↑/↓ to move. Branch and- tag pills sit in their own column left of the graph, joined to their commit: white text, a- laptop icon when the branch is local, a cloud when a remote has it at that commit (`x` and- `origin/x` together make one pill), the tip author's avatar, `+N` when more refs share the- commit (hover lists them). An *Uncommitted changes*- row sits on top when the working tree is dirty. Right-click a commit: create a branch, check it- out (detached), cherry-pick, revert, copy hash or message.-- **Detail** (right): commit message, author, parents (clickable), changed files with +/−.- On the changes row: conflicted / unstaged / staged lists with stage, unstage, discard and- mark-resolved buttons on hover, *Stage all* / *Unstage all*, and the commit box- (Ctrl+Enter; with nothing staged it stages everything).-- **Diff**: clicking a file shows its diff in the centre with old/new line numbers (Esc closes).-- **Merges and conflicts**: a merge, cherry-pick or revert that stops on conflicts shows a banner- with *Abort*; the prepared merge message fills the commit box.-- **Toolbar**: Fetch (`--all --prune`), Pull (`--ff-only`), Push (publishes a new branch with- `-u`), new branch, terminal, refresh (F5; also when the window regains focus).-- **Terminal**: the *Terminal* button opens your shell (PowerShell on Windows, `$SHELL` elsewhere)- in the repository folder, in a resizable panel under the graph. It runs in a real- pseudo-terminal (ConPTY on Windows), with colours, scrollback (mouse wheel) and keys such as- Ctrl+C, arrows and Tab going to the shell. Closing the panel keeps the shell running.-- **Themes**: Dark, Medium Gray and Light, from PhotoCraft's Pro palettes.+**Repositories and tabs**+- Start page: checks that `git` is installed; open, create (`git init`) or clone a repository;+ recent repositories.+- Browser-like tabs, one per repository (Ctrl+T, Ctrl+W, middle-click). Open tabs, recents,+ theme and settings are remembered.+- Changes made elsewhere (editor, terminal) show up by themselves: the folder is watched.++**Graph**+- Every branch, coloured lanes, ↑/↓ to move. History loads 1500 commits at a time as you scroll.+- Branch and tag pills in their own column left of the graph, on each branch's tip only, joined+ to their commit: white text, a laptop icon when the branch is local, a cloud when a remote has+ it at that commit (`x` and `origin/x` make one pill), a pull-request icon when one is open,+ `+N` when more refs share the commit, the author's avatar and how long ago it was ("2 hours+ ago"). Author, date and hash columns are optional (Settings).+- An *Uncommitted changes* row on top while the working tree is dirty.+- Search (Ctrl+F) through messages, authors and hashes of all history; Enter / Shift+Enter jump+ between results, loading older history when needed.+- Right-click a commit: create a branch or a tag, check it out, cherry-pick, revert, reset the+ current branch to it (soft / mixed / hard, confirmed), the menu of each branch on it.++**Branches, remotes, worktrees, stashes, tags** (left)+- Local branches with ahead/behind; right-click: check out (or in a new worktree), merge into /+ rebase onto the current branch, push, create a pull request, rename, delete…+- Remotes: add, edit (name and URL), fetch one, remove; their branches below each.+- Worktrees: add (existing or new branch), open in a tab, open a terminal there, lock, remove,+ prune.+- Stashes: stash (with a message, untracked files included), see what a stash holds, apply, pop,+ drop.+- Pull / merge requests of GitHub (through `gh`) or GitLab (through `glab`): list, open in the+ browser, check out, create from a branch.+- Tags: create (light or annotated, optionally pushed), push, delete locally or on the remote.++**Changes and commits** (right)+- Conflicted / unstaged / staged lists with stage, unstage, discard and mark-resolved buttons,+ *Stage all* / *Unstage all*; right-click a file to open it, open it in your editor or show it in+ its folder.+- Commit box (Ctrl+Enter; with nothing staged it stages everything), *Amend last commit*+ (warns when the commit is already pushed), the identity you commit as, and saved identities to+ switch a repository to.+- Undo / redo (Ctrl+Z / Ctrl+Y) of commits, amends, merges, rebases, pulls, resets,+ cherry-picks, reverts, checkouts, branch create / rename / delete, tags and stashes.++**Diffs and conflicts** (centre)+- Unified or side by side, syntax colours, the changed part of each line marked, whitespace+ changes optional, images shown before / after. Esc closes.+- Conflicts open in a three-pane editor: each conflict's two sides with *Ours*, *Theirs* and+ *Both* buttons, and the result below (editable). *Use mine* / *Use theirs* for a whole file.+- A merge, rebase, cherry-pick or revert stopped on conflicts shows a banner with *Abort*; the+ commit box finishes it (*Continue rebase* during a rebase).++**Toolbar, terminal, app**+- Undo, redo, Fetch, Pull and Push (with incoming / outgoing counts), new branch, stash, terminal,+ search, open the folder (Explorer / Finder, your editor), refresh (F5).+- Background fetch every few minutes (Settings; 0 turns it off).+- Terminal panel with tabs: PowerShell, cmd, Git Bash, WSL… on Windows, your shells elsewhere, in a+ real pseudo-terminal (ConPTY on Windows) with colours, scrollback, mouse selection and copy+ (Ctrl+C with a selection, Ctrl+Shift+C or right-click).+- Command palette (Ctrl+P): every action and branch, fuzzy matched.+- Settings: zoom, branch column width, graph columns, avatars from Gravatar / GitHub (sends a hash+ of each author's email; can be turned off), notifications, background fetch, editor command,+ default shell and terminal font size, saved identities.+- Toasts, and a desktop notification when a long operation ends while the window is in the+ background.+- Themes: Dark, Medium Gray and Light, from PhotoCraft's Pro palettes.## Build and run@@ -53,7 +83,8 @@ cargo test```Linux needs the usual eframe system packages (e.g. `libxkbcommon-dev`, `libgtk-3-dev` for the-file dialogs).+file dialogs, `libdbus-1-dev` for notifications). Pull requests need the GitHub CLI (`gh`) or+GitLab CLI (`glab`), logged in.### Looking at the UI headlessly@@ -63,25 +94,31 @@ file dialogs).cargo run --example ui_shot -- path/to/repo /tmp/shot click:500,266 shot key:Escape shot```-Steps: `click:x,y`, `dclick:x,y`, `rclick:x,y`, `hover:x,y`, `leave`, `key:Name`, `type:text`,-`wait:ms`, `shot`. The README screenshot was made this way, on a demo repository.+Steps: `click:x,y`, `dclick:x,y`, `rclick:x,y`, `drag:x1,y1,x2,y2`, `hover:x,y`, `leave`,+`key:Name`, `ckey:Name` (with Ctrl / Cmd), `type:text`, `wait:ms`, `shot`. The README screenshot+was made this way, on a demo repository.## Layout| File | Job ||---|---|-| `src/git.rs` | `git` CLI wrapper and output parsing (refs, log, status, diffs) |+| `src/git.rs` | `git` CLI wrapper and output parsing (refs, log, status, stashes, remotes, search) || `src/graph.rs` | lane layout for the commit graph |+| `src/forge.rs` | pull / merge requests through `gh` and `glab` |+| `src/avatars.rs` | avatars from Gravatar / GitHub, cached on disk |+| `src/settings.rs` | user settings and their form || `src/theme.rs` | colour tokens, fonts, egui style (PhotoCraft's Pro themes) || `src/icons.rs` | embedded Lucide SVG icons, tinted |-| `src/repo/mod.rs` | one repository tab: state, background git work, toolbar |-| `src/repo/sidebar.rs` | branches, worktrees and tags pane |-| `src/repo/graph_view.rs` | commit graph and the branch/tag pills |-| `src/repo/detail.rs` | commit detail, changes and commit box |-| `src/repo/diff.rs` | diff parsing and the diff view |-| `src/repo/dialogs.rs` | create-branch, add-worktree and confirmation dialogs |-| `src/repo/widgets.rs` | shared painted widgets (panel headers, file rows, chips) |-| `src/terminal.rs` | integrated terminal: pty, VT parsing (`vt100`), painting, keys |-| `src/app.rs` | window shell: git check, tabs, start page, cloning, persistence |+| `src/terminal.rs` | integrated terminal: pty, VT parsing (`vt100`), painting, keys, selection |+| `src/repo/mod.rs` | one repository tab: state, background git work, undo / redo, toolbar |+| `src/repo/sidebar.rs` | branches, remotes, worktrees, stashes, pull requests, tags |+| `src/repo/graph_view.rs` | commit graph, pills, search bar, commit menu |+| `src/repo/detail.rs` | commit / stash detail, changes and commit box |+| `src/repo/diff.rs` | diff loading, pairing and the diff view (unified, split, images) |+| `src/repo/highlight.rs` | syntax colours (syntect) |+| `src/repo/conflict.rs` | three-pane conflict editor |+| `src/repo/dialogs.rs` | branch, tag, stash, remote, worktree, pull request and confirm dialogs |+| `src/repo/widgets.rs` | shared painted widgets (panel headers, file rows, avatars, tabs) |+| `src/app.rs` | window shell: tabs, start page, cloning, palette, settings, toasts |Assets and their licences: [ATTRIBUTION.md](ATTRIBUTION.md).diff --git a/assets/icons/archive.svg b/assets/icons/archive.svgnew file mode 100644index 0000000..4c5ae8e--- /dev/null+++ b/assets/icons/archive.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="20" height="5" x="2" y="3" rx="1" />+ <path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" />+ <path d="M10 12h4" />+</svg>diff --git a/assets/icons/chevron-up.svg b/assets/icons/chevron-up.svgnew file mode 100644index 0000000..b011f77--- /dev/null+++ b/assets/icons/chevron-up.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m18 15-6-6-6 6" />+</svg>diff --git a/assets/icons/columns-2.svg b/assets/icons/columns-2.svgnew file mode 100644index 0000000..79d8f66--- /dev/null+++ b/assets/icons/columns-2.svg@@ -0,0 +1,14 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="18" height="18" x="3" y="3" rx="2" />+ <path d="M12 3v18" />+</svg>diff --git a/assets/icons/command.svg b/assets/icons/command.svgnew file mode 100644index 0000000..69510a9--- /dev/null+++ b/assets/icons/command.svg@@ -0,0 +1,13 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3" />+</svg>diff --git a/assets/icons/external-link.svg b/assets/icons/external-link.svgnew file mode 100644index 0000000..a73a9ba--- /dev/null+++ b/assets/icons/external-link.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M15 3h6v6" />+ <path d="M10 14 21 3" />+ <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />+</svg>diff --git a/assets/icons/git-pull-request.svg b/assets/icons/git-pull-request.svgnew file mode 100644index 0000000..09ed1ca--- /dev/null+++ b/assets/icons/git-pull-request.svg@@ -0,0 +1,16 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="18" cy="18" r="3" />+ <circle cx="6" cy="6" r="3" />+ <path d="M13 6h3a2 2 0 0 1 2 2v7" />+ <line x1="6" x2="6" y1="9" y2="21" />+</svg>diff --git a/assets/icons/pilcrow.svg b/assets/icons/pilcrow.svgnew file mode 100644index 0000000..b290942--- /dev/null+++ b/assets/icons/pilcrow.svg@@ -0,0 +1,15 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M13 4v16" />+ <path d="M17 4v16" />+ <path d="M19 4H9.5a4.5 4.5 0 0 0 0 9H13" />+</svg>diff --git a/assets/icons/redo-2.svg b/assets/icons/redo-2.svgnew file mode 100644index 0000000..72371c8--- /dev/null+++ b/assets/icons/redo-2.svg@@ -0,0 +1,14 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="m15 14 5-5-5-5" />+ <path d="M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13" />+</svg>diff --git a/assets/icons/rows-2.svg b/assets/icons/rows-2.svgnew file mode 100644index 0000000..f31fbb5--- /dev/null+++ b/assets/icons/rows-2.svg@@ -0,0 +1,14 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <rect width="18" height="18" x="3" y="3" rx="2" />+ <path d="M3 12h18" />+</svg>diff --git a/assets/icons/settings.svg b/assets/icons/settings.svgnew file mode 100644index 0000000..4c6263a--- /dev/null+++ b/assets/icons/settings.svg@@ -0,0 +1,14 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <path d="M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915" />+ <circle cx="12" cy="12" r="3" />+</svg>diff --git a/assets/icons/user-round.svg b/assets/icons/user-round.svgnew file mode 100644index 0000000..5f27e33--- /dev/null+++ b/assets/icons/user-round.svg@@ -0,0 +1,14 @@+<svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+>+ <circle cx="12" cy="8" r="5" />+ <path d="M20 21a8 8 0 0 0-16 0" />+</svg>diff --git a/docs/screenshot.png b/docs/screenshot.pngindex 7b49629..8305250 100644Binary files a/docs/screenshot.png and b/docs/screenshot.png differdiff --git a/examples/ui_shot.rs b/examples/ui_shot.rsindex 0be27f2..3d23a3b 100644--- a/examples/ui_shot.rs+++ b/examples/ui_shot.rs@@ -4,7 +4,7 @@//! `cargo run --example ui_shot -- <repo> <out-prefix> [step]...`//!//! Steps (coordinates in points, window is 1400×860):-//! `click:x,y`, `dclick:x,y`, `rclick:x,y`, `hover:x,y`, `leave` (pointer off the window), `key:Escape`, `type:text`, `wait:ms`, `shot`.+//! `click:x,y`, `dclick:x,y`, `rclick:x,y`, `hover:x,y`, `drag:x1,y1,x2,y2`, `leave` (pointer off the window), `key:Escape`, `ckey:P` (Ctrl/Cmd+key), `type:text`, `wait:ms`, `shot`.//! Each `shot` writes `<out-prefix>-<n>.png`.use std::time::{Duration, Instant};@@ -71,6 +71,36 @@ fn main() {harness.remove_cursor();settle(&mut harness, 200);}+ "drag" => {+ let n: Vec<f32> = arg+ .split(',')+ .map(|v| v.trim().parse().unwrap_or(0.0))+ .collect();+ let (from, to) = match n[..] {+ [a, b, c, d] => (Pos2::new(a, b), Pos2::new(c, d)),+ _ => (Pos2::ZERO, Pos2::ZERO),+ };+ harness.event(Event::PointerMoved(from));+ harness.step();+ harness.event(Event::PointerButton {+ pos: from,+ button: PointerButton::Primary,+ pressed: true,+ modifiers: Modifiers::NONE,+ });+ harness.step();+ for k in 1..=8 {+ harness.event(Event::PointerMoved(from + (to - from) * (k as f32 / 8.0)));+ harness.step();+ }+ harness.event(Event::PointerButton {+ pos: to,+ button: PointerButton::Primary,+ pressed: false,+ modifiers: Modifiers::NONE,+ });+ settle(&mut harness, 300);+ }"hover" => {harness.event(Event::PointerMoved(point(arg)));settle(&mut harness, 200);@@ -81,6 +111,12 @@ fn main() {}settle(&mut harness, 200);}+ "ckey" => {+ if let Some(key) = Key::from_name(arg) {+ harness.key_press_modifiers(Modifiers::COMMAND, key);+ }+ settle(&mut harness, 300);+ }"type" => {harness.event(Event::Text(arg.to_owned()));settle(&mut harness, 200);diff --git a/src/app.rs b/src/app.rsindex f543507..eb37923 100644--- a/src/app.rs+++ b/src/app.rs@@ -9,6 +9,7 @@ use serde::{Deserialize, Serialize};use crate::git;use crate::icons;use crate::repo::RepoTab;+use crate::settings::Settings;use crate::theme::{self, ThemeKind, Tokens};const MAX_RECENT: usize = 12;@@ -23,6 +24,7 @@ struct Saved {recent: Vec<PathBuf>,theme: ThemeKind,clone_parent: Option<PathBuf>,+ settings: Settings,}enum Tab {@@ -53,6 +55,39 @@ pub struct App {clone_form: Option<CloneForm>,/// A clone running in the background: (destination, result).cloning: Option<(PathBuf, Receiver<Result<(), String>>)>,+ settings: Settings,+ settings_open: bool,+ palette: Option<Palette>,+ toasts: Vec<Toast>,+}++/// The command palette (Ctrl+P): type to filter, Enter runs.+struct Palette {+ query: String,+ selected: usize,+ focus: bool,+}++struct Toast {+ text: String,+ error: bool,+ until: std::time::Instant,+}++/// What a palette entry does outside the open repository.+enum AppCommand {+ NewTab,+ Open,+ Create,+ Clone,+ Settings,+ Theme(ThemeKind),+}++enum Entry {+ App(AppCommand),+ /// Index into the active repository's palette items.+ Repo(usize),}impl App {@@ -66,6 +101,7 @@ impl App {egui_extras::install_image_loaders(ctx);theme::install_fonts(ctx);theme::apply(ctx, saved.theme);+ saved.settings.set(ctx);let mut app = Self {git_version: git::version(),@@ -74,6 +110,10 @@ impl App {recent: saved.recent,theme: saved.theme,clone_parent: saved.clone_parent,+ settings: saved.settings.clone(),+ settings_open: false,+ palette: None,+ toasts: Vec::new(),error: None,was_focused: true,clone_form: None,@@ -316,6 +356,12 @@ impl App {ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {ui.add_space(6.0);+ if icons::small_button(ui, "settings", "Settings").clicked() {+ self.settings_open = true;+ }+ if icons::small_button(ui, "command", "Command palette (Ctrl+P)").clicked() {+ self.open_palette();+ }let resp = icons::small_button(ui, "palette", "Theme");egui::Popup::menu(&resp).show(|ui| {ui.label(@@ -607,15 +653,26 @@ impl eframe::App for App {// Shortcuts.// A focused text field or the terminal keeps these keys for itself.- let modal_open = self.clone_form.is_some() || ctx.egui_wants_keyboard_input();- let (new_tab, close, refresh, focused) = ctx.input(|i| {+ let modal_open = self.clone_form.is_some()+ || self.palette.is_some()+ || self.settings_open+ || ctx.egui_wants_keyboard_input();+ let (new_tab, close, refresh, focused, palette) = ctx.input(|i| {(i.modifiers.command && i.key_pressed(Key::T),i.modifiers.command && i.key_pressed(Key::W),i.key_pressed(Key::F5),i.focused,+ i.modifiers.command && i.key_pressed(Key::P),)});+ if palette && self.clone_form.is_none() && !self.settings_open {+ if self.palette.is_some() {+ self.palette = None;+ } else {+ self.open_palette();+ }+ }if new_tab && !modal_open {self.new_tab();}@@ -656,6 +713,8 @@ impl eframe::App for App {let active = self.active;match self.tabs.get_mut(active) {Some(Tab::Repo(repo)) => {+ repo.keys_blocked =+ self.palette.is_some() || self.settings_open || self.clone_form.is_some();repo.ui(ui);// A worktree asked to be opened in its own tab.if let Some(path) = repo.open_request.take() {@@ -669,6 +728,25 @@ impl eframe::App for App {}}self.clone_dialog(&ctx);+ self.palette_ui(&ctx);+ self.settings_ui(&ctx);++ // Long operations that ended: a toast, and a desktop notification when away.+ for tab in &mut self.tabs {+ if let Tab::Repo(r) = tab+ && let Some((text, error)) = r.finished.take()+ {+ if !focused && self.settings.notifications {+ notify(&text);+ }+ self.toasts.push(Toast {+ text,+ error,+ until: std::time::Instant::now() + std::time::Duration::from_secs(6),+ });+ }+ }+ self.toasts_ui(&ctx);}fn save(&mut self, storage: &mut dyn eframe::Storage) {@@ -694,6 +772,7 @@ impl eframe::App for App {recent: self.recent.clone(),theme: self.theme,clone_parent: self.clone_parent.clone(),+ settings: self.settings.clone(),};eframe::set_value(storage, eframe::APP_KEY, &saved);}@@ -823,3 +902,306 @@ fn strip_verbatim(path: PathBuf) -> PathBuf {_ => path,}}++impl App {+ fn open_palette(&mut self) {+ self.palette = Some(Palette {+ query: String::new(),+ selected: 0,+ focus: true,+ });+ }++ /// Every palette entry: (label, hint, what it runs).+ fn palette_entries(&self) -> Vec<(String, String, Entry)> {+ let mut list = vec![+ (+ "New tab".to_owned(),+ "Ctrl+T".to_owned(),+ Entry::App(AppCommand::NewTab),+ ),+ (+ "Open repository…".to_owned(),+ "app".to_owned(),+ Entry::App(AppCommand::Open),+ ),+ (+ "Create repository…".to_owned(),+ "app".to_owned(),+ Entry::App(AppCommand::Create),+ ),+ (+ "Clone repository…".to_owned(),+ "app".to_owned(),+ Entry::App(AppCommand::Clone),+ ),+ (+ "Settings".to_owned(),+ "app".to_owned(),+ Entry::App(AppCommand::Settings),+ ),+ ];+ for kind in ThemeKind::ALL {+ list.push((+ format!("Theme: {}", kind.label()),+ "theme".to_owned(),+ Entry::App(AppCommand::Theme(kind)),+ ));+ }+ if let Some(Tab::Repo(repo)) = self.tabs.get(self.active) {+ for (i, (label, hint, _)) in repo.palette_items().into_iter().enumerate() {+ list.push((label, hint, Entry::Repo(i)));+ }+ }+ list+ }++ fn run_entry(&mut self, entry: Entry, ctx: &egui::Context) {+ match entry {+ Entry::App(AppCommand::NewTab) => self.new_tab(),+ Entry::App(AppCommand::Open) => self.pick_existing(ctx),+ Entry::App(AppCommand::Create) => self.pick_new(ctx),+ Entry::App(AppCommand::Clone) => self.start_clone(),+ Entry::App(AppCommand::Settings) => self.settings_open = true,+ Entry::App(AppCommand::Theme(kind)) => self.set_theme(ctx, kind),+ Entry::Repo(i) => {+ if let Some(Tab::Repo(repo)) = self.tabs.get_mut(self.active)+ && let Some((_, _, action)) = repo.palette_items().into_iter().nth(i)+ {+ repo.queue(action);+ ctx.request_repaint();+ }+ }+ }+ }++ fn palette_ui(&mut self, ctx: &egui::Context) {+ if self.palette.is_none() {+ return;+ }+ let t = Tokens::get(ctx);+ let entries = self.palette_entries();+ let Some(palette) = &mut self.palette else {+ return;+ };+ let query = palette.query.to_lowercase();+ let shown: Vec<usize> = (0..entries.len())+ .filter(|&i| fuzzy(&entries[i].0.to_lowercase(), &query))+ .take(60)+ .collect();+ palette.selected = palette.selected.min(shown.len().saturating_sub(1));+ let (up, down, enter, esc) = ctx.input(|i| {+ (+ i.key_pressed(Key::ArrowUp),+ i.key_pressed(Key::ArrowDown),+ i.key_pressed(Key::Enter),+ i.key_pressed(Key::Escape),+ )+ });+ if down {+ palette.selected = (palette.selected + 1).min(shown.len().saturating_sub(1));+ }+ if up {+ palette.selected = palette.selected.saturating_sub(1);+ }+ let mut run = None;+ let mut close = esc;+ let frame = egui::Frame::new()+ .fill(t.card)+ .stroke(Stroke::new(1.0, t.field_border))+ .corner_radius(t.radius_lg)+ .inner_margin(egui::Margin::same(10))+ .shadow(ctx.global_style().visuals.window_shadow);+ let area = egui::Area::new(egui::Id::new("palette"))+ .order(egui::Order::Foreground)+ .anchor(egui::Align2::CENTER_TOP, vec2(0.0, 70.0));+ let resp = area.show(ctx, |ui| {+ frame.show(ui, |ui| {+ ui.set_width(560.0);+ let edit = ui.add(+ egui::TextEdit::singleline(&mut palette.query)+ .hint_text("Type a command or a branch…")+ .desired_width(f32::INFINITY)+ .margin(egui::Margin::symmetric(10, 8))+ .font(theme::medium(14.0)),+ );+ if std::mem::take(&mut palette.focus) {+ edit.request_focus();+ }+ if edit.changed() {+ palette.selected = 0;+ }+ ui.add_space(6.0);+ egui::ScrollArea::vertical()+ .max_height(380.0)+ .show(ui, |ui| {+ ui.spacing_mut().item_spacing.y = 0.0;+ for (k, &i) in shown.iter().enumerate() {+ let (label, hint, _) = &entries[i];+ let (rect, r) = ui.allocate_exact_size(+ vec2(ui.available_width(), 28.0),+ Sense::click(),+ );+ if k == palette.selected {+ ui.painter().rect_filled(rect, t.radius_sm, t.row_selected);+ if up || down {+ ui.scroll_to_rect(rect, None);+ }+ } else if r.hovered() {+ ui.painter().rect_filled(rect, t.radius_sm, t.hover);+ }+ ui.painter().text(+ pos2(rect.left() + 10.0, rect.center().y),+ Align2::LEFT_CENTER,+ label,+ egui::FontId::proportional(13.0),+ t.text,+ );+ ui.painter().text(+ pos2(rect.right() - 10.0, rect.center().y),+ Align2::RIGHT_CENTER,+ hint,+ egui::FontId::proportional(11.0),+ t.text_faint,+ );+ if r.clicked() {+ run = Some(i);+ }+ }+ if shown.is_empty() {+ ui.label(RichText::new("Nothing matches").color(t.text_faint));+ }+ });+ });+ });+ if enter && let Some(&i) = shown.get(palette.selected) {+ run = Some(i);+ }+ if resp.response.clicked_elsewhere()+ && ctx.input(|i| i.pointer.any_pressed())+ && run.is_none()+ {+ close = true;+ }+ if close || run.is_some() {+ self.palette = None;+ }+ if let Some(i) = run+ && let Some((_, _, entry)) = entries.into_iter().nth(i)+ {+ self.run_entry(entry, ctx);+ }+ }++ fn settings_ui(&mut self, ctx: &egui::Context) {+ if !self.settings_open {+ return;+ }+ let t = Tokens::get(ctx);+ let frame = egui::Frame::new()+ .fill(t.card)+ .stroke(Stroke::new(1.0, t.field_border))+ .corner_radius(t.radius_lg)+ .inner_margin(egui::Margin::same(18))+ .shadow(ctx.global_style().visuals.window_shadow);+ let mut close = false;+ let resp = egui::Modal::new(egui::Id::new("settings"))+ .frame(frame)+ .backdrop_color(egui::Color32::from_black_alpha(110))+ .show(ctx, |ui| {+ ui.set_width(560.0);+ ui.horizontal(|ui| {+ ui.label(RichText::new("Settings").font(theme::semibold(16.0)));+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if icons::small_button(ui, "x", "Close").clicked() {+ close = true;+ }+ });+ });+ egui::ScrollArea::vertical()+ .max_height(560.0)+ .show(ui, |ui| {+ if self.settings.ui(ui) {+ self.settings.set(ui.ctx());+ }+ });+ });+ if close || resp.should_close() {+ self.settings_open = false;+ }+ }++ fn toasts_ui(&mut self, ctx: &egui::Context) {+ let now = std::time::Instant::now();+ self.toasts.retain(|t| t.until > now);+ if self.toasts.is_empty() {+ return;+ }+ ctx.request_repaint_after(std::time::Duration::from_millis(500));+ let t = Tokens::get(ctx);+ egui::Area::new(egui::Id::new("toasts"))+ .order(egui::Order::Tooltip)+ .anchor(egui::Align2::RIGHT_BOTTOM, vec2(-16.0, -16.0))+ .show(ctx, |ui| {+ for toast in &self.toasts {+ egui::Frame::new()+ .fill(t.card)+ .stroke(Stroke::new(+ 1.0,+ if toast.error { t.danger } else { t.success },+ ))+ .corner_radius(t.radius_lg)+ .inner_margin(egui::Margin::symmetric(14, 10))+ .shadow(ctx.global_style().visuals.popup_shadow)+ .show(ui, |ui| {+ ui.set_max_width(380.0);+ ui.horizontal(|ui| {+ let icon = if toast.error { "circle-alert" } else { "check" };+ icons::inline(+ ui,+ icon,+ 16.0,+ if toast.error { t.danger } else { t.success },+ );+ ui.add(egui::Label::new(&toast.text).wrap());+ });+ });+ ui.add_space(6.0);+ }+ });+ }+}++/// `needle`'s characters appear in `haystack` in order ("cmain" → "Check out main").+fn fuzzy(haystack: &str, needle: &str) -> bool {+ let mut chars = haystack.chars();+ needle+ .chars()+ .filter(|c| !c.is_whitespace())+ .all(|n| chars.any(|h| h == n))+}++/// A desktop notification, on its own thread (it can take a moment to show).+fn notify(text: &str) {+ let text = text.to_owned();+ std::thread::spawn(move || {+ let _ = notify_rust::Notification::new()+ .appname("gitcraft")+ .summary("gitcraft")+ .body(&text)+ .show();+ });+}++#[cfg(test)]+mod tests {+ use super::fuzzy;++ #[test]+ fn fuzzy_matching() {+ assert!(fuzzy("check out main", "cmain"));+ assert!(fuzzy("check out main", "co main"));+ assert!(!fuzzy("fetch", "push"));+ assert!(fuzzy("anything", ""));+ }+}diff --git a/src/avatars.rs b/src/avatars.rsnew file mode 100644index 0000000..4fe87fb--- /dev/null+++ b/src/avatars.rs@@ -0,0 +1,174 @@+//! Author avatars from Gravatar (or GitHub for its noreply addresses), fetched in the+//! background, cached on disk, painted round. Initials stand in until (or unless) one loads.++use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::mpsc::{Sender, channel};+use std::sync::{Arc, Mutex, OnceLock};+use std::time::{Duration, SystemTime};++use egui::{Rect, Vec2, load::Bytes};++/// A missing avatar is asked for again after this long.+const RETRY_MISSING: Duration = Duration::from_secs(7 * 24 * 3600);++#[derive(Clone)]+enum State {+ Pending,+ Ready(Arc<[u8]>),+ Missing,+}++struct Avatars {+ map: Mutex<HashMap<String, State>>,+ queue: Mutex<Sender<String>>,+}++fn cache_dir() -> Option<PathBuf> {+ eframe::storage_dir("gitcraft").map(|d| d.join("avatars"))+}++fn avatars(ctx: &egui::Context) -> &'static Avatars {+ static AVATARS: OnceLock<Avatars> = OnceLock::new();+ AVATARS.get_or_init(|| {+ let (tx, rx) = channel::<String>();+ let ctx = ctx.clone();+ std::thread::spawn(move || {+ let agent = ureq::AgentBuilder::new()+ .timeout(Duration::from_secs(8))+ .user_agent("gitcraft")+ .build();+ while let Ok(email) = rx.recv() {+ let state = fetch(&agent, &email);+ if let Some(map) = AVATARS.get() {+ lock(&map.map).insert(email, state);+ }+ ctx.request_repaint();+ }+ });+ Avatars {+ map: Mutex::new(HashMap::new()),+ queue: Mutex::new(tx),+ }+ })+}++fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {+ match m.lock() {+ Ok(g) => g,+ Err(p) => p.into_inner(),+ }+}++fn key(email: &str) -> String {+ format!("{:x}", md5::compute(email.trim().to_lowercase()))+}++/// Where to ask: GitHub knows its noreply addresses, Gravatar the rest.+fn url(email: &str) -> String {+ let email = email.trim().to_lowercase();+ if let Some(local) = email.strip_suffix("@users.noreply.github.com") {+ return match local.split_once('+') {+ Some((id, _)) => format!("https://avatars.githubusercontent.com/u/{id}?s=80"),+ None => format!("https://github.com/{local}.png?size=80"),+ };+ }+ format!("https://www.gravatar.com/avatar/{}?s=80&d=404", key(&email))+}++fn fetch(agent: &ureq::Agent, email: &str) -> State {+ let dir = cache_dir();+ let k = key(email);+ if let Some(dir) = &dir {+ if let Ok(bytes) = std::fs::read(dir.join(format!("{k}.img"))) {+ return State::Ready(Arc::from(bytes.into_boxed_slice()));+ }+ let missing = dir.join(format!("{k}.none"));+ let recent = std::fs::metadata(&missing)+ .and_then(|m| m.modified())+ .ok()+ .and_then(|t| SystemTime::now().duration_since(t).ok())+ .is_some_and(|age| age < RETRY_MISSING);+ if recent {+ return State::Missing;+ }+ }+ let result = agent.get(&url(email)).call().ok().and_then(|resp| {+ let mut bytes = Vec::new();+ use std::io::Read;+ resp.into_reader()+ .take(512 * 1024)+ .read_to_end(&mut bytes)+ .ok()+ .map(|_| bytes)+ });+ match result {+ Some(bytes) if !bytes.is_empty() => {+ if let Some(dir) = &dir {+ let _ = std::fs::create_dir_all(dir);+ let _ = std::fs::write(dir.join(format!("{k}.img")), &bytes);+ }+ State::Ready(Arc::from(bytes.into_boxed_slice()))+ }+ _ => {+ if let Some(dir) = &dir {+ let _ = std::fs::create_dir_all(dir);+ let _ = std::fs::write(dir.join(format!("{k}.none")), b"");+ }+ State::Missing+ }+ }+}++/// Paints `email`'s avatar into `rect` if it is loaded; returns false (and queues a download)+/// otherwise, so the caller keeps its initials.+pub fn paint(ui: &egui::Ui, rect: Rect, email: &str) -> bool {+ if email.is_empty() || !crate::settings::Settings::get(ui.ctx()).avatars {+ return false;+ }+ let av = avatars(ui.ctx());+ let k = email.trim().to_lowercase();+ let state = {+ let mut map = lock(&av.map);+ match map.get(&k) {+ Some(s) => s.clone(),+ None => {+ map.insert(k.clone(), State::Pending);+ let _ = lock(&av.queue).send(k.clone());+ State::Pending+ }+ }+ };+ let State::Ready(bytes) = state else {+ return false;+ };+ let uri = format!("bytes://avatar/{}.png", key(&k));+ egui::Image::from_bytes(uri, Bytes::Shared(bytes))+ .fit_to_exact_size(Vec2::splat(rect.width()))+ .corner_radius(rect.width() / 2.0)+ .show_loading_spinner(false)+ .paint_at(ui, rect);+ true+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn avatar_urls() {+ assert_eq!(+ url("[email protected]"),+ "https://avatars.githubusercontent.com/u/12345?s=80"+ );+ assert_eq!(+ url("[email protected]"),+ "https://github.com/octo.png?size=80"+ );+ // Gravatar hashes the trimmed, lowercased address.+ assert_eq!(+ url(" [email protected] "),+ "https://www.gravatar.com/avatar/0bc83cb571cd1c50ba6f3e8a78ef1346?s=80&d=404"+ );+ }+}diff --git a/src/forge.rs b/src/forge.rsnew file mode 100644index 0000000..055d2a5--- /dev/null+++ b/src/forge.rs@@ -0,0 +1,214 @@+//! Pull requests through the forges' own command-line tools: `gh` for GitHub, `glab` for+//! GitLab. They hold the user's login, so gitcraft never stores a token.++use std::path::Path;+use std::process::Command;++use crate::git::Remote;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Forge {+ GitHub,+ GitLab,+}++impl Forge {+ pub fn tool(self) -> &'static str {+ match self {+ Forge::GitHub => "gh",+ Forge::GitLab => "glab",+ }+ }++ /// "pull request" or "merge request".+ pub fn noun(self) -> &'static str {+ match self {+ Forge::GitHub => "pull request",+ Forge::GitLab => "merge request",+ }+ }+}++/// The forge hosting `origin` (or the first remote), from its URL.+pub fn detect(remotes: &[Remote]) -> Option<Forge> {+ let remote = remotes+ .iter()+ .find(|r| r.name == "origin")+ .or_else(|| remotes.first())?;+ let url = remote.url.to_lowercase();+ if url.contains("github.com") || url.contains("github.") {+ Some(Forge::GitHub)+ } else if url.contains("gitlab") {+ Some(Forge::GitLab)+ } else {+ None+ }+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct PullRequest {+ pub number: u64,+ pub title: String,+ /// The branch it proposes (head / source branch).+ pub branch: String,+ pub author: String,+ pub url: String,+ pub draft: bool,+}++fn tool(forge: Forge, repo: &Path, args: &[&str]) -> Result<String, String> {+ let mut cmd = Command::new(forge.tool());+ cmd.current_dir(repo).args(args);+ cmd.env("GH_PROMPT_DISABLED", "1").env("NO_PROMPT", "1");+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x0800_0000);+ }+ let out = cmd.output().map_err(|_| {+ format!(+ "{} isn't installed: gitcraft uses it for {}s",+ forge.tool(),+ forge.noun()+ )+ })?;+ if out.status.success() {+ Ok(String::from_utf8_lossy(&out.stdout).into_owned())+ } else {+ Err(String::from_utf8_lossy(&out.stderr).trim().to_owned())+ }+}++pub fn list(repo: &Path, forge: Forge) -> Result<Vec<PullRequest>, String> {+ let out = match forge {+ Forge::GitHub => tool(+ forge,+ repo,+ &[+ "pr",+ "list",+ "--state",+ "open",+ "--limit",+ "100",+ "--json",+ "number,title,headRefName,author,url,isDraft",+ ],+ )?,+ Forge::GitLab => tool(forge, repo, &["mr", "list", "--output", "json"])?,+ };+ parse(forge, &out)+}++fn parse(forge: Forge, json: &str) -> Result<Vec<PullRequest>, String> {+ let value: serde_json::Value = serde_json::from_str(json)+ .map_err(|e| format!("unexpected {} output: {e}", forge.tool()))?;+ let items = value.as_array().cloned().unwrap_or_default();+ let s = |v: &serde_json::Value, path: &[&str]| -> String {+ let mut cur = v;+ for key in path {+ match cur.get(*key) {+ Some(next) => cur = next,+ None => return String::new(),+ }+ }+ cur.as_str().map(str::to_owned).unwrap_or_default()+ };+ Ok(items+ .iter()+ .map(|item| match forge {+ Forge::GitHub => PullRequest {+ number: item.get("number").and_then(|n| n.as_u64()).unwrap_or(0),+ title: s(item, &["title"]),+ branch: s(item, &["headRefName"]),+ author: s(item, &["author", "login"]),+ url: s(item, &["url"]),+ draft: item+ .get("isDraft")+ .and_then(|d| d.as_bool())+ .unwrap_or(false),+ },+ Forge::GitLab => PullRequest {+ number: item.get("iid").and_then(|n| n.as_u64()).unwrap_or(0),+ title: s(item, &["title"]),+ branch: s(item, &["source_branch"]),+ author: s(item, &["author", "username"]),+ url: s(item, &["web_url"]),+ draft: item.get("draft").and_then(|d| d.as_bool()).unwrap_or(false),+ },+ })+ .collect())+}++/// Opens a pull request from `branch` into `base`; returns what the tool printed (its URL).+pub fn create(+ repo: &Path,+ forge: Forge,+ branch: &str,+ base: &str,+ title: &str,+ body: &str,+ draft: bool,+) -> Result<String, String> {+ let mut args: Vec<&str> = match forge {+ Forge::GitHub => vec![+ "pr", "create", "--head", branch, "--base", base, "--title", title, "--body", body,+ ],+ Forge::GitLab => vec![+ "mr",+ "create",+ "--source-branch",+ branch,+ "--target-branch",+ base,+ "--title",+ title,+ "--description",+ body,+ "--yes",+ ],+ };+ if draft {+ args.push("--draft");+ }+ tool(forge, repo, &args).map(|out| out.trim().to_owned())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn detects_forge_from_origin() {+ let r = |name: &str, url: &str| Remote {+ name: name.into(),+ url: url.into(),+ };+ assert_eq!(+ detect(&[r("origin", "[email protected]:a/b.git")]),+ Some(Forge::GitHub)+ );+ assert_eq!(+ detect(&[+ r("up", "https://github.com/x/y"),+ r("origin", "https://gitlab.com/a/b")+ ]),+ Some(Forge::GitLab)+ );+ assert_eq!(detect(&[r("origin", "C:/repos/bare.git")]), None);+ }++ #[test]+ fn parses_both_forges() {+ let gh = r#"[{"number":7,"title":"Fix","headRefName":"fix/x","author":{"login":"ana"},"url":"https://g/7","isDraft":true}]"#;+ let prs = parse(Forge::GitHub, gh).unwrap_or_default();+ assert_eq!(prs.len(), 1);+ assert_eq!(+ (prs[0].number, prs[0].branch.as_str(), prs[0].draft),+ (7, "fix/x", true)+ );+ let gl = r#"[{"iid":3,"title":"Add","source_branch":"feat","author":{"username":"bo"},"web_url":"u","draft":false}]"#;+ let mrs = parse(Forge::GitLab, gl).unwrap_or_default();+ assert_eq!((mrs[0].number, mrs[0].author.as_str()), (3, "bo"));+ }+}diff --git a/src/git.rs b/src/git.rsindex 69ae4c3..37ceccd 100644--- a/src/git.rs+++ b/src/git.rs@@ -8,14 +8,16 @@ use std::process::Command;const FS: char = '\x1f';const RS: char = '\x1e';-/// How many commits the graph loads per repository.-pub const LOG_LIMIT: usize = 5000;+/// How many commits the graph loads at a time; scrolling to the end loads the next page.+pub const LOG_PAGE: usize = 1500;fn git_cmd() -> Command {let mut cmd = Command::new("git");// Never block on an interactive prompt: credential helpers with a GUI still work.cmd.env("GIT_TERMINAL_PROMPT", "0");cmd.env("GIT_OPTIONAL_LOCKS", "0");+ // `rebase --continue`, `merge --continue`… would otherwise open an editor nobody sees.+ cmd.env("GIT_EDITOR", "true");#[cfg(windows)]{use std::os::windows::process::CommandExt;@@ -30,6 +32,23 @@ pub fn run(dir: Option<&Path>, args: &[&str]) -> Result<String, String> {run_ok_codes(dir, args, &[0])}+/// Runs git and returns stdout as raw bytes (file contents: images…).+pub fn run_bytes(dir: Option<&Path>, args: &[&str]) -> Result<Vec<u8>, String> {+ let mut cmd = git_cmd();+ if let Some(dir) = dir {+ cmd.arg("-C").arg(dir);+ }+ cmd.args(args);+ let out = cmd+ .output()+ .map_err(|e| format!("could not run git: {e}"))?;+ if out.status.success() {+ Ok(out.stdout)+ } else {+ Err(String::from_utf8_lossy(&out.stderr).trim().to_owned())+ }+}+/// Like [`run`], but exit codes in `ok` count as success (`diff --no-index` exits 1 on changes).pub fn run_ok_codes(dir: Option<&Path>, args: &[&str], ok: &[i32]) -> Result<String, String> {let mut cmd = git_cmd();@@ -182,28 +201,35 @@ pub fn refs(repo: &Path) -> Result<Refs, String> {Ok(refs)}-#[derive(Clone, Debug)]+#[derive(Clone, Debug, Default)]pub struct Commit {pub hash: String,pub parents: Vec<String>,pub author: String,+ pub email: String,+ /// Author time, seconds since the Unix epoch.+ pub time: i64,pub date: String,pub summary: String,/// Decorations (`HEAD -> main`, `origin/main`, `tag: v1`), as git prints them.pub refs: Vec<String>,}-/// The commits of every branch, newest first, in an order fit for drawing the graph.-pub fn log(repo: &Path) -> Result<Vec<Commit>, String> {- let format = format!("--format=%H{FS}%P{FS}%an{FS}%ad{FS}%s{FS}%D{RS}");- let limit = format!("--max-count={LOG_LIMIT}");+/// The commits of every branch (stashes aside), newest first, in an order fit for drawing the+/// graph: `limit` of them after the first `skip`.+pub fn log(repo: &Path, skip: usize, limit: usize) -> Result<Vec<Commit>, String> {+ let format = format!("--format=%H{FS}%P{FS}%an{FS}%ae{FS}%at{FS}%ad{FS}%s{FS}%D{RS}");+ let limit = format!("--max-count={limit}");+ let skip = format!("--skip={skip}");let out = match run(Some(repo),&["log",+ "--exclude=refs/stash","--all","--date-order","--date=format-local:%Y-%m-%d %H:%M",+ &skip,&limit,&format,],@@ -220,13 +246,15 @@ pub fn log(repo: &Path) -> Result<Vec<Commit>, String> {continue;}let f: Vec<&str> = record.split(FS).collect();- let [hash, parents, author, date, summary, decor] = f[..] else {+ let [hash, parents, author, email, time, date, summary, decor] = f[..] else {continue;};commits.push(Commit {hash: hash.to_owned(),parents: parents.split_whitespace().map(str::to_owned).collect(),author: author.to_owned(),+ email: email.to_owned(),+ time: time.parse().unwrap_or(0),date: date.to_owned(),summary: summary.to_owned(),refs: decor@@ -371,20 +399,14 @@ fn parse_numstat(out: &str) -> Vec<(String, Option<u32>, Option<u32>)> {result}-/// The patch of one file in a commit.-pub fn file_diff(repo: &Path, hash: &str, path: &str) -> Result<String, String> {- run(- Some(repo),- &[- "show",- "--format=",- "--diff-merges=first-parent",- "-M",- hash,- "--",- path,- ],- )+/// The patch of one file in a commit (`ignore_ws`: `-w`).+pub fn file_diff(repo: &Path, hash: &str, path: &str, ignore_ws: bool) -> Result<String, String> {+ let mut args = vec!["show", "--format=", "--diff-merges=first-parent", "-M"];+ if ignore_ws {+ args.push("-w");+ }+ args.extend([hash, "--", path]);+ run(Some(repo), &args)}/// Which side of the index a working-tree file is listed on.@@ -411,6 +433,7 @@ pub enum InProgress {Merge,CherryPick,Revert,+ Rebase,}impl InProgress {@@ -419,6 +442,7 @@ impl InProgress {InProgress::Merge => "Merge",InProgress::CherryPick => "Cherry-pick",InProgress::Revert => "Revert",+ InProgress::Rebase => "Rebase",}}@@ -428,6 +452,7 @@ impl InProgress {InProgress::Merge => "merge",InProgress::CherryPick => "cherry-pick",InProgress::Revert => "revert",+ InProgress::Rebase => "rebase",}}}@@ -530,12 +555,21 @@ pub fn status(repo: &Path) -> Result<WorkStatus, String> {&["status", "--porcelain=v1", "-z", "--untracked-files=all"],)?;let mut status = parse_status(&out);+ for dir in ["rebase-merge", "rebase-apply"] {+ if let Ok(path) = run(Some(repo), &["rev-parse", "--git-path", dir])+ && repo.join(path.trim()).is_dir()+ {+ status.in_progress = Some(InProgress::Rebase);+ }+ }for (state, head) in [(InProgress::Merge, "MERGE_HEAD"),(InProgress::CherryPick, "CHERRY_PICK_HEAD"),(InProgress::Revert, "REVERT_HEAD"),] {- if run(Some(repo), &["rev-parse", "-q", "--verify", head]).is_ok() {+ if status.in_progress.is_none()+ && run(Some(repo), &["rev-parse", "-q", "--verify", head]).is_ok()+ {status.in_progress = Some(state);break;}@@ -597,12 +631,19 @@ fn parse_status(out: &str) -> WorkStatus {status}-/// The patch of one uncommitted file.-pub fn work_diff(repo: &Path, file: &StatusFile) -> Result<String, String> {+/// The patch of one uncommitted file (`ignore_ws`: `-w`).+pub fn work_diff(repo: &Path, file: &StatusFile, ignore_ws: bool) -> Result<String, String> {let path = file.path.as_str();+ let mut args: Vec<&str> = match file.area {+ Area::Staged => vec!["diff", "--cached", "-M"],+ _ => vec!["diff"],+ };+ if ignore_ws {+ args.push("-w");+ }+ args.extend(["--", path]);match file.area {- Area::Staged => run(Some(repo), &["diff", "--cached", "-M", "--", path]),- Area::Unstaged | Area::Conflicted => run(Some(repo), &["diff", "--", path]),+ Area::Staged | Area::Unstaged | Area::Conflicted => run(Some(repo), &args),// An untracked file has no history: show it as all added.Area::Untracked => run_ok_codes(Some(repo),@@ -612,6 +653,169 @@ pub fn work_diff(repo: &Path, file: &StatusFile) -> Result<String, String> {}}+/// The contents of `path` at `rev` (`HEAD`, a hash, or `""` for the index), or from disk when+/// `rev` is `None`.+pub fn file_at(repo: &Path, rev: Option<&str>, path: &str) -> Result<Vec<u8>, String> {+ match rev {+ None => std::fs::read(repo.join(path)).map_err(|e| format!("{path}: {e}")),+ Some(rev) => run_bytes(Some(repo), &["show", &format!("{rev}:{path}")]),+ }+}++/// HEAD's commit hash, or empty before the first commit.+pub fn head(repo: &Path) -> String {+ run(Some(repo), &["rev-parse", "--verify", "-q", "HEAD"])+ .map(|s| s.trim().to_owned())+ .unwrap_or_default()+}++/// The full message of HEAD (to amend it).+pub fn head_message(repo: &Path) -> Result<String, String> {+ run(Some(repo), &["log", "-1", "--format=%B"]).map(|s| s.trim_end().to_owned())+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Stash {+ /// `stash@{0}`.+ pub name: String,+ pub hash: String,+ pub message: String,+ pub time: i64,+}++pub fn stashes(repo: &Path) -> Result<Vec<Stash>, String> {+ let out = run(+ Some(repo),+ &[+ "stash",+ "list",+ &format!("--format=%gd{FS}%H{FS}%gs{FS}%at"),+ ],+ )?;+ Ok(out+ .lines()+ .filter_map(|line| {+ let f: Vec<&str> = line.split(FS).collect();+ let [name, hash, message, time] = f[..] else {+ return None;+ };+ // `On main: wip` / `WIP on main: 1234 msg` → the part after the colon reads better.+ let message = message+ .split_once(": ")+ .map(|(_, m)| m)+ .unwrap_or(message)+ .to_owned();+ Some(Stash {+ name: name.to_owned(),+ hash: hash.to_owned(),+ message,+ time: time.parse().unwrap_or(0),+ })+ })+ .collect())+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Remote {+ pub name: String,+ pub url: String,+}++pub fn remotes(repo: &Path) -> Result<Vec<Remote>, String> {+ let out = run(Some(repo), &["remote", "-v"])?;+ let mut list: Vec<Remote> = Vec::new();+ for line in out.lines() {+ let mut parts = line.split_whitespace();+ let (Some(name), Some(url)) = (parts.next(), parts.next()) else {+ continue;+ };+ if !list.iter().any(|r| r.name == name) {+ list.push(Remote {+ name: name.to_owned(),+ url: url.to_owned(),+ });+ }+ }+ Ok(list)+}++/// Commits whose message or author matches `query` (case-insensitive), or whose hash starts+/// with it, newest first.+pub fn search(repo: &Path, query: &str) -> Result<Vec<String>, String> {+ let mut hashes: Vec<String> = Vec::new();+ let base = [+ "log",+ "--exclude=refs/stash",+ "--all",+ "--date-order",+ "-i",+ "--format=%H",+ ];+ for filter in [format!("--grep={query}"), format!("--author={query}")] {+ let mut args = base.to_vec();+ args.push("--fixed-strings");+ args.push(&filter);+ if let Ok(out) = run(Some(repo), &args) {+ for h in out.lines() {+ if !hashes.iter().any(|x| x == h) {+ hashes.push(h.to_owned());+ }+ }+ }+ }+ let q = query.trim();+ if q.len() >= 4+ && q.chars().all(|c| c.is_ascii_hexdigit())+ && let Ok(h) = run(+ Some(repo),+ &["rev-parse", "--verify", "-q", &format!("{q}^{{commit}}")],+ )+ {+ hashes.insert(0, h.trim().to_owned());+ }+ Ok(hashes)+}++/// The name and email commits are made with here, and whether they're set for this repository+/// only.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Identity {+ pub name: String,+ pub email: String,+ pub local: bool,+}++pub fn identity(repo: &Path) -> Identity {+ let get = |args: &[&str]| run(Some(repo), args).map(|s| s.trim().to_owned()).ok();+ Identity {+ name: get(&["config", "user.name"]).unwrap_or_default(),+ email: get(&["config", "user.email"]).unwrap_or_default(),+ local: get(&["config", "--local", "user.name"]).is_some(),+ }+}++/// "3 minutes ago", "2 days ago"… for `time` seen from `now` (both Unix seconds).+pub fn relative_time(time: i64, now: i64) -> String {+ let secs = (now - time).max(0);+ let (n, unit) = match secs {+ 0..60 => return "just now".to_owned(),+ 60..3_600 => (secs / 60, "minute"),+ 3_600..86_400 => (secs / 3_600, "hour"),+ 86_400..604_800 => (secs / 86_400, "day"),+ 604_800..2_629_800 => (secs / 604_800, "week"),+ 2_629_800..31_557_600 => (secs / 2_629_800, "month"),+ _ => (secs / 31_557_600, "year"),+ };+ format!("{n} {unit}{} ago", if n == 1 { "" } else { "s" })+}++pub fn now() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs() as i64)+ .unwrap_or(0)+}+#[cfg(test)]mod tests {use super::*;@@ -635,6 +839,17 @@ mod tests {assert_eq!(s.conflicted.len(), 1);}+ #[test]+ fn relative_times() {+ assert_eq!(relative_time(1000, 1030), "just now");+ assert_eq!(relative_time(0, 60), "1 minute ago");+ assert_eq!(relative_time(0, 2 * 3_600), "2 hours ago");+ assert_eq!(relative_time(0, 5 * 86_400), "5 days ago");+ assert_eq!(relative_time(0, 3 * 604_800), "3 weeks ago");+ assert_eq!(relative_time(0, 400 * 86_400), "1 year ago");+ assert_eq!(relative_time(100, 50), "just now");+ }+#[test]fn worktree_list() {let out = "worktree C:/src/app\0HEAD abc\0branch refs/heads/main\0\0\diff --git a/src/graph.rs b/src/graph.rsindex d7753eb..2b5e1c1 100644--- a/src/graph.rs+++ b/src/graph.rs@@ -100,6 +100,7 @@ mod tests {date: String::new(),summary: String::new(),refs: Vec::new(),+ ..Commit::default()}}diff --git a/src/icons.rs b/src/icons.rsindex 2768957..505a6bc 100644--- a/src/icons.rs+++ b/src/icons.rs@@ -16,6 +16,7 @@ macro_rules! icons {}const SOURCES: &[(&str, &str)] = icons![+ "archive","arrow-down","arrow-down-to-line","arrow-up",@@ -23,28 +24,38 @@ const SOURCES: &[(&str, &str)] = icons!["check","chevron-down","chevron-right",+ "chevron-up","circle-alert","cloud","cloud-download",+ "columns-2",+ "command","copy",+ "external-link","file-diff","folder-git-2","folder-open","folder-plus",+ "folder-tree","git-branch","git-branch-plus","git-merge",+ "git-pull-request","laptop","log-in","minus","palette",+ "pilcrow","plus",+ "redo-2","refresh-cw",+ "rows-2","search",+ "settings","square-terminal",- "folder-tree","tag","undo-2",+ "user-round","x",];diff --git a/src/lib.rs b/src/lib.rsindex c01f722..2672c86 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -1,9 +1,12 @@//! gitcraft: a small, personal visual git client (egui front end over the git command line).pub mod app;+mod avatars;+mod forge;mod git;mod graph;mod icons;mod repo;+mod settings;mod terminal;mod theme;diff --git a/src/repo/conflict.rs b/src/repo/conflict.rsnew file mode 100644index 0000000..79e85a3--- /dev/null+++ b/src/repo/conflict.rs@@ -0,0 +1,489 @@+//! Three-pane conflict editor: each conflict's "ours" and "theirs" side by side with buttons to+//! pick a side (or both), and the resulting file below, editable by hand.++use std::path::Path;++use egui::{RichText, Sense, Stroke, Ui, vec2};++use super::{Action, Refresh, RepoTab, ops};+use crate::git::InProgress;+use crate::icons;+use crate::theme::{self, Tokens};++#[derive(Clone, Debug, PartialEq, Eq)]+enum Segment {+ Common(String),+ Conflict {+ ours: String,+ base: Option<String>,+ theirs: String,+ },+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Choice {+ Ours,+ Theirs,+ OursThenTheirs,+ TheirsThenOurs,+}++pub struct ConflictEditor {+ pub path: String,+ segments: Vec<Segment>,+ choices: Vec<Option<Choice>>,+ pub result: String,+ /// The result was edited by hand; choices no longer rewrite it.+ manual: bool,+ ours_label: String,+ theirs_label: String,+ /// During a rebase "ours" is the branch being rebased onto, "theirs" your own commit.+ rebase: bool,+}++/// Splits a file with conflict markers into common text and conflicts (diff3 bases kept).+fn parse(text: &str) -> (Vec<Segment>, String, String) {+ enum State {+ Common,+ Ours,+ Base,+ Theirs,+ }+ let mut segments = Vec::new();+ let (mut common, mut ours, mut base, mut theirs) =+ (String::new(), String::new(), None::<String>, String::new());+ let (mut ours_label, mut theirs_label) = (String::new(), String::new());+ let mut state = State::Common;+ for line in text.split_inclusive('\n') {+ let bare = line.trim_end_matches(['\r', '\n']);+ match state {+ State::Common if bare.starts_with("<<<<<<<") => {+ if !common.is_empty() {+ segments.push(Segment::Common(std::mem::take(&mut common)));+ }+ if ours_label.is_empty() {+ ours_label = bare.trim_start_matches('<').trim().to_owned();+ }+ state = State::Ours;+ }+ State::Common => common.push_str(line),+ State::Ours if bare.starts_with("|||||||") => {+ base = Some(String::new());+ state = State::Base;+ }+ State::Ours | State::Base if bare.starts_with("=======") => state = State::Theirs,+ State::Ours => ours.push_str(line),+ State::Base => {+ if let Some(b) = &mut base {+ b.push_str(line);+ }+ }+ State::Theirs if bare.starts_with(">>>>>>>") => {+ if theirs_label.is_empty() {+ theirs_label = bare.trim_start_matches('>').trim().to_owned();+ }+ segments.push(Segment::Conflict {+ ours: std::mem::take(&mut ours),+ base: base.take(),+ theirs: std::mem::take(&mut theirs),+ });+ state = State::Common;+ }+ State::Theirs => theirs.push_str(line),+ }+ }+ if !common.is_empty() {+ segments.push(Segment::Common(common));+ }+ (segments, ours_label, theirs_label)+}++/// The file for the current choices; undecided conflicts keep their markers.+fn render(segments: &[Segment], choices: &[Option<Choice>], labels: (&str, &str)) -> String {+ let mut out = String::new();+ let mut k = 0;+ for seg in segments {+ match seg {+ Segment::Common(text) => out.push_str(text),+ Segment::Conflict { ours, base, theirs } => {+ match choices.get(k).copied().flatten() {+ Some(Choice::Ours) => out.push_str(ours),+ Some(Choice::Theirs) => out.push_str(theirs),+ Some(Choice::OursThenTheirs) => {+ out.push_str(ours);+ out.push_str(theirs);+ }+ Some(Choice::TheirsThenOurs) => {+ out.push_str(theirs);+ out.push_str(ours);+ }+ None => {+ out.push_str(&format!("<<<<<<< {}\n", labels.0));+ out.push_str(ours);+ if let Some(base) = base {+ out.push_str("||||||| base\n");+ out.push_str(base);+ }+ out.push_str("=======\n");+ out.push_str(theirs);+ out.push_str(&format!(">>>>>>> {}\n", labels.1));+ }+ }+ k += 1;+ }+ }+ }+ out+}++impl ConflictEditor {+ /// Opens `path` if it still has conflict markers.+ pub fn open(repo: &Path, path: &str, state: Option<InProgress>) -> Option<Self> {+ let text = std::fs::read_to_string(repo.join(path)).ok()?;+ let (segments, ours_label, theirs_label) = parse(&text);+ let conflicts = segments+ .iter()+ .filter(|s| matches!(s, Segment::Conflict { .. }))+ .count();+ if conflicts == 0 {+ return None;+ }+ Some(Self {+ path: path.to_owned(),+ choices: vec![None; conflicts],+ segments,+ result: text,+ manual: false,+ ours_label,+ theirs_label,+ rebase: state == Some(InProgress::Rebase),+ })+ }++ fn choose(&mut self, k: usize, choice: Choice) {+ if let Some(c) = self.choices.get_mut(k) {+ *c = if *c == Some(choice) {+ None+ } else {+ Some(choice)+ };+ }+ self.manual = false;+ self.result = render(+ &self.segments,+ &self.choices,+ (&self.ours_label, &self.theirs_label),+ );+ }++ fn unresolved(&self) -> usize {+ self.result+ .lines()+ .filter(|l| l.starts_with("<<<<<<<"))+ .count()+ }++ pub fn save(&self, repo: &Path) -> Result<(), String> {+ let left = self.unresolved();+ if left > 0 {+ return Err(format!(+ "{left} conflict{} still unresolved in {}",+ if left == 1 { "" } else { "s" },+ self.path+ ));+ }+ std::fs::write(repo.join(&self.path), &self.result)+ .map_err(|e| format!("Could not save {}: {e}", self.path))+ }++ /// Names for the two sides as the user thinks of them.+ fn side_names(&self) -> (String, String) {+ if self.rebase {+ (+ format!("Upstream ({})", short(&self.ours_label)),+ format!("Your commit ({})", short(&self.theirs_label)),+ )+ } else {+ (+ format!("Ours ({})", short(&self.ours_label)),+ format!("Theirs ({})", short(&self.theirs_label)),+ )+ }+ }+}++fn short(label: &str) -> String {+ let s = label.split_whitespace().next().unwrap_or(label);+ if s.chars().count() > 28 {+ format!("{}…", s.chars().take(27).collect::<String>())+ } else {+ s.to_owned()+ }+}++impl RepoTab {+ pub(super) fn conflict_view(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {+ let t = Tokens::get(ui.ctx());+ let idle = self.busy_op.is_none();+ let Some(ed) = &mut self.conflict else { return };+ let (ours_name, theirs_name) = ed.side_names();+ let total = ed.choices.len();+ let left = ed.unresolved();++ // Header.+ egui::Frame::new()+ .fill(t.chrome)+ .inner_margin(egui::Margin::symmetric(10, 6))+ .stroke(Stroke::new(1.0, t.separator))+ .show(ui, |ui| {+ ui.horizontal(|ui| {+ icons::inline(ui, "git-merge", 16.0, t.danger);+ ui.label(RichText::new(&ed.path).font(theme::medium(13.0)));+ super::widgets::chip(+ ui,+ &format!(+ "{} of {total} resolved",+ total.saturating_sub(left).min(total)+ ),+ if left == 0 { t.success } else { t.warning },+ );+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if icons::small_button(ui, "x", "Close (Esc)").clicked() {+ acts.push(Action::CloseDiff);+ }+ if super::widgets::primary_button(+ ui,+ "Save and mark resolved",+ idle && left == 0,+ 0.0,+ )+ .on_disabled_hover_text("Resolve every conflict first")+ .clicked()+ {+ acts.push(Action::SaveConflict);+ }+ // Whole file: git's own sides (swapped during a rebase).+ let (mine, theirs) = if ed.rebase {+ ("--theirs", "--ours")+ } else {+ ("--ours", "--theirs")+ };+ for (label, side, tip) in [+ ("Use theirs", theirs, "Take their version of the whole file"),+ ("Use mine", mine, "Keep your version of the whole file"),+ ] {+ if ui+ .add_enabled(idle, egui::Button::new(label))+ .on_hover_text(tip)+ .clicked()+ {+ acts.push(Action::Ops {+ label: format!("{label} for {}", ed.path),+ ops: ops(&[+ &["checkout", side, "--", &ed.path],+ &["add", "--", &ed.path],+ ]),+ refresh: Refresh::Status,+ });+ }+ }+ });+ });+ });++ // Bottom: the result.+ egui::Panel::bottom("conflict_result")+ .resizable(true)+ .default_size(ui.available_height() * 0.42)+ .size_range(90.0..=f32::INFINITY)+ .frame(+ egui::Frame::new()+ .fill(t.card)+ .inner_margin(egui::Margin::symmetric(10, 8)),+ )+ .show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.label(+ RichText::new("RESULT")+ .font(theme::semibold(10.5))+ .color(t.text_faint),+ );+ if ed.manual {+ ui.label(RichText::new("edited by hand").color(t.warning).small());+ if ui.small_button("Back to choices").clicked() {+ ed.manual = false;+ ed.result = render(+ &ed.segments,+ &ed.choices,+ (&ed.ours_label, &ed.theirs_label),+ );+ }+ }+ });+ egui::ScrollArea::both()+ .id_salt("conflict_result_scroll")+ .auto_shrink(false)+ .show(ui, |ui| {+ let edit = ui.add(+ egui::TextEdit::multiline(&mut ed.result)+ .font(theme::mono(12.0))+ .code_editor()+ .desired_width(f32::INFINITY)+ .desired_rows(8),+ );+ if edit.changed() {+ ed.manual = true;+ }+ });+ });++ // Top: each conflict, ours | theirs, with the choice buttons.+ egui::ScrollArea::vertical()+ .id_salt("conflict_list")+ .auto_shrink(false)+ .show(ui, |ui| {+ let mut k = 0;+ let mut pick = None;+ for seg in &ed.segments {+ let Segment::Conflict { ours, theirs, .. } = seg else {+ continue;+ };+ let chosen = ed.choices.get(k).copied().flatten();+ egui::Frame::new()+ .inner_margin(egui::Margin::symmetric(10, 8))+ .show(ui, |ui| {+ ui.horizontal(|ui| {+ ui.label(+ RichText::new(format!("Conflict {} of {total}", k + 1))+ .font(theme::semibold(12.0)),+ );+ ui.add_space(8.0);+ for (choice, label) in [+ (Choice::Ours, ours_name.as_str()),+ (Choice::Theirs, theirs_name.as_str()),+ (Choice::OursThenTheirs, "Both (ours first)"),+ (Choice::TheirsThenOurs, "Both (theirs first)"),+ ] {+ let on = chosen == Some(choice);+ let text = if on {+ RichText::new(label).color(t.accent_text)+ } else {+ RichText::new(label)+ };+ let b = egui::Button::new(text).fill(if on {+ t.accent+ } else {+ t.field+ });+ if ui.add(b).clicked() {+ pick = Some((k, choice));+ }+ }+ });+ ui.add_space(4.0);+ ui.columns(2, |cols| {+ for (col, (name, text, side)) in cols.iter_mut().zip([+ (ours_name.as_str(), ours, Choice::Ours),+ (theirs_name.as_str(), theirs, Choice::Theirs),+ ]) {+ let picked = matches!(+ (chosen, side),+ (Some(Choice::Ours), Choice::Ours)+ | (Some(Choice::Theirs), Choice::Theirs)+ ) || matches!(+ chosen,+ Some(Choice::OursThenTheirs | Choice::TheirsThenOurs)+ );+ let border = if picked { t.accent } else { t.field_border };+ egui::Frame::new()+ .fill(t.field)+ .stroke(Stroke::new(1.0, border))+ .corner_radius(t.radius)+ .inner_margin(egui::Margin::same(8))+ .show(col, |ui| {+ ui.set_width(ui.available_width());+ ui.label(+ RichText::new(name).color(t.text_faint).small(),+ );+ let body = if text.is_empty() {+ "(nothing)"+ } else {+ text.trim_end_matches(['\r', '\n'])+ };+ // No wrapping: wrapped code loses its indentation.+ egui::ScrollArea::horizontal()+ .id_salt(("conflict-side", name, body.len()))+ .show(ui, |ui| {+ ui.add(+ egui::Label::new(+ RichText::new(body)+ .font(theme::mono(12.0)),+ )+ .extend(),+ );+ });+ });+ }+ });+ });+ let (sep, _) =+ ui.allocate_exact_size(vec2(ui.available_width(), 1.0), Sense::hover());+ ui.painter().rect_filled(sep, 0.0, t.separator);+ k += 1;+ }+ if let Some((k, choice)) = pick {+ ed.choose(k, choice);+ }+ });+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const FILE: &str = "a\n<<<<<<< HEAD\nours 1\n=======\ntheirs 1\n>>>>>>> feature\nb\n<<<<<<< HEAD\nx\n||||||| base\nbase\n=======\ny\n>>>>>>> feature\nc\n";++ #[test]+ fn parses_conflicts_and_labels() {+ let (segs, ours, theirs) = parse(FILE);+ assert_eq!((ours.as_str(), theirs.as_str()), ("HEAD", "feature"));+ let conflicts: Vec<_> = segs+ .iter()+ .filter(|s| matches!(s, Segment::Conflict { .. }))+ .collect();+ assert_eq!(conflicts.len(), 2);+ assert_eq!(+ conflicts[1],+ &Segment::Conflict {+ ours: "x\n".into(),+ base: Some("base\n".into()),+ theirs: "y\n".into()+ }+ );+ }++ #[test]+ fn renders_choices_and_keeps_undecided_markers() {+ let (segs, o, t) = parse(FILE);+ let out = render(+ &segs,+ &[Some(Choice::Theirs), Some(Choice::OursThenTheirs)],+ (&o, &t),+ );+ assert_eq!(out, "a\ntheirs 1\nb\nx\ny\nc\n");+ let partial = render(&segs, &[Some(Choice::Ours), None], (&o, &t));+ assert!(partial.starts_with("a\nours 1\nb\n<<<<<<< HEAD\nx\n"));+ assert!(partial.contains("||||||| base\nbase\n=======\ny\n>>>>>>> feature\n"));+ }++ #[test]+ fn keeps_crlf_line_endings() {+ let crlf = "a\r\n<<<<<<< HEAD\r\nmine\r\n=======\r\nyours\r\n>>>>>>> b\r\nz\r\n";+ let (segs, o, t) = parse(crlf);+ assert_eq!(+ render(&segs, &[Some(Choice::Ours)], (&o, &t)),+ "a\r\nmine\r\nz\r\n"+ );+ }+}diff --git a/src/repo/detail.rs b/src/repo/detail.rsindex 3d29248..78cbbae 100644--- a/src/repo/detail.rs+++ b/src/repo/detail.rs@@ -25,7 +25,43 @@ impl RepoTab {fn commit_panel(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {let t = Tokens::get(ui.ctx());- widgets::panel_header(ui, "Commit", |_| {});+ let idle = self.busy_op.is_none();+ let stash = self.stash_view.and_then(|i| self.stashes.get(i)).cloned();+ let title = if stash.is_some() { "Stash" } else { "Commit" };+ widgets::panel_header(ui, title, |ui| {+ if let Some(stash) = &stash {+ let more = icons::small_button(ui, "chevron-down", "Apply, pop or drop");+ egui::Popup::menu(&more).show(|ui| {+ super::sidebar::stash_menu_items(ui, acts, &stash.name, idle);+ });+ }+ });+ if let Some(stash) = &stash {+ egui::Frame::new()+ .fill(t.accent.gamma_multiply(0.10))+ .inner_margin(egui::Margin::symmetric(14, 8))+ .show(ui, |ui| {+ ui.set_width(ui.available_width());+ ui.horizontal(|ui| {+ icons::inline(ui, "archive", 15.0, t.accent);+ ui.label(RichText::new(&stash.name).font(theme::medium(12.5)));+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ for (label, args) in [+ ("Pop", ["stash", "pop", "--index", stash.name.as_str()]),+ ("Apply", ["stash", "apply", "--index", stash.name.as_str()]),+ ] {+ if ui.add_enabled(idle, egui::Button::new(label)).clicked() {+ acts.push(Action::Ops {+ label: format!("{label} {}", stash.name),+ ops: super::ops(&[&args]),+ refresh: super::Refresh::All,+ });+ }+ }+ });+ });+ });+ }if let Some(err) = &self.detail_error {ui.add_space(10.0);ui.horizontal(|ui| {@@ -71,7 +107,7 @@ impl RepoTab {ui.horizontal(|ui| {let (rect, _) =ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());- widgets::avatar(ui.painter(), rect.center(), 16.0, &detail.author);+ widgets::avatar(ui, rect.center(), 16.0, &detail.author, &detail.email);ui.vertical(|ui| {ui.spacing_mut().item_spacing.y = 2.0;ui.label(RichText::new(&detail.author).font(theme::medium(12.5)))@@ -198,6 +234,7 @@ impl RepoTab {selected,RowExtra::Stats(f.added, f.removed),);+ widgets::file_menu(&r.row, &f.path, acts);if r.row.clicked() {acts.push(Action::OpenDiff(key));}@@ -263,7 +300,7 @@ impl RepoTab {if !self.work.conflicted.is_empty() {list_header(ui, "CONFLICTED", self.work.conflicted.len(), None);for f in &self.work.conflicted {- match self.work_row(ui, f, &[("check", "Mark resolved (stage)")]) {+ match self.work_row(ui, acts, f, &[("check", "Mark resolved (stage)")]) {RowClick::Open => acts.push(Action::OpenDiff(DiffKey::Work(f.clone()))),RowClick::Button(_) => acts.push(stage_action("Mark resolved",@@ -284,8 +321,12 @@ impl RepoTab {acts.push(stage_action("Stage all", vec![vec!["add", "-A"]]));}for f in unstaged {- match self.work_row(ui, f, &[("undo-2", "Discard changes…"), ("plus", "Stage")])- {+ match self.work_row(+ ui,+ acts,+ f,+ &[("undo-2", "Discard changes…"), ("plus", "Stage")],+ ) {RowClick::Open => acts.push(Action::OpenDiff(DiffKey::Work(f.clone()))),RowClick::Button(0) => acts.push(Action::Dialog(discard_dialog(f))),RowClick::Button(_) => {@@ -313,7 +354,7 @@ impl RepoTab {acts.push(stage_action("Unstage all", vec![all]));}for f in staged {- match self.work_row(ui, f, &[("minus", "Unstage")]) {+ match self.work_row(ui, acts, f, &[("minus", "Unstage")]) {RowClick::Open => acts.push(Action::OpenDiff(DiffKey::Work(f.clone()))),RowClick::Button(_) => {acts.push(stage_action("Unstage", vec![unstage_args(&head, &f.path)]))@@ -328,7 +369,13 @@ impl RepoTab {}/// One working-tree file with hover buttons (hidden while an operation runs).- fn work_row(&self, ui: &mut Ui, f: &StatusFile, buttons: &[(&str, &str)]) -> RowClick {+ fn work_row(+ &self,+ ui: &mut Ui,+ acts: &mut Vec<Action>,+ f: &StatusFile,+ buttons: &[(&str, &str)],+ ) -> RowClick {let key = DiffKey::Work(f.clone());let selected = self.open_key() == Some(&key);let buttons = if self.busy_op.is_none() { buttons } else { &[] };@@ -340,6 +387,9 @@ impl RepoTab {selected,RowExtra::Buttons(buttons),);+ if f.code != 'D' {+ widgets::file_menu(&r.row, &f.path, acts);+ }match r.button {Some(i) => RowClick::Button(i),None if r.row.clicked() => RowClick::Open,@@ -350,11 +400,53 @@ impl RepoTab {fn commit_box(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {let t = Tokens::get(ui.ctx());let idle = self.busy_op.is_none();- ui.label(- RichText::new("COMMIT")+ let rebasing = self.work.in_progress == Some(crate::git::InProgress::Rebase);+ ui.horizontal(|ui| {+ ui.label(+ RichText::new(if rebasing {+ "CONTINUE REBASE"+ } else {+ "COMMIT"+ }).font(theme::semibold(10.5)).color(t.text_faint),- );+ );+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ let amend = ui+ .add_enabled(+ !rebasing && !self.refs.head.is_empty(),+ egui::Checkbox::new(&mut self.amend, "Amend last commit"),+ )+ .on_hover_text(+ "Rewrite the last commit with the staged changes and this message",+ );+ if amend.changed() && self.amend && self.commit_summary.trim().is_empty() {+ // Start from the message being amended.+ if let Ok(msg) = crate::git::head_message(&self.path) {+ let (summary, body) = msg.split_once('\n').unwrap_or((msg.as_str(), ""));+ self.commit_summary = summary.trim().to_owned();+ self.commit_body = body.trim().to_owned();+ }+ }+ });+ });+ if self.amend {+ let pushed = self+ .refs+ .current+ .as_ref()+ .and_then(|c| self.refs.local.iter().find(|b| &b.name == c))+ .is_some_and(|b| !b.upstream.is_empty() && b.ahead_behind().0 == 0);+ if pushed {+ ui.label(+ RichText::new(+ "This commit is already pushed: amending rewrites shared history.",+ )+ .color(t.warning)+ .small(),+ );+ }+ }ui.add_space(2.0);let summary = ui.add(egui::TextEdit::singleline(&mut self.commit_summary)@@ -379,7 +471,11 @@ impl RepoTab {}ui.add_space(4.0);let staged = self.work.staged.len();- let label = if staged > 0 {+ let label = if rebasing {+ "Continue rebase".to_owned()+ } else if self.amend {+ "Amend last commit".to_owned()+ } else if staged > 0 {format!("Commit {staged} file{}", if staged == 1 { "" } else { "s" })} else {"Stage all and commit".to_owned()@@ -393,6 +489,38 @@ impl RepoTab {acts.push(Action::Commit);}resp.on_hover_text("Ctrl+Enter");++ // Who the commit will be by, and the saved identities to switch to.+ ui.add_space(4.0);+ ui.horizontal(|ui| {+ let id = &self.identity;+ let who = if id.name.is_empty() {+ "No identity set (git config user.name)".to_owned()+ } else {+ format!(+ "as {} <{}>{}",+ id.name,+ id.email,+ if id.local { "" } else { " · global" }+ )+ };+ ui.add(egui::Label::new(RichText::new(who).color(t.text_faint).small()).truncate());+ let profiles = crate::settings::Settings::get(ui.ctx()).profiles;+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ let b = icons::small_button(ui, "user-round", "Commit as…");+ egui::Popup::menu(&b).show(|ui| {+ if profiles.is_empty() {+ ui.label(RichText::new("Add identities in Settings").color(t.text_faint));+ }+ for p in &profiles {+ let label = format!("{} — {} <{}>", p.label, p.name, p.email);+ if ui.add_enabled(idle, egui::Button::new(label)).clicked() {+ acts.push(Action::SetIdentity(p.name.clone(), p.email.clone()));+ }+ }+ });+ });+ });}}diff --git a/src/repo/dialogs.rs b/src/repo/dialogs.rsindex 5b6c585..a50af86 100644--- a/src/repo/dialogs.rs+++ b/src/repo/dialogs.rs@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};use egui::{Key, RichText};use super::widgets;-use super::{Action, Refresh, RepoTab};+use super::{Action, Refresh, RepoTab, Undo};use crate::theme::{self, Tokens};pub enum Dialog {@@ -41,6 +41,42 @@ pub enum Dialog {alternative: Option<(String, Vec<Vec<String>>)>,use_alternative: bool,refresh: Refresh,+ undo: Undo,+ },+ Stash {+ message: String,+ focus: bool,+ },+ Tag {+ at: String,+ at_label: String,+ name: String,+ message: String,+ /// Remote to push the tag to, if any.+ remote: Option<String>,+ push: bool,+ focus: bool,+ },+ RenameBranch {+ old: String,+ new: String,+ focus: bool,+ },+ /// Add a remote (`original` = None) or edit one's name and URL.+ Remote {+ original: Option<(String, String)>,+ name: String,+ url: String,+ focus: bool,+ },+ CreatePr {+ noun: String,+ branch: String,+ base: String,+ title: String,+ body: String,+ draft: bool,+ focus: bool,},}@@ -70,6 +106,64 @@ impl Dialog {alternative,use_alternative: false,refresh: Refresh::All,+ undo: Undo::None,+ }+ }++ /// Makes a confirmed operation undoable.+ pub fn undo(mut self, how: Undo) -> Self {+ if let Dialog::Confirm { undo, .. } = &mut self {+ *undo = how;+ }+ self+ }++ pub fn stash() -> Self {+ Dialog::Stash {+ message: String::new(),+ focus: true,+ }+ }++ pub fn tag(at: &str, at_label: &str, remote: Option<String>) -> Self {+ Dialog::Tag {+ at: at.to_owned(),+ at_label: at_label.to_owned(),+ name: String::new(),+ message: String::new(),+ remote,+ push: false,+ focus: true,+ }+ }++ pub fn rename_branch(old: &str) -> Self {+ Dialog::RenameBranch {+ old: old.to_owned(),+ new: old.to_owned(),+ focus: true,+ }+ }++ pub fn remote(original: Option<(String, String)>) -> Self {+ let (name, url) = original.clone().unwrap_or_default();+ Dialog::Remote {+ original,+ name,+ url,+ focus: true,+ }+ }++ pub fn create_pr(noun: &str, branch: &str, base: &str, title: &str) -> Self {+ Dialog::CreatePr {+ noun: noun.to_owned(),+ branch: branch.to_owned(),+ base: base.to_owned(),+ title: title.to_owned(),+ body: String::new(),+ draft: false,+ focus: true,}}@@ -154,6 +248,12 @@ impl RepoTab {let local = &self.refs.local;let worktrees = &self.worktrees;+ // What a new branch's undo checks out again.+ let previous = self+ .refs+ .current+ .clone()+ .unwrap_or_else(|| self.refs.head.clone());let response = modal.show(ctx, |ui| {ui.set_width(380.0);let enter = ui.input(|i| i.key_pressed(Key::Enter));@@ -197,10 +297,16 @@ impl RepoTab {} else {vec!["branch".into(), name.clone(), at.clone()]};- outcome = Outcome::Done(Action::Ops {+ let mut undo = Vec::new();+ if *checkout && !previous.is_empty() {+ undo.push(vec!["checkout".to_owned(), previous.clone()]);+ }+ undo.push(vec!["branch".to_owned(), "-D".to_owned(), name.clone()]);+ outcome = Outcome::Done(Action::UndoableOps {label: format!("Create branch {name}"),- ops: vec![args],+ ops: vec![args.clone()],refresh: Refresh::All,+ undo: Undo::Custom { undo, redo: vec![args] },});}if ui@@ -367,6 +473,139 @@ impl RepoTab {}outcome}+ Dialog::Stash { message, focus } => {+ title(ui, "Stash changes", "Puts every change, untracked files included, aside and cleans the working tree.", &t);+ let edit = field(ui, message, "Message (optional)", focus);+ let _ = edit;+ buttons(ui, "Stash", true, enter, || Action::StashPush(message.trim().to_owned()))+ }+ Dialog::Tag { at, at_label, name, message, remote, push, focus } => {+ title(ui, "Create tag", &format!("At {at_label}"), &t);+ field(ui, name, "v1.2.0", focus);+ if name.contains(' ') {+ *name = name.replace(' ', "-");+ }+ ui.add_space(4.0);+ ui.add(+ egui::TextEdit::multiline(message)+ .hint_text("Message (optional: makes an annotated tag)")+ .desired_width(f32::INFINITY)+ .desired_rows(2)+ .margin(egui::Margin::symmetric(8, 6)),+ );+ if let Some(remote) = remote {+ ui.add_space(4.0);+ ui.checkbox(push, format!("Push it to {remote}"));+ }+ ui.add_space(8.0);+ let valid = !name.trim().is_empty();+ buttons(ui, "Create", valid, enter && !message.contains('\n'), || {+ let name = name.trim().to_owned();+ let mut create = vec!["tag".to_owned()];+ if !message.trim().is_empty() {+ create.extend(["-a".to_owned(), "-m".to_owned(), message.trim().to_owned()]);+ }+ create.extend([name.clone(), at.clone()]);+ let mut steps = vec![create.clone()];+ if *push && let Some(remote) = remote {+ steps.push(vec!["push".to_owned(), remote.clone(), format!("refs/tags/{name}")]);+ }+ Action::UndoableOps {+ label: format!("Create tag {name}"),+ ops: steps,+ refresh: Refresh::All,+ undo: Undo::Custom {+ undo: vec![vec!["tag".to_owned(), "-d".to_owned(), name.clone()]],+ redo: vec![create],+ },+ }+ })+ }+ Dialog::RenameBranch { old, new, focus } => {+ title(ui, "Rename branch", &format!("Renames {old} on this computer; its remote copy keeps its name."), &t);+ field(ui, new, "new-name", focus);+ if new.contains(' ') {+ *new = new.replace(' ', "-");+ }+ ui.add_space(8.0);+ let valid = !new.trim().is_empty() && new.trim() != old.as_str();+ buttons(ui, "Rename", valid, enter, || {+ let new = new.trim().to_owned();+ Action::UndoableOps {+ label: format!("Rename {old} to {new}"),+ ops: vec![vec!["branch".into(), "-m".into(), old.clone(), new.clone()]],+ refresh: Refresh::All,+ undo: Undo::Custom {+ undo: vec![vec!["branch".into(), "-m".into(), new.clone(), old.clone()]],+ redo: vec![vec!["branch".into(), "-m".into(), old.clone(), new]],+ },+ }+ })+ }+ Dialog::Remote { original, name, url, focus } => {+ let heading = if original.is_some() { "Edit remote" } else { "Add remote" };+ title(ui, heading, "A name (like origin or upstream) and the repository's URL.", &t);+ field(ui, name, "origin", focus);+ ui.add_space(4.0);+ ui.add(+ egui::TextEdit::singleline(url)+ .hint_text("https://github.com/user/repo.git")+ .desired_width(f32::INFINITY)+ .margin(egui::Margin::symmetric(8, 6)),+ );+ ui.add_space(8.0);+ let valid = !name.trim().is_empty() && !url.trim().is_empty();+ buttons(ui, if original.is_some() { "Save" } else { "Add" }, valid, enter, || {+ let (name, url) = (name.trim().to_owned(), url.trim().to_owned());+ let steps = match original {+ None => vec![+ vec!["remote".into(), "add".into(), name.clone(), url],+ vec!["fetch".into(), name.clone()],+ ],+ Some((old_name, old_url)) => {+ let mut steps = Vec::new();+ if *old_name != name {+ steps.push(vec!["remote".into(), "rename".into(), old_name.clone(), name.clone()]);+ }+ if *old_url != url {+ steps.push(vec!["remote".into(), "set-url".into(), name.clone(), url]);+ }+ steps+ }+ };+ Action::Ops {+ label: format!("Remote {name}"),+ ops: steps,+ refresh: Refresh::All,+ }+ })+ }+ Dialog::CreatePr { noun, branch, base, title: pr_title, body, draft, focus } => {+ title(ui, &format!("Create {noun}"), &format!("{branch} → {base} (the branch is pushed first)"), &t);+ field(ui, pr_title, "Title", focus);+ ui.add_space(4.0);+ ui.add(+ egui::TextEdit::multiline(body)+ .hint_text("Description")+ .desired_width(f32::INFINITY)+ .desired_rows(5)+ .margin(egui::Margin::symmetric(8, 6)),+ );+ ui.horizontal(|ui| {+ ui.label(RichText::new("Into").color(t.text_dim));+ ui.add(egui::TextEdit::singleline(base).desired_width(160.0));+ ui.checkbox(draft, "Draft");+ });+ ui.add_space(8.0);+ let valid = !pr_title.trim().is_empty() && !base.trim().is_empty();+ buttons(ui, "Create", valid, false, || Action::CreatePr {+ branch: branch.clone(),+ base: base.trim().to_owned(),+ title: pr_title.trim().to_owned(),+ body: body.trim().to_owned(),+ draft: *draft,+ })+ }Dialog::Confirm {title,body,@@ -375,6 +614,7 @@ impl RepoTab {alternative,use_alternative,refresh,+ undo,} => {ui.label(RichText::new(title.as_str()).font(theme::semibold(15.0)));ui.add_space(6.0);@@ -398,10 +638,18 @@ impl RepoTab {(Some((_, alt)), true) => alt.clone(),_ => ops.clone(),};- outcome = Outcome::Done(Action::Ops {- label: title.clone(),- ops: steps,- refresh: *refresh,+ outcome = Outcome::Done(match undo {+ Undo::None => Action::Ops {+ label: title.clone(),+ ops: steps,+ refresh: *refresh,+ },+ undo => Action::UndoableOps {+ label: title.clone(),+ ops: steps,+ refresh: *refresh,+ undo: undo.clone(),+ },});}if ui@@ -428,3 +676,48 @@ impl RepoTab {}}}++/// A dialog's heading and one line under it.+fn title(ui: &mut egui::Ui, heading: &str, sub: &str, t: &Tokens) {+ ui.label(RichText::new(heading).font(theme::semibold(15.0)));+ ui.label(RichText::new(sub).color(t.text_dim));+ ui.add_space(10.0);+}++/// A single-line field that takes the keyboard when the dialog opens.+fn field(ui: &mut egui::Ui, text: &mut String, hint: &str, focus: &mut bool) -> egui::Response {+ let edit = ui.add(+ egui::TextEdit::singleline(text)+ .hint_text(hint)+ .desired_width(f32::INFINITY)+ .margin(egui::Margin::symmetric(8, 6)),+ );+ if *focus {+ edit.request_focus();+ *focus = false;+ }+ edit+}++/// The primary button (also Enter, when `enter`) and Cancel.+fn buttons(+ ui: &mut egui::Ui,+ label: &str,+ valid: bool,+ enter: bool,+ done: impl FnOnce() -> Action,+) -> Outcome {+ let mut outcome = Outcome::Open;+ ui.horizontal(|ui| {+ if widgets::primary_button(ui, label, valid, 90.0).clicked() || (enter && valid) {+ outcome = Outcome::Done(done());+ }+ if ui+ .add(egui::Button::new("Cancel").min_size(egui::vec2(80.0, 30.0)))+ .clicked()+ {+ outcome = Outcome::Cancel;+ }+ });+ outcome+}diff --git a/src/repo/diff.rs b/src/repo/diff.rsindex 0fd67ac..4b405b8 100644--- a/src/repo/diff.rs+++ b/src/repo/diff.rs@@ -1,10 +1,18 @@-//! Central pane while a file is open: its diff with old/new line numbers.+//! Central pane while a file is open: its diff, unified or side by side, with syntax colours,+//! the changed part of each line marked, and images shown before / after.-use egui::{Align2, Rect, Sense, Stroke, Ui, pos2, vec2};+use std::path::Path;+use std::sync::Arc;+use egui::{+ Align2, Color32, Rect, Sense, Stroke, Ui, load::Bytes, pos2, text::LayoutJob, text::TextFormat,+ vec2,+};++use super::highlight::{self, Spans};use super::widgets;use super::{Action, DiffKey, Refresh, RepoTab, ops};-use crate::git::Area;+use crate::git::{self, Area};use crate::icons;use crate::theme::{self, Tokens};@@ -12,6 +20,7 @@ const LINE_H: f32 = 19.0;const NUM_W: f32 = 46.0;/// Very long diffs are cut here; the UI stays responsive and git is one click away.const MAX_LINES: usize = 50_000;+const IMAGE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "bmp", "webp", "ico"];#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Kind {@@ -31,6 +40,174 @@ pub struct DiffLine {pub text: String,}+/// Everything the view needs, prepared on a background thread.+pub struct DiffData {+ pub lines: Vec<DiffLine>,+ /// Syntax colours per line (`None` when the file type isn't known).+ pub spans: Vec<Option<Spans>>,+ /// The changed part of a removed / added line paired with its counterpart (char range).+ pub changed: Vec<Option<(usize, usize)>>,+ /// Side-by-side rows: (left line, right line).+ pub split: Vec<(Option<usize>, Option<usize>)>,+ pub image: Option<ImagePair>,+}++pub struct ImagePair {+ pub old: Option<Arc<[u8]>>,+ pub new: Option<Arc<[u8]>>,+ /// Makes the image URIs unique to this diff.+ pub id: String,+}++/// Reads and prepares the diff for `key`.+pub fn load(repo: &Path, key: &DiffKey, ignore_ws: bool, dark: bool) -> Result<DiffData, String> {+ let (text, path) = match key {+ DiffKey::Commit { hash, path } => {+ (git::file_diff(repo, hash, path, ignore_ws)?, path.clone())+ }+ DiffKey::Work(file) => (git::work_diff(repo, file, ignore_ws)?, file.path.clone()),+ };+ let lines = parse(&text);+ let image = if is_image(&path) {+ Some(load_images(repo, key, &path))+ } else {+ None+ };++ // Colour the old and the new side each as one stream, so multi-line constructs work.+ let mut spans = vec![None; lines.len()];+ let old_side: Vec<usize> = (0..lines.len())+ .filter(|&i| matches!(lines[i].kind, Kind::Context | Kind::Del))+ .collect();+ let new_side: Vec<usize> = (0..lines.len())+ .filter(|&i| matches!(lines[i].kind, Kind::Context | Kind::Add))+ .collect();+ if let Some(old) = highlight::highlight(+ &path,+ old_side.iter().map(|&i| lines[i].text.as_str()),+ dark,+ ) {+ for (k, &i) in old_side.iter().enumerate() {+ if lines[i].kind == Kind::Del {+ spans[i] = old.get(k).cloned();+ }+ }+ }+ if let Some(new) = highlight::highlight(+ &path,+ new_side.iter().map(|&i| lines[i].text.as_str()),+ dark,+ ) {+ for (k, &i) in new_side.iter().enumerate() {+ spans[i] = new.get(k).cloned();+ }+ }++ let (changed, split) = pair_lines(&lines);+ Ok(DiffData {+ lines,+ spans,+ changed,+ split,+ image,+ })+}++fn is_image(path: &str) -> bool {+ Path::new(path)+ .extension()+ .map(|e| e.to_string_lossy().to_lowercase())+ .is_some_and(|e| IMAGE_EXTS.contains(&e.as_str()))+}++fn load_images(repo: &Path, key: &DiffKey, path: &str) -> ImagePair {+ let get = |rev: Option<&str>| {+ git::file_at(repo, rev, path)+ .ok()+ .map(|b| Arc::from(b.into_boxed_slice()))+ };+ let (old, new, id) = match key {+ DiffKey::Commit { hash, .. } => (+ get(Some(&format!("{hash}^"))),+ get(Some(hash)),+ hash.clone(),+ ),+ DiffKey::Work(file) => match file.area {+ Area::Staged => (get(Some("HEAD")), get(Some("")), "staged".to_owned()),+ Area::Unstaged => (get(Some("")), get(None), "unstaged".to_owned()),+ Area::Untracked => (None, get(None), "untracked".to_owned()),+ Area::Conflicted => (None, get(None), "conflicted".to_owned()),+ },+ };+ ImagePair {+ old,+ new,+ id: format!("{id}-{}", git::now()),+ }+}++type Split = Vec<(Option<usize>, Option<usize>)>;++/// Pairs each run of removed lines with the added lines after it: marks what changed inside+/// each pair, and lays out side-by-side rows.+fn pair_lines(lines: &[DiffLine]) -> (Vec<Option<(usize, usize)>>, Split) {+ let mut changed = vec![None; lines.len()];+ let mut split = Vec::new();+ let mut i = 0;+ while i < lines.len() {+ match lines[i].kind {+ Kind::Del | Kind::Add => {+ let dels_start = i;+ while i < lines.len() && lines[i].kind == Kind::Del {+ i += 1;+ }+ let adds_start = i;+ while i < lines.len() && lines[i].kind == Kind::Add {+ i += 1;+ }+ let dels: Vec<usize> = (dels_start..adds_start).collect();+ let adds: Vec<usize> = (adds_start..i).collect();+ for k in 0..dels.len().max(adds.len()) {+ let (d, a) = (dels.get(k).copied(), adds.get(k).copied());+ if let (Some(d), Some(a)) = (d, a)+ && let Some((dr, ar)) = changed_ranges(&lines[d].text, &lines[a].text)+ {+ changed[d] = Some(dr);+ changed[a] = Some(ar);+ }+ split.push((d, a));+ }+ }+ _ => {+ split.push((Some(i), Some(i)));+ i += 1;+ }+ }+ }+ (changed, split)+}++/// The differing middle of two lines (common prefix and suffix removed), as char ranges;+/// `None` when the lines have little in common (a rewrite, not an edit).+fn changed_ranges(old: &str, new: &str) -> Option<((usize, usize), (usize, usize))> {+ let a: Vec<char> = old.chars().collect();+ let b: Vec<char> = new.chars().collect();+ let prefix = a.iter().zip(&b).take_while(|(x, y)| x == y).count();+ let max_suffix = a.len().min(b.len()) - prefix;+ let suffix = a+ .iter()+ .rev()+ .zip(b.iter().rev())+ .take(max_suffix)+ .take_while(|(x, y)| x == y)+ .count();+ let common = prefix + suffix;+ if common * 3 < a.len().max(b.len()) {+ return None;+ }+ Some(((prefix, a.len() - suffix), (prefix, b.len() - suffix)))+}+/// Parses a unified (or combined, for conflicts) diff of one file.pub fn parse(text: &str) -> Vec<DiffLine> {let mut out = Vec::new();@@ -146,7 +323,7 @@ impl RepoTab {let Some(view) = &self.diff else { return };let idle = self.busy_op.is_none();- // Header: file, where it comes from, actions, close.+ // Header: file, where it comes from, options, actions, close.let (path, origin) = match &view.key {DiffKey::Commit { hash, path } => (path.clone(),@@ -162,6 +339,7 @@ impl RepoTab {},),};+ let (split, ignore_ws) = (self.diff_split, self.diff_ignore_ws);egui::Frame::new().fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 6))@@ -169,7 +347,11 @@ impl RepoTab {.show(ui, |ui| {ui.horizontal(|ui| {icons::inline(ui, "file-diff", 16.0, t.icon);- ui.label(egui::RichText::new(&path).font(theme::medium(13.0)));+ let title = ui.add(+ egui::Label::new(egui::RichText::new(&path).font(theme::medium(13.0)))+ .sense(Sense::click()),+ );+ widgets::file_menu(&title, &path, acts);widgets::chip(ui, &origin, t.text_dim);ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {if icons::small_button(ui, "x", "Close (Esc)").clicked() {@@ -193,11 +375,50 @@ impl RepoTab {});}}+ ui.add_space(8.0);+ let ws = icons::small_button(+ ui,+ "pilcrow",+ if ignore_ws {+ "Show whitespace changes"+ } else {+ "Ignore whitespace changes"+ },+ );+ if ignore_ws {+ widgets::active_underline(ui, ws.rect, t.accent);+ }+ if ws.clicked() {+ acts.push(Action::SetDiffOptions {+ split,+ ignore_ws: !ignore_ws,+ });+ }+ let s = icons::small_button(ui, "columns-2", "Side by side");+ if split {+ widgets::active_underline(ui, s.rect, t.accent);+ }+ if s.clicked() {+ acts.push(Action::SetDiffOptions {+ split: true,+ ignore_ws,+ });+ }+ let u = icons::small_button(ui, "rows-2", "Unified");+ if !split {+ widgets::active_underline(ui, u.rect, t.accent);+ }+ if u.clicked() {+ acts.push(Action::SetDiffOptions {+ split: false,+ ignore_ws,+ });+ }});});});- let lines = match &view.lines {+ let data = match &view.data {None => {ui.centered_and_justified(|ui| ui.spinner());return;@@ -210,11 +431,20 @@ impl RepoTab {});return;}- Some(Ok(lines)) => lines,+ Some(Ok(data)) => data,};- if lines.is_empty() {+ if let Some(images) = &data.image {+ image_view(ui, images);+ return;+ }+ if data.lines.is_empty() {ui.centered_and_justified(|ui| {- ui.label(egui::RichText::new("No textual changes").color(t.text_dim));+ let msg = if ignore_ws {+ "No changes besides whitespace"+ } else {+ "No textual changes"+ };+ ui.label(egui::RichText::new(msg).color(t.text_dim));});return;}@@ -225,78 +455,263 @@ impl RepoTab {.layout_no_wrap("M".to_owned(), font.clone(), t.text).size().x;- let longest = lines+ let longest = data+ .lines.iter().map(|l| l.text.chars().count()).max()- .unwrap_or(0);- let content_w = NUM_W * 2.0 + 24.0 + longest as f32 * char_w + 24.0;+ .unwrap_or(0) as f32;ui.spacing_mut().item_spacing.y = 0.0;+ let rows = if split {+ data.split.len()+ } else {+ data.lines.len()+ };egui::ScrollArea::both()- .id_salt(("diff_scroll", &path))+ .id_salt(("diff_scroll", &path, split)).auto_shrink(false)- .show_rows(ui, LINE_H, lines.len(), |ui, range| {- let width = content_w.max(ui.available_width());- for line in lines.get(range).unwrap_or_default() {- let (rect, _) = ui.allocate_exact_size(vec2(width, LINE_H), Sense::hover());- let p = ui.painter();- let (bg, fg) = match line.kind {- Kind::Add => (Some(t.diff_add_bg), t.text),- Kind::Del => (Some(t.diff_del_bg), t.text),- Kind::Hunk => (Some(t.accent.gamma_multiply(0.12)), t.accent),- Kind::Meta => (None, t.text_faint),- Kind::Context => (None, t.text_dim),- };- if let Some(bg) = bg {- p.rect_filled(rect, 0.0, bg);- }- let y = rect.center().y;- let gutter = Rect::from_min_size(rect.min, vec2(NUM_W * 2.0, LINE_H));- p.rect_filled(gutter, 0.0, t.card.gamma_multiply(0.6));- for (n, x) in [- (line.old, rect.left() + NUM_W - 8.0),- (line.new, rect.left() + NUM_W * 2.0 - 8.0),- ] {- if let Some(n) = n {- p.text(- pos2(x, y),- Align2::RIGHT_CENTER,- n.to_string(),- theme::mono(11.0),- t.text_faint,- );+ .show_rows(ui, LINE_H, rows, |ui, range| {+ if split {+ let half =+ (NUM_W + 24.0 + longest * char_w + 16.0).max(ui.available_width() / 2.0);+ for row in range {+ let Some(&(l, r)) = data.split.get(row) else {+ continue;+ };+ let (rect, _) =+ ui.allocate_exact_size(vec2(half * 2.0, LINE_H), Sense::hover());+ let left = Rect::from_min_size(rect.min, vec2(half, LINE_H));+ let right = Rect::from_min_size(+ pos2(rect.left() + half, rect.top()),+ vec2(half, LINE_H),+ );+ // Hunk headers and notes span both halves.+ if l == r+ && let Some(i) = l+ && matches!(+ data.lines.get(i).map(|x| x.kind),+ Some(Kind::Hunk | Kind::Meta)+ )+ {+ paint_line(ui, rect, data, i, Side::Both, &font, &t);+ continue;+ }+ match l {+ Some(i) => paint_line(ui, left, data, i, Side::Old, &font, &t),+ None => filler(ui, left, &t),}+ match r {+ Some(i) => paint_line(ui, right, data, i, Side::New, &font, &t),+ None => filler(ui, right, &t),+ }+ ui.painter().line_segment(+ [right.left_top(), right.left_bottom()],+ Stroke::new(1.0, t.separator),+ );+ }+ } else {+ let width =+ (NUM_W * 2.0 + 24.0 + longest * char_w + 24.0).max(ui.available_width());+ for i in range {+ let (rect, _) = ui.allocate_exact_size(vec2(width, LINE_H), Sense::hover());+ paint_line(ui, rect, data, i, Side::Unified, &font, &t);}- let marker = match line.kind {- Kind::Add => "+",- Kind::Del => "−",- _ => "",- };- let mark_color = if line.kind == Kind::Add {- t.success- } else {- t.danger- };- p.text(- pos2(rect.left() + NUM_W * 2.0 + 8.0, y),- Align2::LEFT_CENTER,- marker,- font.clone(),- mark_color,- );- p.text(- pos2(rect.left() + NUM_W * 2.0 + 24.0, y),- Align2::LEFT_CENTER,- &line.text,- font.clone(),- fg,- );}});}}+#[derive(Clone, Copy, PartialEq, Eq)]+enum Side {+ Unified,+ Old,+ New,+ /// A hunk header across both halves of the split view.+ Both,+}++fn filler(ui: &Ui, rect: Rect, t: &Tokens) {+ ui.painter()+ .rect_filled(rect, 0.0, t.card.gamma_multiply(0.35));+}++fn paint_line(+ ui: &Ui,+ rect: Rect,+ data: &DiffData,+ i: usize,+ side: Side,+ font: &egui::FontId,+ t: &Tokens,+) {+ let Some(line) = data.lines.get(i) else {+ return;+ };+ let p = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect()));+ let (bg, fg) = match line.kind {+ Kind::Add => (Some(t.diff_add_bg), t.text),+ Kind::Del => (Some(t.diff_del_bg), t.text),+ Kind::Hunk => (Some(t.accent.gamma_multiply(0.12)), t.accent),+ Kind::Meta => (None, t.text_faint),+ Kind::Context => (None, t.text_dim),+ };+ if let Some(bg) = bg {+ p.rect_filled(rect, 0.0, bg);+ }+ let y = rect.center().y;+ let numbers: &[(Option<u32>, f32)] = match side {+ Side::Unified => &[(line.old, NUM_W - 8.0), (line.new, NUM_W * 2.0 - 8.0)],+ Side::Old => &[(line.old, NUM_W - 8.0)],+ Side::New => &[(line.new, NUM_W - 8.0)],+ Side::Both => &[],+ };+ let gutter = match side {+ Side::Unified => NUM_W * 2.0,+ Side::Both => 0.0,+ _ => NUM_W,+ };+ if gutter > 0.0 {+ p.rect_filled(+ Rect::from_min_size(rect.min, vec2(gutter, LINE_H)),+ 0.0,+ t.card.gamma_multiply(0.6),+ );+ }+ for &(n, x) in numbers {+ if let Some(n) = n {+ p.text(+ pos2(rect.left() + x, y),+ Align2::RIGHT_CENTER,+ n.to_string(),+ theme::mono(11.0),+ t.text_faint,+ );+ }+ }+ let marker = match line.kind {+ Kind::Add => "+",+ Kind::Del => "−",+ _ => "",+ };+ let mark_color = if line.kind == Kind::Add {+ t.success+ } else {+ t.danger+ };+ p.text(+ pos2(rect.left() + gutter + 8.0, y),+ Align2::LEFT_CENTER,+ marker,+ font.clone(),+ mark_color,+ );++ // Text: syntax colours when known, the changed part on a stronger background.+ let strong = match line.kind {+ Kind::Add => t.success.gamma_multiply(0.35),+ Kind::Del => t.danger.gamma_multiply(0.35),+ _ => Color32::TRANSPARENT,+ };+ let changed = data.changed.get(i).copied().flatten();+ let spans: Vec<(Color32, &str)> = match (line.kind, data.spans.get(i).and_then(|s| s.as_ref()))+ {+ (Kind::Add | Kind::Del | Kind::Context, Some(spans)) => {+ spans.iter().map(|(c, s)| (*c, s.as_str())).collect()+ }+ _ => vec![(fg, line.text.as_str())],+ };+ let job = line_job(&spans, changed, font, strong);+ let galley = ui.fonts_mut(|f| f.layout_job(job));+ let x = rect.left() + gutter + 24.0;+ p.galley(pos2(x, y - galley.size().y / 2.0), galley, fg);+}++/// A layout job for `spans`, with the chars in `changed` on `strong`.+fn line_job(+ spans: &[(Color32, &str)],+ changed: Option<(usize, usize)>,+ font: &egui::FontId,+ strong: Color32,+) -> LayoutJob {+ let mut job = LayoutJob::default();+ let mut pos = 0usize;+ for (color, text) in spans {+ let n = text.chars().count();+ let (start, end) = (pos, pos + n);+ // Split the span at the changed range's edges.+ let cuts: Vec<usize> = match changed {+ Some((a, b)) => vec![start, a.clamp(start, end), b.clamp(start, end), end],+ None => vec![start, end],+ };+ for w in cuts.windows(2) {+ let (from, to) = (w[0], w[1]);+ if to <= from {+ continue;+ }+ let piece: String = text.chars().skip(from - start).take(to - from).collect();+ let inside = changed.is_some_and(|(a, b)| from >= a && to <= b);+ job.append(+ &piece,+ 0.0,+ TextFormat {+ font_id: font.clone(),+ color: *color,+ background: if inside { strong } else { Color32::TRANSPARENT },+ ..Default::default()+ },+ );+ }+ pos = end;+ }+ job+}++fn image_view(ui: &mut Ui, images: &ImagePair) {+ let t = Tokens::get(ui.ctx());+ ui.add_space(12.0);+ ui.columns(2, |cols| {+ for (col, (label, bytes, side)) in cols.iter_mut().zip([+ ("Before", &images.old, "old"),+ ("After", &images.new, "new"),+ ]) {+ col.vertical_centered(|ui| {+ ui.label(+ egui::RichText::new(label)+ .font(theme::semibold(12.0))+ .color(t.text_dim),+ );+ ui.add_space(6.0);+ match bytes {+ Some(bytes) => {+ let uri = format!("bytes://diff/{}/{side}.png", images.id);+ let max = vec2(ui.available_width() - 16.0, ui.available_height() - 40.0);+ ui.add(+ egui::Image::from_bytes(uri, Bytes::Shared(bytes.clone()))+ .max_size(max)+ .fit_to_original_size(1.0)+ .bg_fill(t.field),+ );+ ui.label(+ egui::RichText::new(format!("{} KB", bytes.len().div_ceil(1024)))+ .color(t.text_faint)+ .small(),+ );+ }+ None => {+ let note = if side == "old" {+ "(new file)"+ } else {+ "(deleted)"+ };+ ui.label(egui::RichText::new(note).color(t.text_faint));+ }+ }+ });+ }+ });+}+/// `git restore --staged`, or `git rm --cached` before the first commit (no HEAD to restore from).pub(super) fn unstage_args<'a>(head: &str, path: &'a str) -> Vec<&'a str> {if head.is_empty() {@@ -345,4 +760,48 @@ mod tests {let lines = parse("diff --git a/x b/x\nBinary files a/x and b/x differ\n");assert_eq!(lines, vec![meta("Binary files a/x and b/x differ")]);}++ #[test]+ fn side_by_side_pairs_and_inline_changes() {+ let lines = parse("@@ -1,3 +1,3 @@\n a\n-let x = 1;\n-gone\n+let x = 2;\n b\n");+ let (changed, split) = pair_lines(&lines);+ // hunk, a, (del x1, add x2), (del gone, —), b+ assert_eq!(+ split,+ vec![+ (Some(0), Some(0)),+ (Some(1), Some(1)),+ (Some(2), Some(4)),+ (Some(3), None),+ (Some(5), Some(5))+ ]+ );+ assert_eq!(changed[2], Some((8, 9)));+ assert_eq!(changed[4], Some((8, 9)));+ assert_eq!(changed[3], None);+ }++ #[test]+ fn rewrites_are_not_marked_inline() {+ assert_eq!(changed_ranges("completely", "different words"), None);+ assert_eq!(changed_ranges("abc", "abXc"), Some(((2, 2), (2, 3))));+ }++ #[test]+ fn changed_part_gets_its_own_section() {+ let font = theme::mono(12.0);+ let job = line_job(+ &[(Color32::RED, "let x = 2;")],+ Some((8, 9)),+ &font,+ Color32::GREEN,+ );+ let pieces: Vec<&str> = job+ .sections+ .iter()+ .map(|s| &job.text[s.byte_range.start.0..s.byte_range.end.0])+ .collect();+ assert_eq!(pieces, vec!["let x = ", "2", ";"]);+ assert_eq!(job.sections[1].format.background, Color32::GREEN);+ }}diff --git a/src/repo/graph_view.rs b/src/repo/graph_view.rsindex 04e4fd0..731b9d7 100644--- a/src/repo/graph_view.rs+++ b/src/repo/graph_view.rs@@ -1,4 +1,5 @@-//! Central pane: the commit graph of every branch.+//! Central pane: the commit graph of every branch, with branch pills on the left, search and+//! older history loaded as you scroll.use egui::{Align2, Color32, CornerRadius, FontId, Key, Pos2, Rect, Response, Sense, Stroke, Ui,@@ -6,9 +7,10 @@ use egui::{};use super::widgets;-use super::{Action, Dialog, Refresh, RepoTab, WIP_HASH, ops};-use crate::git::Refs;+use super::{Action, Dialog, Refresh, RepoTab, Undo, WIP_HASH, ops};+use crate::git::{self, Refs};use crate::icons;+use crate::settings::Settings;use crate::theme::{self, Tokens};const ROW_H: f32 = 28.0;@@ -16,13 +18,32 @@ const LANE_W: f32 = 16.0;const MAX_LANES_SHOWN: usize = 24;const AUTHOR_W: f32 = 150.0;const DATE_W: f32 = 118.0;-/// Width of the branch/tag column left of the graph.-const REFS_W: f32 = 210.0;+const HASH_W: f32 = 70.0;const AVATAR_D: f32 = 20.0;+/// Column widths for this frame (from the settings).+#[derive(Clone, Copy)]+struct Cols {+ refs: f32,+ graph: f32,+ hash: f32,+ author: f32,+ date: f32,+}++impl Cols {+ /// Width of everything right of the description.+ fn trailing(&self) -> f32 {+ self.hash + self.author + self.date+ }+}+impl RepoTab {pub(super) fn graph_view(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {let t = Tokens::get(ui.ctx());+ if self.search.open {+ self.search_bar(ui, acts);+ }if let Some(err) = &self.load_error {ui.add_space(12.0);ui.horizontal(|ui| {@@ -63,8 +84,15 @@ impl RepoTab {}}+ let settings = Settings::get(ui.ctx());let lanes = self.graph.width.clamp(1, MAX_LANES_SHOWN);- let graph_w = (lanes as f32 * LANE_W + 12.0).max(60.0);+ let cols = Cols {+ refs: settings.refs_width.clamp(150.0, 600.0),+ graph: (lanes as f32 * LANE_W + 12.0).max(60.0),+ hash: if settings.show_hash { HASH_W } else { 0.0 },+ author: if settings.show_author { AUTHOR_W } else { 0.0 },+ date: if settings.show_date { DATE_W } else { 0.0 },+ };// Column headers.let (header, _) = ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::hover());@@ -77,13 +105,22 @@ impl RepoTab {);let y = header.center().y;let font = theme::semibold(10.5);- for (x, label) in [+ let right = header.right();+ let mut labels = vec![(header.left() + 10.0, "BRANCH / TAG"),- (header.left() + REFS_W + 10.0, "GRAPH"),- (header.left() + REFS_W + graph_w + 6.0, "DESCRIPTION"),- (header.right() - DATE_W - AUTHOR_W, "AUTHOR"),- (header.right() - DATE_W, "DATE"),- ] {+ (header.left() + cols.refs + 10.0, "GRAPH"),+ (header.left() + cols.refs + cols.graph + 6.0, "DESCRIPTION"),+ ];+ if cols.hash > 0.0 {+ labels.push((right - cols.trailing(), "COMMIT"));+ }+ if cols.author > 0.0 {+ labels.push((right - cols.author - cols.date, "AUTHOR"));+ }+ if cols.date > 0.0 {+ labels.push((right - cols.date, "DATE"));+ }+ for (x, label) in labels {p.text(pos2(x, y),Align2::LEFT_CENTER,@@ -111,9 +148,27 @@ impl RepoTab {// `show_rows` sizes rows as ROW_H + item spacing, so the spacing must be zero here.ui.spacing_mut().item_spacing.y = 0.0;let idle = self.busy_op.is_none();- let out = scroll.show_rows(ui, ROW_H, self.commits.len(), |ui, range| {+ let now = git::now();+ let total = self.commits.len() + usize::from(self.has_more);+ let out = scroll.show_rows(ui, ROW_H, total, |ui, range| {+ // Near the end: fetch the next page of history.+ if range.end + 40 >= self.commits.len() && self.has_more && !self.loading_more {+ acts.push(Action::LoadMore);+ }for i in range {- let resp = self.commit_row(ui, i, graph_w, lanes);+ if i >= self.commits.len() {+ let (rect, _) =+ ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::hover());+ ui.painter().text(+ rect.center(),+ Align2::CENTER_CENTER,+ "Loading older commits…",+ FontId::proportional(12.0),+ t.text_faint,+ );+ continue;+ }+ let resp = self.commit_row(ui, i, cols, lanes, now);if resp.clicked() {acts.push(Action::Select(i));}@@ -132,64 +187,183 @@ impl RepoTab {refresh: Refresh::Status,});}+ if ui+ .add_enabled(idle, egui::Button::new("Stash changes…"))+ .clicked()+ {+ acts.push(Action::Dialog(Dialog::stash()));+ }});continue;}- let hash = commit.hash.clone();- let short = hash.get(..8).unwrap_or(&hash).to_owned();- let summary = commit.summary.clone();- let is_head = hash == self.refs.head;- resp.context_menu(|ui| {- if ui.button("Create branch here…").clicked() {- acts.push(Action::Dialog(Dialog::create_branch(&hash, &short)));- }- if ui- .add_enabled(- idle && !is_head,- egui::Button::new("Check out this commit (detached)"),- )- .clicked()- {- acts.push(Action::Checkout(hash.clone()));+ self.commit_menu(&resp, i, idle, acts);+ }+ });+ ui.data_mut(|d| d.insert_temp(offset_id, out.state.offset.y));+ }++ /// Right-click menu of a commit row.+ fn commit_menu(&self, resp: &Response, i: usize, idle: bool, acts: &mut Vec<Action>) {+ let Some(commit) = self.commits.get(i) else {+ return;+ };+ let hash = commit.hash.clone();+ let short = hash.get(..8).unwrap_or(&hash).to_owned();+ let summary = commit.summary.clone();+ let is_head = hash == self.refs.head;+ // Local branches pointing here get their own submenu.+ let here: Vec<&git::Branch> = self+ .refs+ .local+ .iter()+ .filter(|b| b.target == hash)+ .collect();+ resp.context_menu(|ui| {+ for b in &here {+ ui.menu_button(format!("Branch {}", b.name), |ui| {+ self.branch_menu_items(ui, acts, b, idle);+ });+ }+ if !here.is_empty() {+ ui.separator();+ }+ if ui.button("Create branch here…").clicked() {+ acts.push(Action::Dialog(Dialog::create_branch(&hash, &short)));+ }+ if ui.button("Create tag here…").clicked() {+ acts.push(Action::Dialog(Dialog::tag(&hash, &short, self.default_remote())));+ }+ if ui+ .add_enabled(+ idle && !is_head,+ egui::Button::new("Check out this commit (detached)"),+ )+ .clicked()+ {+ acts.push(Action::Checkout(hash.clone()));+ }+ ui.separator();+ if ui+ .add_enabled(+ idle && !is_head,+ egui::Button::new("Cherry-pick onto current branch"),+ )+ .clicked()+ {+ acts.push(Action::UndoableOps {+ label: format!("Cherry-pick {short}"),+ ops: ops(&[&["cherry-pick", &hash]]),+ refresh: Refresh::All,+ undo: Undo::HeadMove { mode: "--keep" },+ });+ }+ if ui+ .add_enabled(idle, egui::Button::new("Revert commit"))+ .clicked()+ {+ acts.push(Action::UndoableOps {+ label: format!("Revert {short}"),+ ops: ops(&[&["revert", "--no-edit", &hash]]),+ refresh: Refresh::All,+ undo: Undo::HeadMove { mode: "--keep" },+ });+ }+ let target = self.refs.current.clone().unwrap_or_else(|| "HEAD".to_owned());+ ui.add_enabled_ui(idle && !is_head, |ui| {+ ui.menu_button(format!("Reset {target} to here"), |ui| {+ for (mode, undo_mode, label, explain) in [+ ("--soft", "--soft", "Soft", "Keeps every change, staged."),+ ("--mixed", "--mixed", "Mixed", "Keeps every change, unstaged."),+ ("--hard", "--keep", "Hard", "Throws away uncommitted changes and the commits after this one. Uncommitted work can't be recovered."),+ ] {+ if ui.button(format!("{label} — {}", explain.split('.').next().unwrap_or(explain))).clicked() {+ acts.push(Action::Dialog(+ Dialog::confirm(+ &format!("{label} reset"),+ format!("Move {target} to {short} ({summary})? {explain}"),+ &format!("Reset {}", label.to_lowercase()),+ ops(&[&["reset", mode, &hash]]),+ None,+ )+ .undo(Undo::HeadMove { mode: undo_mode }),+ ));+ }}- ui.separator();- if ui- .add_enabled(- idle && !is_head,- egui::Button::new("Cherry-pick onto current branch"),- )- .clicked()- {- acts.push(Action::Ops {- label: format!("Cherry-pick {short}"),- ops: ops(&[&["cherry-pick", &hash]]),- refresh: Refresh::All,- });+ });+ });+ ui.separator();+ if ui.button("Copy commit hash").clicked() {+ ui.ctx().copy_text(hash.clone());+ }+ if ui.button("Copy message").clicked() {+ ui.ctx().copy_text(summary.clone());+ }+ });+ }++ fn search_bar(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {+ let t = Tokens::get(ui.ctx());+ egui::Frame::new()+ .fill(t.chrome)+ .inner_margin(egui::Margin::symmetric(10, 6))+ .stroke(Stroke::new(1.0, t.separator))+ .show(ui, |ui| {+ ui.horizontal(|ui| {+ icons::inline(ui, "search", 15.0, t.text_faint);+ let edit = ui.add(+ egui::TextEdit::singleline(&mut self.search.query)+ .hint_text("Search messages, authors and hashes in all history")+ .desired_width(ui.available_width() - 190.0)+ .margin(egui::Margin::symmetric(8, 4)),+ );+ if std::mem::take(&mut self.search.focus) {+ edit.request_focus();}- if ui- .add_enabled(idle, egui::Button::new("Revert commit"))- .clicked()- {- acts.push(Action::Ops {- label: format!("Revert {short}"),- ops: ops(&[&["revert", "--no-edit", &hash]]),- refresh: Refresh::All,- });+ if edit.changed() {+ self.search.edited = Some(std::time::Instant::now());}- ui.separator();- if ui.button("Copy commit hash").clicked() {- ui.ctx().copy_text(hash.clone());+ let (enter, shift, esc) = ui.input(|i| {+ (+ i.key_pressed(Key::Enter),+ i.modifiers.shift,+ i.key_pressed(Key::Escape),+ )+ });+ if edit.lost_focus() && enter {+ acts.push(Action::SearchStep(if shift { -1 } else { 1 }));+ edit.request_focus();}- if ui.button("Copy message").clicked() {- ui.ctx().copy_text(summary.clone());+ if edit.has_focus() && esc {+ acts.push(Action::ToggleSearch);}+ let n = self.search.results.len();+ let summary = if self.search.running {+ "searching…".to_owned()+ } else if self.search.searched.is_empty() {+ String::new()+ } else if n == 0 {+ "no results".to_owned()+ } else {+ format!("{} of {n}", self.search.current + 1)+ };+ ui.label(egui::RichText::new(summary).color(t.text_dim).small());+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if icons::small_button(ui, "x", "Close (Esc)").clicked() {+ acts.push(Action::ToggleSearch);+ }+ if icons::small_button(ui, "chevron-down", "Next (Enter)").clicked() {+ acts.push(Action::SearchStep(1));+ }+ if icons::small_button(ui, "chevron-up", "Previous (Shift+Enter)").clicked()+ {+ acts.push(Action::SearchStep(-1));+ }+ });});- }- });- ui.data_mut(|d| d.insert_temp(offset_id, out.state.offset.y));+ });}- fn commit_row(&self, ui: &mut Ui, i: usize, graph_w: f32, lanes: usize) -> Response {+ fn commit_row(&self, ui: &mut Ui, i: usize, cols: Cols, lanes: usize, now: i64) -> Response {let t = Tokens::get(ui.ctx());let (rect, resp) =ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());@@ -198,15 +372,25 @@ impl RepoTab {};let painter = ui.painter_at(rect);let is_wip = commit.hash == WIP_HASH;+ let is_match = self.search.matches.contains(&commit.hash);if self.selected == Some(i) {painter.rect_filled(rect, 0.0, t.row_selected);} else if resp.hovered() {painter.rect_filled(rect, 0.0, t.hover);+ } else if is_match {+ painter.rect_filled(rect, 0.0, t.warning.gamma_multiply(0.10));+ }+ if is_match {+ painter.rect_filled(+ Rect::from_min_size(rect.min, vec2(3.0, ROW_H)),+ 0.0,+ t.warning,+ );}let (top, mid, bottom) = (rect.top(), rect.center().y, rect.bottom());- let gx = rect.left() + REFS_W;+ let gx = rect.left() + cols.refs;let x = |lane: usize| gx + 6.0 + lane as f32 * LANE_W + LANE_W / 2.0;let row_color = self.graph@@ -216,22 +400,29 @@ impl RepoTab {.unwrap_or(t.text_faint);let node_x = self.graph.rows.get(i).map(|r| x(r.col));- // Branch and tag pills, left of the graph, joined to the commit's dot.+ // Branch and tag pills, left of the graph, joined to the commit's dot, with the tip's+ // author and how long ago it was made.let badges = badges(&commit.refs, &self.refs);let mut resp = resp;if let (Some(first), Some(node_x)) = (badges.first(), node_x) {let refs_clip = Rect::from_min_max(rect.min, pos2(gx - 4.0, bottom));let rp = painter.with_clip_rect(refs_clip);+ let when = git::relative_time(commit.time, now);+ let when_galley = rp.layout_no_wrap(when, theme::medium(10.5), t.text_dim);+ let when_w = when_galley.size().x + 12.0;let more = badges.len() - 1;let more_w = if more > 0 { 28.0 } else { 0.0 };- let max_w = REFS_W - 10.0 - AVATAR_D - 8.0 - more_w - 8.0;+ let max_w = cols.refs - 10.0 - AVATAR_D - 8.0 - more_w - when_w - 14.0;+ let has_pr =+ first.kind == BadgeKind::Branch && self.prs.iter().any(|p| p.branch == first.label);let pill = ref_pill(ui,&rp,pos2(rect.left() + 8.0, mid),first,row_color,- max_w,+ max_w.max(40.0),+ has_pr,);let mut end = pill.right();if more > 0 {@@ -250,21 +441,37 @@ impl RepoTab {);end = r.right();}- // Avatar of whoever made the tip commit.let avatar = pos2(end + 5.0 + AVATAR_D / 2.0, mid);+ let when_rect = Rect::from_min_size(+ pos2(avatar.x + AVATAR_D / 2.0 + 5.0, mid - 9.0),+ vec2(when_w, 18.0),+ );// Connector to the dot, drawn first so the lanes cross over it.painter.line_segment(- [pos2(avatar.x, mid), pos2(node_x, mid)],+ [pos2(when_rect.right(), mid), pos2(node_x, mid)],Stroke::new(1.5, row_color.gamma_multiply(0.8)),);- widgets::avatar(&rp, avatar, AVATAR_D / 2.0, &commit.author);+ widgets::avatar(ui, avatar, AVATAR_D / 2.0, &commit.author, &commit.email);+ rp.rect_filled(when_rect, CornerRadius::same(9), t.field);+ rp.rect_stroke(+ when_rect,+ CornerRadius::same(9),+ Stroke::new(1.0, row_color.gamma_multiply(0.6)),+ egui::StrokeKind::Inside,+ );+ rp.galley(+ pos2(when_rect.left() + 6.0, mid - when_galley.size().y / 2.0),+ when_galley,+ t.text_dim,+ );let refs_cell = Rect::from_min_max(rect.min, pos2(gx, bottom));if ui.rect_contains_pointer(refs_cell) {let lines: Vec<String> = badges.iter().map(Badge::describe).collect();resp = resp.on_hover_text(format!(- "{}\nTip commit by {}",+ "{}\nTip commit by {} · {}",lines.join("\n"),- commit.author+ commit.author,+ commit.date));}}@@ -272,7 +479,7 @@ impl RepoTab {// Graph.if let Some(row) = self.graph.rows.get(i) {let gp = painter.with_clip_rect(- rect.intersect(Rect::from_min_size(pos2(gx, top), vec2(graph_w, ROW_H))),+ rect.intersect(Rect::from_min_size(pos2(gx, top), vec2(cols.graph, ROW_H))),);let node = pos2(x(row.col), mid);let width = 2.0;@@ -311,8 +518,8 @@ impl RepoTab {}}- let mut x = gx + graph_w + 6.0;- let text_right = rect.right() - DATE_W - AUTHOR_W - 10.0;+ let mut x = gx + cols.graph + 6.0;+ let text_right = rect.right() - cols.trailing() - 10.0;if is_wip {let font = theme::medium(12.5);@@ -341,6 +548,11 @@ impl RepoTab {return resp;}+ let font = if is_match {+ theme::medium(12.5)+ } else {+ FontId::proportional(12.5)+ };painter.with_clip_rect(Rect::from_min_max(pos2(x, rect.top()),@@ -350,29 +562,42 @@ impl RepoTab {pos2(x + 2.0, mid),Align2::LEFT_CENTER,&commit.summary,- FontId::proportional(12.5),+ font,t.text,);let small = FontId::proportional(11.5);- let author_clip = Rect::from_min_max(- pos2(rect.right() - DATE_W - AUTHOR_W, rect.top()),- pos2(rect.right() - DATE_W - 8.0, rect.bottom()),- );- painter.with_clip_rect(author_clip).text(- pos2(author_clip.left(), mid),- Align2::LEFT_CENTER,- &commit.author,- small.clone(),- t.text_dim,- );- painter.text(- pos2(rect.right() - DATE_W, mid),- Align2::LEFT_CENTER,- &commit.date,- theme::mono(11.0),- t.text_faint,- );+ if cols.hash > 0.0 {+ painter.text(+ pos2(rect.right() - cols.trailing(), mid),+ Align2::LEFT_CENTER,+ commit.hash.get(..7).unwrap_or(&commit.hash),+ theme::mono(11.0),+ t.text_faint,+ );+ }+ if cols.author > 0.0 {+ let author_clip = Rect::from_min_max(+ pos2(rect.right() - cols.author - cols.date, rect.top()),+ pos2(rect.right() - cols.date - 8.0, rect.bottom()),+ );+ painter.with_clip_rect(author_clip).text(+ pos2(author_clip.left(), mid),+ Align2::LEFT_CENTER,+ &commit.author,+ small.clone(),+ t.text_dim,+ );+ }+ if cols.date > 0.0 {+ painter.text(+ pos2(rect.right() - cols.date, mid),+ Align2::LEFT_CENTER,+ &commit.date,+ theme::mono(11.0),+ t.text_faint,+ );+ }resp}}@@ -505,6 +730,7 @@ fn ref_pill(badge: &Badge,lane: Color32,max_w: f32,+ pr: bool,) -> Rect {const ICON: f32 = 15.0;let t = Tokens::get(ui.ctx());@@ -532,6 +758,9 @@ fn ref_pill(if !badge.remotes.is_empty() {trail.push("cloud");}+ if pr {+ trail.push("git-pull-request");+ }}}let font = if badge.head {diff --git a/src/repo/highlight.rs b/src/repo/highlight.rsnew file mode 100644index 0000000..3ae88c0--- /dev/null+++ b/src/repo/highlight.rs@@ -0,0 +1,89 @@+//! Syntax colouring for diffs (syntect, pure-Rust regex engine), chosen by file extension.++use std::sync::OnceLock;++use egui::Color32;+use syntect::easy::HighlightLines;+use syntect::highlighting::ThemeSet;+use syntect::parsing::SyntaxSet;++/// Coloured pieces of one line.+pub type Spans = Vec<(Color32, String)>;++/// Bigger diffs stay uncoloured: highlighting is the slow part of opening them.+const MAX_LINES: usize = 8000;++fn syntaxes() -> &'static SyntaxSet {+ static SET: OnceLock<SyntaxSet> = OnceLock::new();+ SET.get_or_init(SyntaxSet::load_defaults_newlines)+}++fn themes() -> &'static ThemeSet {+ static SET: OnceLock<ThemeSet> = OnceLock::new();+ SET.get_or_init(ThemeSet::load_defaults)+}++/// Colours `lines` (one file's text, in order) for `path`; `None` for plain text, unknown+/// types or very long inputs.+pub fn highlight<'a>(+ path: &str,+ lines: impl ExactSizeIterator<Item = &'a str>,+ dark: bool,+) -> Option<Vec<Spans>> {+ if lines.len() > MAX_LINES {+ return None;+ }+ let ss = syntaxes();+ let ext = std::path::Path::new(path)+ .extension()+ .map(|e| e.to_string_lossy().to_lowercase())?;+ let syntax = ss.find_syntax_by_extension(&ext)?;+ if syntax.name == "Plain Text" {+ return None;+ }+ let theme_name = if dark {+ "base16-ocean.dark"+ } else {+ "InspiredGitHub"+ };+ let theme = themes().themes.get(theme_name)?;+ let mut h = HighlightLines::new(syntax, theme);+ let mut out = Vec::new();+ for line in lines {+ let with_nl = format!("{line}\n");+ let ranges = h.highlight_line(&with_nl, ss).ok()?;+ out.push(+ ranges+ .into_iter()+ .map(|(style, text)| {+ let c = style.foreground;+ (+ Color32::from_rgb(c.r, c.g, c.b),+ text.trim_end_matches('\n').to_owned(),+ )+ })+ .filter(|(_, t)| !t.is_empty())+ .collect(),+ );+ }+ Some(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn colours_rust_and_skips_plain_text() {+ let lines = ["fn main() {", " let x = 1;", "}"];+ let spans = highlight("a.rs", lines.iter().copied(), true);+ let spans = spans.unwrap_or_default();+ assert_eq!(spans.len(), 3);+ let text: String = spans[1].iter().map(|(_, t)| t.as_str()).collect();+ assert_eq!(text, " let x = 1;");+ // More than one colour on a line of code.+ assert!(spans[0].len() > 1);+ assert!(highlight("notes.txt", lines.iter().copied(), true).is_none());+ assert!(highlight("Makefile-without-ext", lines.iter().copied(), true).is_none());+ }+}diff --git a/src/repo/mod.rs b/src/repo/mod.rsindex a1fd755..50d51f5 100644--- a/src/repo/mod.rs+++ b/src/repo/mod.rs@@ -1,41 +1,58 @@//! One open repository: its state, background git work and the view//! (branches on the left, commit graph or diff in the middle, commit detail / changes on the right).+mod conflict;mod detail;mod dialogs;mod diff;mod graph_view;+mod highlight;mod sidebar;pub(crate) mod widgets;-use std::collections::HashMap;-use std::path::PathBuf;+use std::collections::{HashMap, HashSet};+use std::path::{Path, PathBuf};use std::sync::mpsc::{Receiver, Sender, channel};+use std::time::{Duration, Instant};use egui::{Key, Ui};-use crate::git::{self, Commit, CommitDetail, InProgress, Refs, StatusFile, WorkStatus, Worktree};+use crate::forge::{self, Forge, PullRequest};+use crate::git::{+ self, Commit, CommitDetail, Identity, InProgress, Refs, Remote, Stash, StatusFile, WorkStatus,+ Worktree,+};use crate::graph::{self, Graph};use crate::icons;-use crate::terminal::Terminal;+use crate::settings::Settings;+use crate::terminal::{ShellSpec, Terminal};use crate::theme::Tokens;pub use dialogs::Dialog;-use diff::DiffLine;+pub use widgets::primary_button;/// Hash of the pseudo-commit that stands for uncommitted changes at the top of the graph.pub(crate) const WIP_HASH: &str = "\u{0}wip";+/// History deeper than this isn't loaded by scrolling or searching.+const MAX_HISTORY: usize = 100_000;+/// An operation that takes longer than this gets a notification when it ends.+const LONG_OP: Duration = Duration::from_secs(4);/// Results coming back from background git calls.enum Msg {Loaded(Result<Box<Loaded>, String>),+ More(Result<Vec<Commit>, String>),Status(Result<WorkStatus, String>),Detail(String, Result<CommitDetail, String>),- Diff(DiffKey, Result<String, String>),+ Diff(DiffKey, Result<diff::DiffData, String>),+ Search(String, Result<Vec<String>, String>),+ Prs(Result<Vec<PullRequest>, String>),OpDone {label: String,result: Result<String, String>,refresh: Refresh,+ kind: OpKind,+ quiet: bool,},}@@ -44,6 +61,11 @@ struct Loaded {history: Vec<Commit>,work: WorkStatus,worktrees: Vec<Worktree>,+ stashes: Vec<Stash>,+ remotes: Vec<Remote>,+ identity: Identity,+ /// How many commits were asked for (more exist when that many came back).+ requested: usize,}/// What to re-read after an operation.@@ -54,6 +76,36 @@ pub(crate) enum Refresh {All,}+/// How an operation can be undone.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) enum Undo {+ None,+ /// The operation moved HEAD (commit, merge, reset…): undo moves it back with+ /// `git reset <mode>`, redo forward again. `--soft` keeps the changes staged.+ HeadMove {+ mode: &'static str,+ },+ /// Explicit commands each way (branch create/delete/rename, checkout, tags, stash).+ Custom {+ undo: Vec<Vec<String>>,+ redo: Vec<Vec<String>>,+ },+}++#[derive(Clone, Debug)]+pub(crate) struct UndoEntry {+ label: String,+ undo: Vec<Vec<String>>,+ redo: Vec<Vec<String>>,+}++#[derive(Clone, Debug)]+enum OpKind {+ Normal(Undo, String),+ Undo(UndoEntry),+ Redo(UndoEntry),+}+/// Which diff the central area shows.#[derive(Clone, Debug, PartialEq, Eq)]pub(crate) enum DiffKey {@@ -63,13 +115,28 @@ pub(crate) enum DiffKey {pub(crate) struct DiffView {key: DiffKey,- lines: Option<Result<Vec<DiffLine>, String>>,+ data: Option<Result<diff::DiffData, String>>,+}++#[derive(Default)]+struct Search {+ open: bool,+ focus: bool,+ query: String,+ /// The query the results are for.+ searched: String,+ results: Vec<String>,+ matches: HashSet<String>,+ current: usize,+ running: bool,+ edited: Option<Instant>,}/// Everything the views ask for; applied after drawing so views only borrow the state.pub(crate) enum Action {Select(usize),SelectHash(String),+ SelectStash(usize),OpenDiff(DiffKey),CloseDiff,Ops {@@ -77,18 +144,52 @@ pub(crate) enum Action {ops: Vec<Vec<String>>,refresh: Refresh,},+ UndoableOps {+ label: String,+ ops: Vec<Vec<String>>,+ refresh: Refresh,+ undo: Undo,+ },Checkout(String),CheckoutRemote(String),Dialog(Dialog),Commit,Fetch,- /// Open a folder (a worktree) in its own tab.- OpenTab(PathBuf),- ToggleTerminal,- RestartTerminal,Pull,Push,Reload,+ LoadMore,+ Undo,+ Redo,+ StashPush(String),+ /// Open a folder (a worktree) in its own tab.+ OpenTab(PathBuf),+ ToggleTerminal,+ NewTerminal {+ shell: Option<ShellSpec>,+ cwd: Option<PathBuf>,+ },+ CloseTerminal(usize),+ SelectTerminal(usize),+ ToggleSearch,+ SearchStep(i32),+ CreatePr {+ branch: String,+ base: String,+ title: String,+ body: String,+ draft: bool,+ },+ OpenUrl(String),+ /// Open a path (relative to the repository) with the system's default app.+ OpenPath(PathBuf),+ OpenInEditor(PathBuf),+ SetIdentity(String, String),+ SetDiffOptions {+ split: bool,+ ignore_ws: bool,+ },+ SaveConflict,}pub struct RepoTab {@@ -102,33 +203,72 @@ pub struct RepoTab {refs: Refs,/// Commits as git listed them.history: Vec<Commit>,+ has_more: bool,+ loading_more: bool,work: WorkStatus,/// Rows of the graph: the WIP pseudo-commit (when the tree is dirty) followed by `history`.commits: Vec<Commit>,graph: Graph,index: HashMap<String, usize>,+ worktrees: Vec<Worktree>,+ stashes: Vec<Stash>,+ remotes: Vec<Remote>,+ identity: Identity,+ forge: Option<Forge>,+ prs: Vec<PullRequest>,+ pr_error: Option<String>,+ prs_loaded: Option<Instant>,selected: Option<usize>,+ /// A stash shown in the detail pane instead of a graph row.+ stash_view: Option<usize>,scroll_to: Option<usize>,+ /// The commit the detail pane is about (a graph row or a stash).+ detail_hash: Option<String>,detail: Option<CommitDetail>,detail_error: Option<String>,diff: Option<DiffView>,+ diff_split: bool,+ diff_ignore_ws: bool,+ conflict: Option<conflict::ConflictEditor>,commit_summary: String,commit_body: String,+ amend: bool,dialog: Option<Dialog>,+ search: Search,+ /// A commit to select once enough history is loaded (search results, links).+ pending_goto: Option<String>,++ undo_stack: Vec<UndoEntry>,+ redo_stack: Vec<UndoEntry>,busy_op: Option<String>,+ op_started: Option<Instant>,status: Option<(String, bool)>,branch_filter: String,/// Jump to the changes row on the next rebuild (after an operation left conflicts).focus_wip: bool,- worktrees: Vec<Worktree>,- terminal: Option<Terminal>,+ last_fetch: Instant,++ terminals: Vec<Terminal>,+ active_terminal: usize,terminal_open: bool,terminal_error: Option<String>,++ watcher: Option<notify::RecommendedWatcher>,+ fs_rx: Option<Receiver<bool>>,+ /// A change on disk not yet reloaded: (inside .git, when).+ fs_pending: Option<(bool, Instant)>,++ /// Actions queued from outside (the command palette).+ queued: Vec<Action>,/// A folder the app should open in a new tab (taken by `App`).pub open_request: Option<PathBuf>,+ /// The app has a dialog of its own open (palette, settings): leave the keys to it.+ pub keys_blocked: bool,+ /// A long operation that just ended: (message, failed), for a notification (taken by `App`).+ pub finished: Option<(String, bool)>,}impl RepoTab {@@ -147,6 +287,8 @@ impl RepoTab {load_error: None,refs: Refs::default(),history: Vec::new(),+ has_more: false,+ loading_more: false,work: WorkStatus::default(),commits: Vec::new(),graph: Graph {@@ -154,24 +296,51 @@ impl RepoTab {width: 0,},index: HashMap::new(),+ worktrees: Vec::new(),+ stashes: Vec::new(),+ remotes: Vec::new(),+ identity: Identity::default(),+ forge: None,+ prs: Vec::new(),+ pr_error: None,+ prs_loaded: None,selected: None,+ stash_view: None,scroll_to: None,+ detail_hash: None,detail: None,detail_error: None,diff: None,+ diff_split: false,+ diff_ignore_ws: false,+ conflict: None,commit_summary: String::new(),commit_body: String::new(),+ amend: false,dialog: None,+ search: Search::default(),+ pending_goto: None,+ undo_stack: Vec::new(),+ redo_stack: Vec::new(),busy_op: None,+ op_started: None,status: None,branch_filter: String::new(),focus_wip: false,- worktrees: Vec::new(),- terminal: None,+ last_fetch: Instant::now(),+ terminals: Vec::new(),+ active_terminal: 0,terminal_open: false,terminal_error: None,+ watcher: None,+ fs_rx: None,+ fs_pending: None,+ queued: Vec::new(),open_request: None,+ keys_blocked: false,+ finished: None,};+ tab.watch(ctx);tab.reload(ctx);tab}@@ -180,25 +349,39 @@ impl RepoTab {self.loading || self.busy_op.is_some()}- /// Re-reads refs, history and working-tree status in the background.+ /// Queues an action from outside the tab (the command palette).+ pub(crate) fn queue(&mut self, action: Action) {+ self.queued.push(action);+ }++ /// Re-reads refs, history, working tree, worktrees, stashes and remotes in the background.pub fn reload(&mut self, ctx: &egui::Context) {if self.loading {return;}self.loading = true;let path = self.path.clone();+ // Keep the pages already loaded.+ let count = self.history.len().clamp(git::LOG_PAGE, MAX_HISTORY);spawn(&self.tx, ctx, move || {Msg::Loaded((|| {let refs = git::refs(&path)?;- let history = git::log(&path)?;+ let history = git::log(&path, 0, count)?;let work = git::status(&path)?;// Very old gits have no `worktree list`; the section just stays empty.let worktrees = git::worktrees(&path).unwrap_or_default();+ let stashes = git::stashes(&path).unwrap_or_default();+ let remotes = git::remotes(&path).unwrap_or_default();+ let identity = git::identity(&path);Ok(Box::new(Loaded {refs,history,work,worktrees,+ stashes,+ remotes,+ identity,+ requested: count,}))})())});@@ -209,6 +392,68 @@ impl RepoTab {spawn(&self.tx, ctx, move || Msg::Status(git::status(&path)));}+ fn load_more(&mut self, ctx: &egui::Context) {+ if self.loading_more || !self.has_more || self.history.len() >= MAX_HISTORY {+ return;+ }+ self.loading_more = true;+ let path = self.path.clone();+ let skip = self.history.len();+ spawn(&self.tx, ctx, move || {+ Msg::More(git::log(&path, skip, git::LOG_PAGE))+ });+ }++ fn load_prs(&mut self, ctx: &egui::Context) {+ let Some(forge) = self.forge else { return };+ self.prs_loaded = Some(Instant::now());+ let path = self.path.clone();+ spawn(&self.tx, ctx, move || Msg::Prs(forge::list(&path, forge)));+ }++ /// Watches the folder so changes made elsewhere (editor, terminal) show up by themselves.+ fn watch(&mut self, ctx: &egui::Context) {+ use notify::Watcher;+ let (tx, rx) = channel();+ let ctx = ctx.clone();+ let handler = move |res: notify::Result<notify::Event>| {+ let Ok(event) = res else { return };+ if matches!(event.kind, notify::EventKind::Access(_)) {+ return;+ }+ for path in &event.paths {+ let s = path.to_string_lossy().replace('\\', "/");+ match s.split_once("/.git/") {+ // Refs, HEAD, the index and merge state matter; objects and logs don't.+ Some((_, inside)) => {+ let relevant = inside.starts_with("refs")+ || inside == "HEAD"+ || inside == "index"+ || inside == "packed-refs"+ || inside.ends_with("_HEAD")+ || inside.starts_with("rebase-");+ if relevant {+ let _ = tx.send(true);+ ctx.request_repaint_after(Duration::from_millis(500));+ }+ }+ None => {+ let _ = tx.send(false);+ ctx.request_repaint_after(Duration::from_millis(500));+ }+ }+ }+ };+ if let Ok(mut watcher) = notify::recommended_watcher(handler)+ && watcher+ .watch(&self.path, notify::RecursiveMode::Recursive)+ .is_ok()+ {+ self.watcher = Some(watcher);+ self.fs_rx = Some(rx);+ }+ }+fn is_wip(&self, row: usize) -> bool {self.commits.get(row).is_some_and(|c| c.hash == WIP_HASH)}@@ -231,10 +476,8 @@ impl RepoTab {} else {vec![self.refs.head.clone()]},- author: String::new(),- date: String::new(),- summary: String::new(),- refs: Vec::new(),+ time: git::now(),+ ..Commit::default()});}self.commits.extend(self.history.iter().cloned());@@ -250,20 +493,23 @@ impl RepoTab {let mut keep = previous.as_ref().and_then(|h| self.index.get(h).copied());if std::mem::take(&mut self.focus_wip) && self.index.contains_key(WIP_HASH) {keep = None;+ self.stash_view = None;}- let target = keep- .or_else(|| self.index.get(WIP_HASH).copied())- .or_else(|| self.index.get(&self.refs.head).copied());- match target {- Some(row) if keep == Some(row) => self.selected = Some(row),- Some(row) => {- self.selected = None;- self.select(row, ctx);- self.scroll_to = Some(row);- }- None => {- self.selected = None;- self.detail = None;+ if self.stash_view.is_none() {+ let target = keep+ .or_else(|| self.index.get(WIP_HASH).copied())+ .or_else(|| self.index.get(&self.refs.head).copied());+ match target {+ Some(row) if keep == Some(row) => self.selected = Some(row),+ Some(row) => {+ self.selected = None;+ self.select(row, ctx);+ self.scroll_to = Some(row);+ }+ None => {+ self.selected = None;+ self.detail = None;+ }}}@@ -290,47 +536,71 @@ impl RepoTab {.chain(&self.work.unstaged).chain(&self.work.conflicted).any(|f| f == file);+ let key = DiffKey::Work(file.clone());+ self.diff = None;+ self.conflict = None;if still {- let key = DiffKey::Work(file.clone());- self.diff = None;self.open_diff(key, ctx);- } else {- self.diff = None;}}++ if let Some(hash) = self.pending_goto.clone() {+ self.goto(&hash, ctx);+ }}fn select(&mut self, row: usize, ctx: &egui::Context) {let Some(commit) = self.commits.get(row) else {return;};- if self.selected == Some(row) {+ if self.selected == Some(row) && self.stash_view.is_none() {return;}+ let hash = commit.hash.clone();self.selected = Some(row);- self.detail = None;- self.detail_error = None;+ self.stash_view = None;if matches!(self.diff,Some(DiffView {key: DiffKey::Commit { .. },..})- ) || !self.is_wip(row)+ ) || hash != WIP_HASH{self.diff = None;+ self.conflict = None;}- if commit.hash == WIP_HASH {+ if hash == WIP_HASH {+ self.detail = None;+ self.detail_hash = None;return;}+ self.load_detail(hash, ctx);+ }++ fn load_detail(&mut self, hash: String, ctx: &egui::Context) {+ self.detail = None;+ self.detail_error = None;+ self.detail_hash = Some(hash.clone());let path = self.path.clone();- let hash = commit.hash.clone();spawn(&self.tx, ctx, move || {let detail = git::commit_detail(&path, &hash);Msg::Detail(hash, detail)});}+ fn select_stash(&mut self, i: usize, ctx: &egui::Context) {+ let Some(stash) = self.stashes.get(i) else {+ return;+ };+ let hash = stash.hash.clone();+ self.stash_view = Some(i);+ self.selected = None;+ self.diff = None;+ self.conflict = None;+ self.load_detail(hash, ctx);+ }+fn select_hash(&mut self, hash: &str, ctx: &egui::Context) {match self.index.get(hash).copied() {Some(row) => {@@ -349,39 +619,83 @@ impl RepoTab {}}- /// Shows a diff in the central area; asking for the open one closes it.+ /// Selects `hash`, loading more history first if it's further down.+ fn goto(&mut self, hash: &str, ctx: &egui::Context) {+ if self.index.contains_key(hash) {+ self.pending_goto = None;+ self.select_hash(hash, ctx);+ } else if self.has_more && self.history.len() < MAX_HISTORY {+ self.pending_goto = Some(hash.to_owned());+ self.load_more(ctx);+ } else {+ self.pending_goto = None;+ self.select_hash(hash, ctx);+ }+ }++ /// Shows a diff (or the conflict editor) in the central area; asking for the open one+ /// closes it.fn open_diff(&mut self, key: DiffKey, ctx: &egui::Context) {if self.diff.as_ref().is_some_and(|d| d.key == key) {self.diff = None;+ self.conflict = None;return;}+ self.conflict = match &key {+ DiffKey::Work(file) if file.area == git::Area::Conflicted => {+ conflict::ConflictEditor::open(&self.path, &file.path, self.work.in_progress)+ }+ _ => None,+ };self.diff = Some(DiffView {key: key.clone(),- lines: None,+ data: None,});let path = self.path.clone();+ let ignore_ws = self.diff_ignore_ws;+ let dark = Tokens::get(ctx).dark();spawn(&self.tx, ctx, move || {- let result = match &key {- DiffKey::Commit { hash, path: file } => git::file_diff(&path, hash, file),- DiffKey::Work(file) => git::work_diff(&path, file),- };+ let result = diff::load(&path, &key, ignore_ws, dark);Msg::Diff(key, result)});}+ fn reopen_diff(&mut self, ctx: &egui::Context) {+ if let Some(view) = self.diff.take() {+ self.conflict = None;+ self.open_diff(view.key, ctx);+ }+ }+/// Runs git commands one after another (stopping at the first failure), then refreshes.fn run_ops(&mut self,label: &str,ops: Vec<Vec<String>>,refresh: Refresh,+ kind: OpKind,+ ctx: &egui::Context,+ ) {+ self.run_ops_ex(label, ops, refresh, kind, false, ctx);+ }++ fn run_ops_ex(+ &mut self,+ label: &str,+ ops: Vec<Vec<String>>,+ refresh: Refresh,+ kind: OpKind,+ quiet: bool,ctx: &egui::Context,) {if self.busy_op.is_some() {return;}self.busy_op = Some(label.to_owned());- self.status = None;+ self.op_started = Some(Instant::now());+ if !quiet {+ self.status = None;+ }let path = self.path.clone();let label = label.to_owned();spawn(&self.tx, ctx, move || {@@ -393,26 +707,97 @@ impl RepoTab {break;}}+ // For HEAD moves, the new HEAD is what redo goes back to.+ let kind = match kind {+ OpKind::Normal(Undo::HeadMove { mode }, before) if result.is_ok() => {+ OpKind::Normal(+ Undo::HeadMove { mode },+ format!("{before}\u{0}{}", git::head(&path)),+ )+ }+ other => other,+ };Msg::OpDone {label,result,refresh,+ kind,+ quiet,}});}+ /// Runs `ops` as an undoable step.+ fn run_undoable(+ &mut self,+ label: &str,+ ops: Vec<Vec<String>>,+ refresh: Refresh,+ undo: Undo,+ ctx: &egui::Context,+ ) {+ let before = self.refs.head.clone();+ self.run_ops(label, ops, refresh, OpKind::Normal(undo, before), ctx);+ }++ fn checkout(&mut self, target: &str, ctx: &egui::Context) {+ let previous = self+ .refs+ .current+ .clone()+ .unwrap_or_else(|| self.refs.head.clone());+ let undo = if previous.is_empty() {+ Undo::None+ } else {+ Undo::Custom {+ undo: ops(&[&["checkout", &previous]]),+ redo: ops(&[&["checkout", target]]),+ }+ };+ self.run_undoable(+ &format!("Checkout {target}"),+ ops(&[&["checkout", target]]),+ Refresh::All,+ undo,+ ctx,+ );+ }+fn checkout_remote(&mut self, remote_branch: &str, ctx: &egui::Context) {// `origin/feature` → local `feature` tracking it (or just switch if it exists).let local = remote_branch.split_once('/').map(|(_, b)| b)- .unwrap_or(remote_branch);- let op = if self.refs.local.iter().any(|b| b.name == local) {- ops(&[&["checkout", local]])- } else {- ops(&[&["checkout", "--track", remote_branch]])- };- self.run_ops(&format!("Checkout {local}"), op, Refresh::All, ctx);+ .unwrap_or(remote_branch)+ .to_owned();+ if self.refs.local.iter().any(|b| b.name == local) {+ self.checkout(&local, ctx);+ return;+ }+ let previous = self+ .refs+ .current+ .clone()+ .unwrap_or_else(|| self.refs.head.clone());+ self.run_undoable(+ &format!("Checkout {local}"),+ ops(&[&["checkout", "--track", remote_branch]]),+ Refresh::All,+ Undo::Custom {+ undo: ops(&[&["checkout", &previous], &["branch", "-D", &local]]),+ redo: ops(&[&["checkout", "--track", remote_branch]]),+ },+ ctx,+ );+ }++ fn default_remote(&self) -> Option<String> {+ self.remotes+ .iter()+ .map(|r| r.name.as_str())+ .find(|r| *r == "origin")+ .or_else(|| self.remotes.first().map(|r| r.name.as_str()))+ .map(str::to_owned)}fn push(&mut self, ctx: &egui::Context) {@@ -426,23 +811,22 @@ impl RepoTab {.iter().any(|b| b.name == current && !b.upstream.is_empty() && !b.upstream_gone());if has_upstream {- self.run_ops("Push", ops(&[&["push"]]), Refresh::All, ctx);+ self.run_ops(+ "Push",+ ops(&[&["push"]]),+ Refresh::All,+ OpKind::Normal(Undo::None, String::new()),+ ctx,+ );return;}// First push of a branch: publish it and track the remote one.- let remote = self- .refs- .remotes- .iter()- .map(|(r, _)| r.as_str())- .find(|r| *r == "origin")- .or_else(|| self.refs.remotes.first().map(|(r, _)| r.as_str()))- .map(str::to_owned);- match remote {+ match self.default_remote() {Some(remote) => self.run_ops(&format!("Push {current} to {remote}"),ops(&[&["push", "-u", &remote, ¤t]]),Refresh::All,+ OpKind::Normal(Undo::None, String::new()),ctx,),None => {@@ -461,130 +845,533 @@ impl RepoTab {self.status = Some(("Resolve the conflicted files first".to_owned(), true));return;}- let mut commit = vec!["commit".to_owned(), "-m".to_owned(), summary.to_owned()];+ let mut commit = vec!["commit".to_owned()];+ if self.amend {+ commit.push("--amend".to_owned());+ }+ commit.extend(["-m".to_owned(), summary.to_owned()]);let body = self.commit_body.trim();if !body.is_empty() {commit.extend(["-m".to_owned(), body.to_owned()]);}- // Nothing staged: commit everything, like "Stage all and commit".let mut steps = Vec::new();- if self.work.staged.is_empty() {+ // A rebase stopped on conflicts finishes with `rebase --continue`, not a new commit.+ if self.work.in_progress == Some(InProgress::Rebase) {+ steps.push(vec!["rebase".to_owned(), "--continue".to_owned()]);+ self.run_ops(+ "Continue rebase",+ steps,+ Refresh::All,+ OpKind::Normal(Undo::None, String::new()),+ ctx,+ );+ return;+ }+ // Nothing staged: commit everything, like "Stage all and commit" (an amend with+ // nothing staged only rewrites the message).+ if self.work.staged.is_empty() && !self.amend {steps.push(vec!["add".to_owned(), "-A".to_owned()]);}steps.push(commit);- self.run_ops("Commit", steps, Refresh::All, ctx);+ let label = if self.amend { "Amend" } else { "Commit" };+ self.run_undoable(+ label,+ steps,+ Refresh::All,+ Undo::HeadMove { mode: "--soft" },+ ctx,+ );+ }++ fn stash_push(&mut self, message: &str, ctx: &egui::Context) {+ let mut args = vec!["stash", "push", "--include-untracked"];+ if !message.trim().is_empty() {+ args.extend(["-m", message.trim()]);+ }+ let redo = ops(&[&args]);+ self.run_undoable(+ "Stash",+ ops(&[&args]),+ Refresh::All,+ Undo::Custom {+ undo: ops(&[&["stash", "pop", "--index"]]),+ redo,+ },+ ctx,+ );+ }++ fn undo(&mut self, ctx: &egui::Context) {+ if self.busy_op.is_some() {+ return;+ }+ if let Some(entry) = self.undo_stack.pop() {+ let label = format!("Undo {}", entry.label);+ let steps = entry.undo.clone();+ self.run_ops(&label, steps, Refresh::All, OpKind::Undo(entry), ctx);+ }+ }++ fn redo(&mut self, ctx: &egui::Context) {+ if self.busy_op.is_some() {+ return;+ }+ if let Some(entry) = self.redo_stack.pop() {+ let label = format!("Redo {}", entry.label);+ let steps = entry.redo.clone();+ self.run_ops(&label, steps, Refresh::All, OpKind::Redo(entry), ctx);+ }+ }++ fn run_search(&mut self, ctx: &egui::Context) {+ let query = self.search.query.trim().to_owned();+ self.search.edited = None;+ if query.is_empty() {+ self.search.results.clear();+ self.search.matches.clear();+ self.search.searched.clear();+ return;+ }+ self.search.running = true;+ let path = self.path.clone();+ spawn(&self.tx, ctx, move || {+ let result = git::search(&path, &query);+ Msg::Search(query, result)+ });+ }++ fn search_step(&mut self, delta: i32, ctx: &egui::Context) {+ let n = self.search.results.len();+ if n == 0 {+ return;+ }+ let cur = self.search.current as i32 + delta;+ self.search.current = cur.rem_euclid(n as i32) as usize;+ if let Some(hash) = self.search.results.get(self.search.current).cloned() {+ self.goto(&hash, ctx);+ }}- /// Drains finished background work.+ fn start_terminal(+ &mut self,+ shell: Option<ShellSpec>,+ cwd: Option<PathBuf>,+ ctx: &egui::Context,+ ) {+ let shell = shell.unwrap_or_else(|| crate::terminal::default_shell(ctx));+ let cwd = cwd.unwrap_or_else(|| self.path.clone());+ match Terminal::spawn(&cwd, &shell, ctx) {+ Ok(term) => {+ self.terminals.push(term);+ self.active_terminal = self.terminals.len() - 1;+ self.terminal_error = None;+ self.terminal_open = true;+ }+ Err(e) => {+ self.terminal_error = Some(e);+ self.terminal_open = true;+ }+ }+ }++ /// Drains finished background work and file-system events.pub fn poll(&mut self, ctx: &egui::Context) {while let Ok(msg) = self.rx.try_recv() {- match msg {- Msg::Loaded(result) => {- self.loading = false;- match result {- Ok(loaded) => {- self.load_error = None;- self.refs = loaded.refs;- self.history = loaded.history;- self.work = loaded.work;- self.worktrees = loaded.worktrees;- self.rebuild(ctx);+ self.handle(msg, ctx);+ }++ // Changes on disk, debounced.+ if let Some(rx) = &self.fs_rx {+ while let Ok(git_dir) = rx.try_recv() {+ let was = self.fs_pending.map(|(g, _)| g).unwrap_or(false);+ self.fs_pending = Some((was || git_dir, Instant::now()));+ }+ }+ if let Some((git_dir, at)) = self.fs_pending+ && at.elapsed() > Duration::from_millis(400)+ && !self.loading+ && self.busy_op.is_none()+ {+ self.fs_pending = None;+ if git_dir {+ self.reload(ctx);+ } else {+ self.reload_status(ctx);+ }+ }++ // Background fetch.+ let minutes = Settings::get(ctx).auto_fetch_minutes;+ if minutes > 0+ && !self.remotes.is_empty()+ && self.busy_op.is_none()+ && self.last_fetch.elapsed() > Duration::from_secs(u64::from(minutes) * 60)+ {+ self.last_fetch = Instant::now();+ self.run_ops_ex(+ "Background fetch",+ ops(&[&["fetch", "--all", "--prune", "--quiet"]]),+ Refresh::All,+ OpKind::Normal(Undo::None, String::new()),+ true,+ ctx,+ );+ }+ if minutes > 0 {+ ctx.request_repaint_after(Duration::from_secs(30));+ }++ // Debounced search while typing.+ if let Some(at) = self.search.edited+ && at.elapsed() > Duration::from_millis(350)+ {+ self.run_search(ctx);+ } else if self.search.edited.is_some() {+ ctx.request_repaint_after(Duration::from_millis(100));+ }+ }++ fn handle(&mut self, msg: Msg, ctx: &egui::Context) {+ match msg {+ Msg::Loaded(result) => {+ self.loading = false;+ match result {+ Ok(loaded) => {+ self.load_error = None;+ self.refs = loaded.refs;+ self.has_more = loaded.history.len() >= loaded.requested;+ self.history = loaded.history;+ self.work = loaded.work;+ self.worktrees = loaded.worktrees;+ self.stashes = loaded.stashes;+ if self.stash_view.is_some_and(|i| i >= self.stashes.len()) {+ self.stash_view = None;}- Err(e) => self.load_error = Some(e),+ self.identity = loaded.identity;+ let forge = forge::detect(&loaded.remotes);+ self.remotes = loaded.remotes;+ if forge != self.forge {+ self.forge = forge;+ self.prs.clear();+ self.prs_loaded = None;+ }+ if self+ .prs_loaded+ .is_none_or(|t| t.elapsed() > Duration::from_secs(120))+ {+ self.load_prs(ctx);+ }+ self.rebuild(ctx);}+ Err(e) => self.load_error = Some(e),}- Msg::Status(result) => match result {- Ok(work) => {- self.work = work;+ }+ Msg::More(result) => {+ self.loading_more = false;+ match result {+ Ok(page) => {+ self.has_more = page.len() == git::LOG_PAGE;+ // A reload in between may have loaded these already.+ let known: HashSet<&str> =+ self.history.iter().map(|c| c.hash.as_str()).collect();+ let fresh: Vec<Commit> = page+ .into_iter()+ .filter(|c| !known.contains(c.hash.as_str()))+ .collect();+ self.history.extend(fresh);self.rebuild(ctx);}Err(e) => self.status = Some((e, true)),- },- Msg::Detail(hash, result) => {- if self.selected_hash().as_deref() == Some(hash.as_str()) {- match result {- Ok(d) => self.detail = Some(d),- Err(e) => self.detail_error = Some(e),- }- }}- Msg::Diff(key, result) => {- if let Some(view) = &mut self.diff- && view.key == key- {- view.lines = Some(result.map(|text| diff::parse(&text)));+ }+ Msg::Status(result) => match result {+ Ok(work) => {+ self.work = work;+ self.rebuild(ctx);+ }+ Err(e) => self.status = Some((e, true)),+ },+ Msg::Detail(hash, result) => {+ if self.detail_hash.as_deref() == Some(hash.as_str()) {+ match result {+ Ok(d) => self.detail = Some(d),+ Err(e) => self.detail_error = Some(e),}}- Msg::OpDone {- label,- result,- refresh,- } => {- self.busy_op = None;+ }+ Msg::Diff(key, result) => {+ if let Some(view) = &mut self.diff+ && view.key == key+ {+ view.data = Some(result);+ }+ }+ Msg::Search(query, result) => {+ if query == self.search.query.trim() {+ self.search.running = false;+ self.search.searched = query;match result {- Ok(_) => {- if label == "Commit" {- self.commit_summary.clear();- self.commit_body.clear();- }- // Quiet success for staging, which happens all the time.- if refresh == Refresh::All {- self.status = Some((format!("{label}: done"), false));+ Ok(hashes) => {+ self.search.matches = hashes.iter().cloned().collect();+ self.search.results = hashes;+ self.search.current = 0;+ if let Some(first) = self.search.results.first().cloned() {+ self.goto(&first, ctx);}}- Err(e) => {- self.focus_wip = e.contains("CONFLICT");- self.status = Some((format!("{label} failed: {e}"), true));+ Err(e) => self.status = Some((e, true)),+ }+ }+ }+ Msg::Prs(result) => match result {+ Ok(prs) => {+ self.prs = prs;+ self.pr_error = None;+ }+ Err(e) => self.pr_error = Some(e),+ },+ Msg::OpDone {+ label,+ result,+ refresh,+ kind,+ quiet,+ } => {+ self.busy_op = None;+ let long = self+ .op_started+ .take()+ .is_some_and(|t| t.elapsed() > LONG_OP);+ match &result {+ Ok(_) => {+ if label == "Commit" || label == "Amend" || label == "Continue rebase" {+ self.commit_summary.clear();+ self.commit_body.clear();+ self.amend = false;}+ // Quiet success for staging, which happens all the time.+ if refresh == Refresh::All && !quiet {+ self.status = Some((format!("{label}: done"), false));+ }+ if label.contains("etch") {+ self.load_prs(ctx);+ }+ self.record_undo(&label, kind);}- match refresh {- Refresh::Status => self.reload_status(ctx),- Refresh::All => self.reload(ctx),+ Err(e) => {+ self.focus_wip = e.contains("CONFLICT") || e.contains("could not apply");+ self.status = Some((format!("{label} failed: {e}"), true));+ // A failed undo stays undoable.+ match kind {+ OpKind::Undo(entry) => self.undo_stack.push(entry),+ OpKind::Redo(entry) => self.redo_stack.push(entry),+ OpKind::Normal(..) => {}+ }}}+ if long && !quiet {+ self.finished = Some(match &result {+ Ok(_) => (format!("{} · {label}: done", self.name), false),+ Err(e) => (+ format!("{} · {label} failed: {}", self.name, headline(e)),+ true,+ ),+ });+ }+ match refresh {+ Refresh::Status => self.reload_status(ctx),+ Refresh::All => self.reload(ctx),+ }+ }+ }+ }++ fn record_undo(&mut self, label: &str, kind: OpKind) {+ match kind {+ OpKind::Normal(Undo::None, _) => {}+ OpKind::Normal(Undo::HeadMove { mode }, heads) => {+ let (before, after) = heads.split_once('\u{0}').unwrap_or(("", ""));+ if before.is_empty() || after.is_empty() || before == after {+ return;+ }+ self.undo_stack.push(UndoEntry {+ label: label.to_owned(),+ undo: ops(&[&["reset", mode, before]]),+ redo: ops(&[&["reset", mode, after]]),+ });+ self.redo_stack.clear();+ }+ OpKind::Normal(Undo::Custom { undo, redo }, _) => {+ self.undo_stack.push(UndoEntry {+ label: label.to_owned(),+ undo,+ redo,+ });+ self.redo_stack.clear();}+ OpKind::Undo(entry) => self.redo_stack.push(entry),+ OpKind::Redo(entry) => self.undo_stack.push(entry),+ }+ // Plenty for a session.+ if self.undo_stack.len() > 50 {+ self.undo_stack.remove(0);}}- fn apply(&mut self, action: Action, ctx: &egui::Context) {+ pub(crate) fn apply(&mut self, action: Action, ctx: &egui::Context) {+ let plain = OpKind::Normal(Undo::None, String::new());match action {Action::Select(row) => self.select(row, ctx),- Action::SelectHash(hash) => self.select_hash(&hash, ctx),+ Action::SelectHash(hash) => self.goto(&hash, ctx),+ Action::SelectStash(i) => self.select_stash(i, ctx),Action::OpenDiff(key) => self.open_diff(key, ctx),- Action::CloseDiff => self.diff = None,+ Action::CloseDiff => {+ self.diff = None;+ self.conflict = None;+ }Action::Ops {label,ops,refresh,- } => self.run_ops(&label, ops, refresh, ctx),- Action::Checkout(name) => self.run_ops(- &format!("Checkout {name}"),- ops(&[&["checkout", &name]]),- Refresh::All,- ctx,- ),+ } => self.run_ops(&label, ops, refresh, plain, ctx),+ Action::UndoableOps {+ label,+ ops,+ refresh,+ undo,+ } => self.run_undoable(&label, ops, refresh, undo, ctx),+ Action::Checkout(name) => self.checkout(&name, ctx),Action::CheckoutRemote(name) => self.checkout_remote(&name, ctx),Action::Dialog(dialog) => self.dialog = Some(dialog),Action::Commit => self.commit(ctx),- Action::Fetch => self.run_ops(- "Fetch",- ops(&[&["fetch", "--all", "--prune"]]),+ Action::Fetch => {+ self.last_fetch = Instant::now();+ self.run_ops(+ "Fetch",+ ops(&[&["fetch", "--all", "--prune"]]),+ Refresh::All,+ plain,+ ctx,+ )+ }+ Action::Pull => self.run_undoable(+ "Pull",+ ops(&[&["pull", "--ff-only"]]),Refresh::All,+ Undo::HeadMove { mode: "--keep" },ctx,),- Action::Pull => self.run_ops("Pull", ops(&[&["pull", "--ff-only"]]), Refresh::All, ctx),Action::Push => self.push(ctx),Action::Reload => self.reload(ctx),+ Action::LoadMore => self.load_more(ctx),+ Action::Undo => self.undo(ctx),+ Action::Redo => self.redo(ctx),+ Action::StashPush(message) => self.stash_push(&message, ctx),Action::OpenTab(path) => self.open_request = Some(path),Action::ToggleTerminal => {self.terminal_open = !self.terminal_open;- if self.terminal_open && self.terminal.is_none() {- self.start_terminal(ctx);+ if self.terminal_open && self.terminals.is_empty() {+ self.start_terminal(None, None, ctx);+ }+ }+ Action::NewTerminal { shell, cwd } => self.start_terminal(shell, cwd, ctx),+ Action::CloseTerminal(i) => {+ if i < self.terminals.len() {+ self.terminals.remove(i);+ }+ self.active_terminal = self+ .active_terminal+ .min(self.terminals.len().saturating_sub(1));+ if self.terminals.is_empty() {+ self.terminal_open = false;+ }+ }+ Action::SelectTerminal(i) => self.active_terminal = i,+ Action::ToggleSearch => {+ self.search.open = !self.search.open;+ self.search.focus = self.search.open;+ if !self.search.open {+ self.search.matches.clear();+ self.search.results.clear();+ self.search.searched.clear();+ }+ }+ Action::SearchStep(d) => self.search_step(d, ctx),+ Action::CreatePr {+ branch,+ base,+ title,+ body,+ draft,+ } => {+ let Some(forge) = self.forge else { return };+ if self.busy_op.is_some() {+ return;+ }+ let label = format!("Create {}", forge.noun());+ self.busy_op = Some(label.clone());+ self.op_started = Some(Instant::now());+ let path = self.path.clone();+ spawn(&self.tx, ctx, move || {+ // Publish the branch first, so the forge can see it.+ let pushed = git::run(Some(&path), &["push", "-u", "origin", &branch]);+ let result = pushed.and_then(|_| {+ forge::create(&path, forge, &branch, &base, &title, &body, draft)+ });+ Msg::OpDone {+ label,+ result,+ refresh: Refresh::All,+ kind: OpKind::Normal(Undo::None, String::new()),+ quiet: false,+ }+ });+ }+ Action::OpenUrl(url) => {+ let _ = open::that_detached(url);+ }+ Action::OpenPath(rel) => {+ let _ = open::that_detached(self.path.join(rel));+ }+ Action::OpenInEditor(rel) => {+ let editor = Settings::get(ctx).editor;+ if let Err(e) = open_in_editor(&editor, &self.path.join(rel)) {+ self.status = Some((e, true));}}- Action::RestartTerminal => {- self.terminal = None;- self.start_terminal(ctx);+ Action::SetIdentity(name, email) => self.run_ops(+ "Set identity",+ ops(&[+ &["config", "--local", "user.name", &name],+ &["config", "--local", "user.email", &email],+ ]),+ Refresh::All,+ plain,+ ctx,+ ),+ Action::SetDiffOptions { split, ignore_ws } => {+ self.diff_split = split;+ if ignore_ws != self.diff_ignore_ws {+ self.diff_ignore_ws = ignore_ws;+ self.reopen_diff(ctx);+ }+ }+ Action::SaveConflict => {+ if let Some(editor) = &self.conflict {+ match editor.save(&self.path) {+ Ok(()) => {+ let file = editor.path.clone();+ self.run_ops(+ "Mark resolved",+ ops(&[&["add", "--", &file]]),+ Refresh::Status,+ plain,+ ctx,+ );+ }+ Err(e) => self.status = Some((e, true)),+ }+ }}}}@@ -593,14 +1380,37 @@ impl RepoTab {let ctx = ui.ctx().clone();self.poll(&ctx);let t = Tokens::get(&ctx);- let mut acts = Vec::new();+ let mut acts: Vec<Action> = std::mem::take(&mut self.queued);- if self.diff.is_some()- && self.dialog.is_none()- && !ctx.egui_wants_keyboard_input()- && ctx.input(|i| i.key_pressed(Key::Escape))- {- acts.push(Action::CloseDiff);+ let free_keys =+ self.dialog.is_none() && !self.keys_blocked && !ctx.egui_wants_keyboard_input();+ if free_keys {+ let (esc, undo, redo, find) = ctx.input(|i| {+ (+ i.key_pressed(Key::Escape),+ i.modifiers.command && !i.modifiers.shift && i.key_pressed(Key::Z),+ i.modifiers.command+ && (i.key_pressed(Key::Y) || (i.modifiers.shift && i.key_pressed(Key::Z))),+ i.modifiers.command && i.key_pressed(Key::F),+ )+ });+ if esc && self.diff.is_some() {+ acts.push(Action::CloseDiff);+ } else if esc && self.search.open {+ acts.push(Action::ToggleSearch);+ }+ if undo {+ acts.push(Action::Undo);+ }+ if redo {+ acts.push(Action::Redo);+ }+ if find {+ self.search.open = true;+ self.search.focus = true;+ }+ } else if self.search.open && ctx.input(|i| i.modifiers.command && i.key_pressed(Key::F)) {+ self.search.focus = true;}egui::Panel::top("repo_toolbar")@@ -614,7 +1424,7 @@ impl RepoTab {let side = egui::Frame::new().fill(t.card);egui::Panel::left("repo_branches").resizable(true)- .default_size(260.0)+ .default_size(270.0).size_range(170.0..=520.0).frame(side).show(ui, |ui| self.sidebar(ui, &mut acts));@@ -635,7 +1445,9 @@ impl RepoTab {egui::CentralPanel::default().frame(egui::Frame::new().fill(t.dock)).show(ui, |ui| {- if self.diff.is_some() {+ if self.conflict.is_some() {+ self.conflict_view(ui, &mut acts);+ } else if self.diff.is_some() {self.diff_view(ui, &mut acts);} else {self.graph_view(ui, &mut acts);@@ -653,20 +1465,69 @@ impl RepoTab {ui.horizontal(|ui| {ui.spacing_mut().item_spacing.x = 2.0;let idle = self.busy_op.is_none();- let has_remote = !self.refs.remotes.is_empty();- if icons::tool_button(ui, "cloud-download", "Fetch", idle && has_remote)- .on_hover_text("Fetch all remotes (git fetch --all --prune)")++ let undo_tip = match self.undo_stack.last() {+ Some(e) => format!("Undo {} (Ctrl+Z)", e.label),+ None => "Nothing to undo".to_owned(),+ };+ if icons::tool_button(ui, "undo-2", "", idle && !self.undo_stack.is_empty())+ .on_hover_text(undo_tip)+ .on_disabled_hover_text("Nothing to undo").clicked(){- acts.push(Action::Fetch);+ acts.push(Action::Undo);+ }+ let redo_tip = match self.redo_stack.last() {+ Some(e) => format!("Redo {} (Ctrl+Y)", e.label),+ None => "Nothing to redo".to_owned(),+ };+ if icons::tool_button(ui, "redo-2", "", idle && !self.redo_stack.is_empty())+ .on_hover_text(redo_tip)+ .on_disabled_hover_text("Nothing to redo")+ .clicked()+ {+ acts.push(Action::Redo);}- if icons::tool_button(ui, "arrow-down-to-line", "Pull", idle && has_remote)- .on_hover_text("Fast-forward the current branch (git pull --ff-only)")+ widgets::toolbar_separator(ui);++ let has_remote = !self.remotes.is_empty();+ let fetched = format!(+ "Fetch all remotes (git fetch --all --prune)\nLast fetched {} ago",+ short_duration(self.last_fetch.elapsed())+ );+ if icons::tool_button(ui, "cloud-download", "Fetch", idle && has_remote)+ .on_hover_text(fetched).clicked(){+ acts.push(Action::Fetch);+ }+ let (ahead, behind) = self+ .refs+ .current+ .as_ref()+ .and_then(|c| self.refs.local.iter().find(|b| &b.name == c))+ .map(|b| b.ahead_behind())+ .unwrap_or((0, 0));+ let pull_label = if behind > 0 {+ format!("Pull {behind}")+ } else {+ "Pull".to_owned()+ };+ let pull =+ icons::tool_button(ui, "arrow-down-to-line", &pull_label, idle && has_remote)+ .on_hover_text("Fast-forward the current branch (git pull --ff-only)");+ if behind > 0 {+ widgets::count_badge(ui, pull.rect, t.accent);+ }+ if pull.clicked() {acts.push(Action::Pull);}- if icons::tool_button(ui, "arrow-up-from-line", "Push", idle && has_remote)+ let push_label = if ahead > 0 {+ format!("Push {ahead}")+ } else {+ "Push".to_owned()+ };+ if icons::tool_button(ui, "arrow-up-from-line", &push_label, idle && has_remote).on_hover_text("Push the current branch (publishes it if it has no upstream yet)").clicked(){@@ -680,20 +1541,42 @@ impl RepoTab {{acts.push(Action::Dialog(Dialog::create_branch(&head, "HEAD")));}+ if icons::tool_button(ui, "archive", "Stash", idle && !self.work.is_clean())+ .on_hover_text("Stash all changes, untracked files included")+ .on_disabled_hover_text("No changes to stash")+ .clicked()+ {+ acts.push(Action::Dialog(Dialog::stash()));+ }let terminal = icons::tool_button(ui, "square-terminal", "Terminal", true).on_hover_text("Terminal in the repository folder");if self.terminal_open {- ui.painter().line_segment(- [- terminal.rect.left_bottom() + egui::vec2(6.0, -1.0),- terminal.rect.right_bottom() + egui::vec2(-6.0, -1.0),- ],- egui::Stroke::new(2.0, t.accent),- );+ widgets::active_underline(ui, terminal.rect, t.accent);}if terminal.clicked() {acts.push(Action::ToggleTerminal);}+ let search =+ icons::tool_button(ui, "search", "", true).on_hover_text("Search commits (Ctrl+F)");+ if self.search.open {+ widgets::active_underline(ui, search.rect, t.accent);+ }+ if search.clicked() {+ acts.push(Action::ToggleSearch);+ }+ let open =+ icons::tool_button(ui, "external-link", "", true).on_hover_text("Open the folder…");+ egui::Popup::menu(&open).show(|ui| {+ if ui.button(reveal_label()).clicked() {+ acts.push(Action::OpenPath(PathBuf::new()));+ }+ if ui.button("Open in editor").clicked() {+ acts.push(Action::OpenInEditor(PathBuf::new()));+ }+ if ui.button("Copy path").clicked() {+ ui.ctx().copy_text(self.path.display().to_string());+ }+ });widgets::toolbar_separator(ui);if icons::tool_button(ui, "refresh-cw", "", !self.loading).on_hover_text("Reload (F5)")@@ -754,57 +1637,147 @@ impl RepoTab {});});}-}-impl RepoTab {- fn start_terminal(&mut self, ctx: &egui::Context) {- match Terminal::spawn(&self.path, ctx) {- Ok(term) => {- self.terminal = Some(term);- self.terminal_error = None;- }- Err(e) => self.terminal_error = Some(e),- }- }-- /// The bottom panel: a header strip and the shell.+ /// The bottom panel: terminal tabs and the active shell.fn terminal_panel(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {let t = Tokens::get(ui.ctx());- let title = match &self.terminal {- Some(term) => format!("Terminal · {}", term.shell),- None => "Terminal".to_owned(),- };- widgets::panel_header(ui, &title, |ui| {- if icons::small_button(ui, "x", "Close the panel (the shell keeps running)").clicked() {- acts.push(Action::ToggleTerminal);- }- if icons::small_button(ui, "refresh-cw", "Restart the shell").clicked() {- acts.push(Action::RestartTerminal);- }- });+ widgets::terminal_tabs(ui, &self.terminals, self.active_terminal, acts);if let Some(err) = &self.terminal_error {ui.add_space(8.0);ui.horizontal(|ui| {ui.add_space(10.0);ui.colored_label(t.danger, err);});- return;+ if self.terminals.is_empty() {+ return;+ }}- let Some(term) = &mut self.terminal else {+ let i = self.active_terminal;+ let Some(term) = self.terminals.get_mut(i) else {return;};if term.has_exited() {ui.add_space(12.0);ui.vertical_centered(|ui| {ui.label(egui::RichText::new("The shell has exited.").color(t.text_dim));- if ui.button("Start a new one").clicked() {- acts.push(Action::RestartTerminal);+ if ui.button("Close").clicked() {+ acts.push(Action::CloseTerminal(i));}});return;}term.ui(ui);}++ /// What the command palette offers for this repository.+ pub(crate) fn palette_items(&self) -> Vec<(String, String, Action)> {+ let mut items: Vec<(String, String, Action)> = vec![+ ("Fetch".into(), "remote".into(), Action::Fetch),+ ("Pull".into(), "remote".into(), Action::Pull),+ ("Push".into(), "remote".into(), Action::Push),+ ("Undo".into(), "Ctrl+Z".into(), Action::Undo),+ ("Redo".into(), "Ctrl+Y".into(), Action::Redo),+ (+ "Stash changes".into(),+ "stash".into(),+ Action::Dialog(Dialog::stash()),+ ),+ (+ "Search commits".into(),+ "Ctrl+F".into(),+ Action::ToggleSearch,+ ),+ (+ "Toggle terminal".into(),+ "terminal".into(),+ Action::ToggleTerminal,+ ),+ (+ "New terminal".into(),+ "terminal".into(),+ Action::NewTerminal {+ shell: None,+ cwd: None,+ },+ ),+ ("Reload".into(), "F5".into(), Action::Reload),+ (+ reveal_label().into(),+ "folder".into(),+ Action::OpenPath(PathBuf::new()),+ ),+ (+ "Open in editor".into(),+ "folder".into(),+ Action::OpenInEditor(PathBuf::new()),+ ),+ ];+ if !self.refs.head.is_empty() {+ items.push((+ "Create branch".into(),+ "branch".into(),+ Action::Dialog(Dialog::create_branch(&self.refs.head, "HEAD")),+ ));+ items.push((+ "Create tag".into(),+ "tag".into(),+ Action::Dialog(Dialog::tag(&self.refs.head, "HEAD", self.default_remote())),+ ));+ }+ for b in &self.refs.local {+ if !b.is_head {+ items.push((+ format!("Check out {}", b.name),+ "branch".into(),+ Action::Checkout(b.name.clone()),+ ));+ }+ }+ if let Some(current) = &self.refs.current {+ for b in &self.refs.local {+ if !b.is_head {+ items.push((+ format!("Merge {} into {current}", b.name),+ "merge".into(),+ merge_action(&b.name, current),+ ));+ items.push((+ format!("Rebase {current} onto {}", b.name),+ "rebase".into(),+ rebase_action(&b.name, current),+ ));+ }+ }+ }+ for (remote, branches) in &self.refs.remotes {+ for b in branches {+ items.push((+ format!("Check out {}", b.name),+ remote.clone(),+ Action::CheckoutRemote(b.name.clone()),+ ));+ }+ }+ items+ }+}++pub(crate) fn merge_action(branch: &str, current: &str) -> Action {+ Action::UndoableOps {+ label: format!("Merge {branch} into {current}"),+ ops: ops(&[&["merge", "--no-edit", branch]]),+ refresh: Refresh::All,+ undo: Undo::HeadMove { mode: "--keep" },+ }+}++pub(crate) fn rebase_action(onto: &str, current: &str) -> Action {+ Action::UndoableOps {+ label: format!("Rebase {current} onto {onto}"),+ ops: ops(&[&["rebase", onto]]),+ refresh: Refresh::All,+ undo: Undo::HeadMove { mode: "--keep" },+ }}fn abort_action(state: InProgress) -> Action {@@ -815,6 +1788,52 @@ fn abort_action(state: InProgress) -> Action {}}+pub(crate) fn reveal_label() -> &'static str {+ if cfg!(windows) {+ "Show in Explorer"+ } else if cfg!(target_os = "macos") {+ "Show in Finder"+ } else {+ "Open folder"+ }+}++/// Runs the user's editor command with `path` (through `cmd` on Windows, where editors are+/// usually `.cmd` scripts).+pub(crate) fn open_in_editor(editor: &str, path: &Path) -> Result<(), String> {+ let editor = if editor.trim().is_empty() {+ "code"+ } else {+ editor.trim()+ };+ let mut cmd = if cfg!(windows) {+ let mut c = std::process::Command::new("cmd");+ c.arg("/C").arg(editor).arg(path);+ c+ } else {+ let mut c = std::process::Command::new(editor);+ c.arg(path);+ c+ };+ #[cfg(windows)]+ {+ use std::os::windows::process::CommandExt;+ cmd.creation_flags(0x0800_0000);+ }+ cmd.spawn()+ .map(|_| ())+ .map_err(|e| format!("Could not run {editor}: {e}"))+}++fn short_duration(d: Duration) -> String {+ let s = d.as_secs();+ match s {+ 0..60 => format!("{s} s"),+ 60..3600 => format!("{} min", s / 60),+ _ => format!("{} h", s / 3600),+ }+}+/// The line of a git error worth showing in the toolbar: conflicts and `error:`/`fatal:` lines/// beat progress chatter like "Auto-merging x".fn headline(msg: &str) -> String {@@ -852,7 +1871,6 @@ fn spawn(tx: &Sender<Msg>, ctx: &egui::Context, job: impl FnOnce() -> Msg + Sendctx.request_repaint();});}-pub use widgets::primary_button;#[cfg(test)]mod tests {diff --git a/src/repo/sidebar.rs b/src/repo/sidebar.rsindex 56b6925..61ca465 100644--- a/src/repo/sidebar.rs+++ b/src/repo/sidebar.rs@@ -1,10 +1,11 @@-//! Left pane: local branches, remote branches per remote, tags.+//! Left pane: local branches, remotes and their branches, worktrees, stashes, pull requests,+//! tags.use egui::{Align2, Rect, Response, Sense, Ui, pos2, vec2};use super::widgets::{self, ROW_H};-use super::{Action, Dialog, Refresh, RepoTab, ops};-use crate::git::Branch;+use super::{Action, Dialog, Refresh, RepoTab, Undo, merge_action, ops, rebase_action};+use crate::git::{self, Branch};use crate::icons;use crate::theme::{self, Tokens};@@ -26,7 +27,6 @@ impl RepoTab {let filter = self.branch_filter.to_lowercase();let matches = |b: &&Branch| filter.is_empty() || b.name.to_lowercase().contains(&filter);- let current = self.refs.current.clone();let idle = self.busy_op.is_none();egui::ScrollArea::vertical()@@ -36,158 +36,680 @@ impl RepoTab {ui.spacing_mut().item_spacing.y = 0.0;let local: Vec<&Branch> = self.refs.local.iter().filter(matches).collect();- if widgets::section(ui, "local", "laptop", "LOCAL", local.len(), true) {+ let (open, add) = widgets::section_with_button(+ ui,+ "local",+ "laptop",+ "LOCAL",+ local.len(),+ true,+ Some(("plus", "New branch at HEAD…")),+ );+ if add && idle && !self.refs.head.is_empty() {+ acts.push(Action::Dialog(Dialog::create_branch(+ &self.refs.head,+ "HEAD",+ )));+ }+ if open {for b in local {- let (ahead, behind) = b.ahead_behind();- // Checked out in another worktree: git won't check it out here too.- let elsewhere = self- .worktrees- .iter()- .find(|w| !w.current && w.branch.as_deref() == Some(b.name.as_str()));- let r = branch_row(- ui,- &b.name,- b.is_head,- ahead,- behind,- b.upstream_gone(),- elsewhere.is_some(),- );- let tip = match (b.upstream.is_empty(), b.upstream_gone()) {- (true, _) => "Not tracking a remote branch".to_owned(),- (false, true) => format!("{} was deleted on the remote", b.upstream),- (false, false) => format!("Tracks {}", b.upstream),- };- let r = match elsewhere {- Some(wt) => r.on_hover_text(format!(- "{tip}\nChecked out in worktree {}\nDouble-click to open it",- wt.path.display()- )),- None => r.on_hover_text(format!("{tip}\nDouble-click to check out")),- };- if r.double_clicked() && elsewhere.is_some() {- if let Some(wt) = elsewhere {- acts.push(Action::OpenTab(wt.path.clone()));- }- } else if r.double_clicked() && !b.is_head && idle {- acts.push(Action::Checkout(b.name.clone()));- } else if r.clicked() {- acts.push(Action::SelectHash(b.target.clone()));+ self.local_branch_row(ui, acts, b, idle);+ }+ }++ self.remotes_section(ui, acts, idle, &filter);+ self.worktree_section(ui, acts, idle);+ self.stash_section(ui, acts, idle);+ self.pr_section(ui, acts, idle);++ let tags: Vec<&Branch> = self.refs.tags.iter().filter(matches).collect();+ if !tags.is_empty()+ && widgets::section(ui, "tags", "tag", "TAGS", tags.len(), false)+ {+ for tag in tags {+ let r = plain_row(ui, "tag", &tag.name, "");+ if r.clicked() {+ acts.push(Action::SelectHash(tag.target.clone()));}r.context_menu(|ui| {- if let Some(wt) = elsewhere {- if ui.button("Open its worktree in a tab").clicked() {- acts.push(Action::OpenTab(wt.path.clone()));- }- } else {- if ui.add_enabled(!b.is_head && idle, egui::Button::new("Check out")).clicked() {- acts.push(Action::Checkout(b.name.clone()));+ if ui.button("Copy name").clicked() {+ ui.ctx().copy_text(tag.name.clone());+ }+ if let Some(remote) = self.default_remote() {+ if ui+ .add_enabled(+ idle,+ egui::Button::new(format!("Push to {remote}")),+ )+ .clicked()+ {+ acts.push(Action::Ops {+ label: format!("Push tag {}", tag.name),+ ops: ops(&[&[+ "push",+ &remote,+ &format!("refs/tags/{}", tag.name),+ ]]),+ refresh: Refresh::All,+ });}if ui- .add_enabled(!b.is_head && idle, egui::Button::new("Check out in a new worktree…"))+ .add_enabled(+ idle,+ egui::Button::new(format!("Delete from {remote}…")),+ ).clicked(){- acts.push(Action::Dialog(Dialog::add_worktree(&self.path, Some(&b.name), &self.refs.head)));+ acts.push(Action::Dialog(Dialog::confirm(+ "Delete remote tag",+ format!("Delete the tag “{}” from {remote}?", tag.name),+ "Delete",+ ops(&[&[+ "push",+ &remote,+ "--delete",+ &format!("refs/tags/{}", tag.name),+ ]]),+ None,+ )));}}- merge_item(ui, acts, &b.name, current.as_deref(), b.is_head || !idle);- if ui.button("Create branch here…").clicked() {- acts.push(Action::Dialog(Dialog::create_branch(&b.target, &b.name)));- }- ui.separator();- if ui.button("Copy name").clicked() {- ui.ctx().copy_text(b.name.clone());- }ui.separator();if ui- .add_enabled(!b.is_head && idle, egui::Button::new("Delete…"))- .on_disabled_hover_text("Can't delete the checked-out branch")+ .add_enabled(idle, egui::Button::new("Delete tag…")).clicked(){- acts.push(Action::Dialog(Dialog::confirm(- "Delete branch",- format!("Delete the local branch “{}”?", b.name),- "Delete",- ops(&[&["branch", "-d", &b.name]]),- Some((- "Force, even if it isn't merged (-D)".to_owned(),- ops(&[&["branch", "-D", &b.name]]),- )),- )));+ acts.push(Action::Dialog(+ Dialog::confirm(+ "Delete tag",+ format!("Delete the local tag “{}”?", tag.name),+ "Delete",+ ops(&[&["tag", "-d", &tag.name]]),+ None,+ )+ .undo(Undo::Custom {+ undo: ops(&[&["tag", &tag.name, &tag.target]]),+ redo: ops(&[&["tag", "-d", &tag.name]]),+ }),+ ));}});}}+ });+ }- for (remote, branches) in &self.refs.remotes {- let list: Vec<&Branch> = branches.iter().filter(matches).collect();- let title = remote.to_uppercase();- if widgets::section(ui, &format!("remote:{remote}"), "cloud", &title, list.len(), true) {- for b in list {- let short = b- .name- .strip_prefix(&format!("{remote}/"))- .unwrap_or(&b.name);- let r = branch_row(ui, short, false, 0, 0, false, false)- .on_hover_text(format!("{}\nDouble-click to check out", b.name));- if r.double_clicked() && idle {- acts.push(Action::CheckoutRemote(b.name.clone()));- } else if r.clicked() {- acts.push(Action::SelectHash(b.target.clone()));- }- r.context_menu(|ui| {- if ui.add_enabled(idle, egui::Button::new("Check out as local branch")).clicked() {- acts.push(Action::CheckoutRemote(b.name.clone()));- }- merge_item(ui, acts, &b.name, current.as_deref(), !idle);- if ui.button("Create branch here…").clicked() {- acts.push(Action::Dialog(Dialog::create_branch(&b.target, &b.name)));- }- ui.separator();- if ui.button("Copy name").clicked() {- ui.ctx().copy_text(b.name.clone());- }- ui.separator();- if ui.add_enabled(idle, egui::Button::new("Delete from remote…")).clicked() {- acts.push(Action::Dialog(Dialog::confirm(- "Delete remote branch",- format!("Delete “{short}” from {remote}? This changes the remote for everyone."),- "Delete",- ops(&[&["push", remote, "--delete", short]]),- None,- )));- }- });- }+ fn local_branch_row(&self, ui: &mut Ui, acts: &mut Vec<Action>, b: &Branch, idle: bool) {+ let (ahead, behind) = b.ahead_behind();+ // Checked out in another worktree: git won't check it out here too.+ let elsewhere = self+ .worktrees+ .iter()+ .find(|w| !w.current && w.branch.as_deref() == Some(b.name.as_str()));+ let has_pr = self.prs.iter().any(|p| p.branch == b.name);+ let r = branch_row(+ ui,+ &b.name,+ b.is_head,+ ahead,+ behind,+ b.upstream_gone(),+ elsewhere.is_some(),+ has_pr,+ );+ let tip = match (b.upstream.is_empty(), b.upstream_gone()) {+ (true, _) => "Not tracking a remote branch".to_owned(),+ (false, true) => format!("{} was deleted on the remote", b.upstream),+ (false, false) => format!("Tracks {}", b.upstream),+ };+ let r = match elsewhere {+ Some(wt) => r.on_hover_text(format!(+ "{tip}\nChecked out in worktree {}\nDouble-click to open it",+ wt.path.display()+ )),+ None => r.on_hover_text(format!("{tip}\nDouble-click to check out")),+ };+ if r.double_clicked() && elsewhere.is_some() {+ if let Some(wt) = elsewhere {+ acts.push(Action::OpenTab(wt.path.clone()));+ }+ } else if r.double_clicked() && !b.is_head && idle {+ acts.push(Action::Checkout(b.name.clone()));+ } else if r.clicked() {+ acts.push(Action::SelectHash(b.target.clone()));+ }+ r.context_menu(|ui| self.branch_menu_items(ui, acts, b, idle));+ }++ /// The menu of a local branch: in the sidebar and in the graph's commit menu.+ pub(super) fn branch_menu_items(+ &self,+ ui: &mut Ui,+ acts: &mut Vec<Action>,+ b: &Branch,+ idle: bool,+ ) {+ let elsewhere = self+ .worktrees+ .iter()+ .find(|w| !w.current && w.branch.as_deref() == Some(b.name.as_str()));+ if let Some(wt) = elsewhere {+ if ui.button("Open its worktree in a tab").clicked() {+ acts.push(Action::OpenTab(wt.path.clone()));+ }+ } else {+ if ui+ .add_enabled(!b.is_head && idle, egui::Button::new("Check out"))+ .clicked()+ {+ acts.push(Action::Checkout(b.name.clone()));+ }+ if ui+ .add_enabled(+ !b.is_head && idle,+ egui::Button::new("Check out in a new worktree…"),+ )+ .clicked()+ {+ acts.push(Action::Dialog(Dialog::add_worktree(+ &self.path,+ Some(&b.name),+ &self.refs.head,+ )));+ }+ }+ if let Some(current) = self.refs.current.as_deref()+ && !b.is_head+ {+ ui.separator();+ if ui+ .add_enabled(+ idle,+ egui::Button::new(format!("Merge {} into {current}", b.name)),+ )+ .clicked()+ {+ acts.push(merge_action(&b.name, current));+ }+ if ui+ .add_enabled(+ idle,+ egui::Button::new(format!("Rebase {current} onto {}", b.name)),+ )+ .clicked()+ {+ acts.push(rebase_action(&b.name, current));+ }+ }+ ui.separator();+ if let Some(remote) = self.default_remote()+ && ui+ .add_enabled(idle, egui::Button::new(format!("Push to {remote}")))+ .clicked()+ {+ acts.push(Action::Ops {+ label: format!("Push {}", b.name),+ ops: ops(&[&["push", "-u", &remote, &b.name]]),+ refresh: Refresh::All,+ });+ }+ if let Some(forge) = self.forge {+ let existing = self.prs.iter().find(|p| p.branch == b.name);+ match existing {+ Some(pr) => {+ if ui+ .button(format!("Open {} #{}", forge.noun(), pr.number))+ .clicked()+ {+ acts.push(Action::OpenUrl(pr.url.clone()));+ }+ }+ None => {+ if ui+ .add_enabled(idle, egui::Button::new(format!("Create {}…", forge.noun())))+ .clicked()+ {+ let base = self.default_base();+ let title = self+ .history+ .iter()+ .find(|c| c.hash == b.target)+ .map(|c| c.summary.clone())+ .unwrap_or_default();+ acts.push(Action::Dialog(Dialog::create_pr(+ forge.noun(),+ &b.name,+ &base,+ &title,+ )));}}+ }+ }+ ui.separator();+ if ui.button("Create branch here…").clicked() {+ acts.push(Action::Dialog(Dialog::create_branch(&b.target, &b.name)));+ }+ if ui.button("Create tag here…").clicked() {+ acts.push(Action::Dialog(Dialog::tag(+ &b.target,+ &b.name,+ self.default_remote(),+ )));+ }+ if ui.add_enabled(idle, egui::Button::new("Rename…")).clicked() {+ acts.push(Action::Dialog(Dialog::rename_branch(&b.name)));+ }+ if ui.button("Copy name").clicked() {+ ui.ctx().copy_text(b.name.clone());+ }+ ui.separator();+ if ui+ .add_enabled(!b.is_head && idle, egui::Button::new("Delete…"))+ .on_disabled_hover_text("Can't delete the checked-out branch")+ .clicked()+ {+ acts.push(Action::Dialog(+ Dialog::confirm(+ "Delete branch",+ format!("Delete the local branch “{}”?", b.name),+ "Delete",+ ops(&[&["branch", "-d", &b.name]]),+ Some((+ "Force, even if it isn't merged (-D)".to_owned(),+ ops(&[&["branch", "-D", &b.name]]),+ )),+ )+ .undo(Undo::Custom {+ undo: ops(&[&["branch", &b.name, &b.target]]),+ redo: ops(&[&["branch", "-D", &b.name]]),+ }),+ ));+ }+ }- self.worktree_section(ui, acts, idle);+ /// The branch pull requests go into by default: the remote's HEAD, else main / master.+ fn default_base(&self) -> String {+ let remote = self.default_remote().unwrap_or_else(|| "origin".to_owned());+ let names: Vec<&str> = self+ .refs+ .remotes+ .iter()+ .filter(|(r, _)| *r == remote)+ .flat_map(|(_, list)| list.iter().map(|b| b.name.as_str()))+ .collect();+ for candidate in ["main", "master", "develop"] {+ if names.contains(&format!("{remote}/{candidate}").as_str()) {+ return candidate.to_owned();+ }+ }+ "main".to_owned()+ }- let tags: Vec<&Branch> = self.refs.tags.iter().filter(matches).collect();- if !tags.is_empty() && widgets::section(ui, "tags", "tag", "TAGS", tags.len(), false) {- for tag in tags {- let r = plain_row(ui, &tag.name);- if r.clicked() {- acts.push(Action::SelectHash(tag.target.clone()));+ fn remotes_section(&self, ui: &mut Ui, acts: &mut Vec<Action>, idle: bool, filter: &str) {+ let t = Tokens::get(ui.ctx());+ let (open, add) = widgets::section_with_button(+ ui,+ "remotes",+ "cloud",+ "REMOTES",+ self.remotes.len(),+ true,+ Some(("plus", "Add a remote…")),+ );+ if add && idle {+ acts.push(Action::Dialog(Dialog::remote(None)));+ }+ if !open {+ return;+ }+ let current = self.refs.current.clone();+ for remote in &self.remotes {+ let branches: Vec<&Branch> = self+ .refs+ .remotes+ .iter()+ .filter(|(r, _)| *r == remote.name)+ .flat_map(|(_, list)| list.iter())+ .filter(|b| filter.is_empty() || b.name.to_lowercase().contains(filter))+ .collect();+ // A collapsible row per remote.+ let id = ui.id().with(("remote-open", &remote.name));+ let mut expanded = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(true);+ let (rect, r) =+ ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());+ if r.hovered() {+ ui.painter().rect_filled(rect, 0.0, t.hover);+ }+ if r.clicked() {+ expanded = !expanded;+ ui.data_mut(|d| d.insert_temp(id, expanded));+ }+ let y = rect.center().y;+ icons::paint(+ ui,+ Rect::from_center_size(pos2(rect.left() + 24.0, y), vec2(12.0, 12.0)),+ if expanded {+ "chevron-down"+ } else {+ "chevron-right"+ },+ 11.0,+ t.text_faint,+ );+ icons::paint(+ ui,+ Rect::from_center_size(pos2(rect.left() + 40.0, y), vec2(14.0, 14.0)),+ "cloud",+ 13.0,+ t.icon,+ );+ let p = ui.painter_at(rect);+ p.text(+ pos2(rect.left() + 54.0, y),+ Align2::LEFT_CENTER,+ &remote.name,+ theme::medium(12.5),+ t.text,+ );+ p.text(+ pos2(rect.right() - 10.0, y),+ Align2::RIGHT_CENTER,+ branches.len().to_string(),+ theme::medium(11.0),+ t.text_faint,+ );+ let r = r.on_hover_text(&remote.url);+ r.context_menu(|ui| {+ if ui.add_enabled(idle, egui::Button::new(format!("Fetch {}", remote.name))).clicked() {+ acts.push(Action::Ops {+ label: format!("Fetch {}", remote.name),+ ops: ops(&[&["fetch", "--prune", &remote.name]]),+ refresh: Refresh::All,+ });+ }+ if ui.add_enabled(idle, egui::Button::new("Edit…")).clicked() {+ acts.push(Action::Dialog(Dialog::remote(Some((remote.name.clone(), remote.url.clone())))));+ }+ if ui.button("Copy URL").clicked() {+ ui.ctx().copy_text(remote.url.clone());+ }+ ui.separator();+ if ui.add_enabled(idle, egui::Button::new("Remove…")).clicked() {+ acts.push(Action::Dialog(Dialog::confirm(+ "Remove remote",+ format!(+ "Remove the remote “{}” ({})? Its branches disappear from this repository; nothing changes on the server.",+ remote.name, remote.url+ ),+ "Remove",+ ops(&[&["remote", "remove", &remote.name]]),+ None,+ )));+ }+ });+ if !expanded {+ continue;+ }+ for b in branches {+ let short = b+ .name+ .strip_prefix(&format!("{}/", remote.name))+ .unwrap_or(&b.name);+ let has_pr = self.prs.iter().any(|p| p.branch == short);+ let r = branch_row_indented(ui, short, has_pr)+ .on_hover_text(format!("{}\nDouble-click to check out", b.name));+ if r.double_clicked() && idle {+ acts.push(Action::CheckoutRemote(b.name.clone()));+ } else if r.clicked() {+ acts.push(Action::SelectHash(b.target.clone()));+ }+ r.context_menu(|ui| {+ if ui+ .add_enabled(idle, egui::Button::new("Check out as local branch"))+ .clicked()+ {+ acts.push(Action::CheckoutRemote(b.name.clone()));+ }+ if let Some(current) = current.as_deref() {+ if ui+ .add_enabled(idle, egui::Button::new(format!("Merge into {current}")))+ .clicked()+ {+ acts.push(merge_action(&b.name, current));}- r.context_menu(|ui| {- if ui.button("Copy name").clicked() {- ui.ctx().copy_text(tag.name.clone());- }- if ui.add_enabled(idle, egui::Button::new("Delete tag…")).clicked() {- acts.push(Action::Dialog(Dialog::confirm(- "Delete tag",- format!("Delete the local tag “{}”?", tag.name),- "Delete",- ops(&[&["tag", "-d", &tag.name]]),- None,- )));- }- });+ if ui+ .add_enabled(+ idle,+ egui::Button::new(format!("Rebase {current} onto it")),+ )+ .clicked()+ {+ acts.push(rebase_action(&b.name, current));+ }+ }+ if ui.button("Create branch here…").clicked() {+ acts.push(Action::Dialog(Dialog::create_branch(&b.target, &b.name)));+ }+ ui.separator();+ if ui.button("Copy name").clicked() {+ ui.ctx().copy_text(b.name.clone());+ }+ ui.separator();+ if ui+ .add_enabled(idle, egui::Button::new("Delete from remote…"))+ .clicked()+ {+ acts.push(Action::Dialog(Dialog::confirm(+ "Delete remote branch",+ format!(+ "Delete “{short}” from {}? This changes the remote for everyone.",+ remote.name+ ),+ "Delete",+ ops(&[&["push", &remote.name, "--delete", short]]),+ None,+ )));+ }+ });+ }+ }+ }++ fn stash_section(&self, ui: &mut Ui, acts: &mut Vec<Action>, idle: bool) {+ let t = Tokens::get(ui.ctx());+ let (open, add) = widgets::section_with_button(+ ui,+ "stashes",+ "archive",+ "STASHES",+ self.stashes.len(),+ true,+ Some(("plus", "Stash changes…")),+ );+ if add && idle && !self.work.is_clean() {+ acts.push(Action::Dialog(Dialog::stash()));+ }+ if !open {+ return;+ }+ let now = git::now();+ for (i, stash) in self.stashes.iter().enumerate() {+ let (rect, r) =+ ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());+ if self.stash_view == Some(i) {+ ui.painter().rect_filled(rect, 0.0, t.row_selected);+ } else if r.hovered() {+ ui.painter().rect_filled(rect, 0.0, t.hover);+ }+ let y = rect.center().y;+ icons::paint(+ ui,+ Rect::from_center_size(pos2(rect.left() + 34.0, y), vec2(16.0, 16.0)),+ "archive",+ 13.0,+ t.text_faint,+ );+ let p = ui.painter_at(rect);+ p.text(+ pos2(rect.left() + 48.0, y - 7.0),+ Align2::LEFT_CENTER,+ &stash.message,+ egui::FontId::proportional(12.5),+ t.text,+ );+ p.text(+ pos2(rect.left() + 48.0, y + 8.0),+ Align2::LEFT_CENTER,+ format!("{} · {}", stash.name, git::relative_time(stash.time, now)),+ egui::FontId::proportional(11.0),+ t.text_faint,+ );+ if r.clicked() {+ acts.push(Action::SelectStash(i));+ }+ r.context_menu(|ui| stash_menu_items(ui, acts, &stash.name, idle));+ }+ }++ fn pr_section(&self, ui: &mut Ui, acts: &mut Vec<Action>, idle: bool) {+ let Some(forge) = self.forge else { return };+ let t = Tokens::get(ui.ctx());+ let title = match forge {+ crate::forge::Forge::GitHub => "PULL REQUESTS",+ crate::forge::Forge::GitLab => "MERGE REQUESTS",+ };+ if !widgets::section(ui, "prs", "git-pull-request", title, self.prs.len(), true) {+ return;+ }+ if let Some(err) = &self.pr_error {+ let (rect, r) =+ ui.allocate_exact_size(vec2(ui.available_width(), 26.0), Sense::hover());+ ui.painter_at(rect).text(+ pos2(rect.left() + 34.0, rect.center().y),+ Align2::LEFT_CENTER,+ err.lines().next().unwrap_or_default(),+ egui::FontId::proportional(11.0),+ t.text_faint,+ );+ r.on_hover_text(err.as_str());+ return;+ }+ for pr in &self.prs {+ let (rect, r) =+ ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());+ if r.hovered() {+ ui.painter().rect_filled(rect, 0.0, t.hover);+ }+ let y = rect.center().y;+ icons::paint(+ ui,+ Rect::from_center_size(pos2(rect.left() + 34.0, y), vec2(16.0, 16.0)),+ "git-pull-request",+ 13.0,+ if pr.draft { t.text_faint } else { t.success },+ );+ let p = ui.painter_at(rect);+ p.text(+ pos2(rect.left() + 48.0, y - 7.0),+ Align2::LEFT_CENTER,+ format!("#{} {}", pr.number, pr.title),+ egui::FontId::proportional(12.5),+ t.text,+ );+ let sub = format!(+ "{} · {}{}",+ pr.branch,+ pr.author,+ if pr.draft { " · draft" } else { "" }+ );+ p.text(+ pos2(rect.left() + 48.0, y + 8.0),+ Align2::LEFT_CENTER,+ sub,+ egui::FontId::proportional(11.0),+ t.text_faint,+ );+ let r = r.on_hover_text(format!("{}\nDouble-click to open in the browser", pr.url));+ // The branch's tip, local or on a remote.+ let target = self+ .refs+ .local+ .iter()+ .find(|b| b.name == pr.branch)+ .or_else(|| {+ self.refs+ .remotes+ .iter()+ .flat_map(|(_, l)| l.iter())+ .find(|b| {+ b.name.split_once('/').map(|(_, n)| n) == Some(pr.branch.as_str())+ })+ })+ .map(|b| b.target.clone());+ if r.double_clicked() {+ acts.push(Action::OpenUrl(pr.url.clone()));+ } else if r.clicked()+ && let Some(target) = &target+ {+ acts.push(Action::SelectHash(target.clone()));+ }+ r.context_menu(|ui| {+ if ui.button("Open in the browser").clicked() {+ acts.push(Action::OpenUrl(pr.url.clone()));+ }+ if ui+ .add_enabled(idle, egui::Button::new(format!("Check out {}", pr.branch)))+ .clicked()+ {+ if self.refs.local.iter().any(|b| b.name == pr.branch) {+ acts.push(Action::Checkout(pr.branch.clone()));+ } else {+ let remote = self.default_remote().unwrap_or_else(|| "origin".to_owned());+ acts.push(Action::CheckoutRemote(format!("{remote}/{}", pr.branch)));}}+ if ui.button("Copy URL").clicked() {+ ui.ctx().copy_text(pr.url.clone());+ }});+ }+ }+}++/// Apply / pop / drop for a stash (sidebar and detail pane).+pub(super) fn stash_menu_items(ui: &mut Ui, acts: &mut Vec<Action>, name: &str, idle: bool) {+ if ui+ .add_enabled(idle, egui::Button::new("Apply"))+ .on_hover_text("Bring the changes back and keep the stash")+ .clicked()+ {+ acts.push(Action::Ops {+ label: format!("Apply {name}"),+ ops: ops(&[&["stash", "apply", "--index", name]]),+ refresh: Refresh::All,+ });+ }+ if ui+ .add_enabled(idle, egui::Button::new("Pop"))+ .on_hover_text("Bring the changes back and drop the stash")+ .clicked()+ {+ acts.push(Action::Ops {+ label: format!("Pop {name}"),+ ops: ops(&[&["stash", "pop", "--index", name]]),+ refresh: Refresh::All,+ });+ }+ ui.separator();+ if ui.add_enabled(idle, egui::Button::new("Drop…")).clicked() {+ acts.push(Action::Dialog(Dialog::confirm(+ "Drop stash",+ format!("Delete {name}? Its changes are gone for good."),+ "Drop",+ ops(&[&["stash", "drop", name]]),+ None,+ )));}}@@ -301,6 +823,12 @@ impl RepoTab {{acts.push(Action::OpenTab(wt.path.clone()));}+ if ui.button("Open terminal here").clicked() {+ acts.push(Action::NewTerminal { shell: None, cwd: Some(wt.path.clone()) });+ }+ if ui.button(super::reveal_label()).clicked() {+ let _ = open::that_detached(&wt.path);+ }if ui.button("Copy path").clicked() {ui.ctx().copy_text(path.clone());}@@ -352,30 +880,8 @@ impl RepoTab {}}-fn merge_item(- ui: &mut Ui,- acts: &mut Vec<Action>,- branch: &str,- current: Option<&str>,- disabled: bool,-) {- let Some(current) = current else { return };- if ui- .add_enabled(- !disabled,- egui::Button::new(format!("Merge into {current}")),- )- .clicked()- {- acts.push(Action::Ops {- label: format!("Merge {branch} into {current}"),- ops: ops(&[&["merge", "--no-edit", branch]]),- refresh: Refresh::All,- });- }-}-/// A branch: icon (a check for the checked-out one), name, ahead/behind counts.+#[allow(clippy::too_many_arguments)]fn branch_row(ui: &mut Ui,name: &str,@@ -384,6 +890,7 @@ fn branch_row(behind: u32,gone: bool,in_worktree: bool,+ has_pr: bool,) -> Response {let t = Tokens::get(ui.ctx());let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());@@ -404,6 +911,11 @@ fn branch_row(let mut right = rect.right() - 8.0;let small = theme::mono(11.0);+ if has_pr {+ let ir = Rect::from_center_size(pos2(right - 6.0, y), vec2(12.0, 12.0));+ icons::paint(ui, ir, "git-pull-request", 12.0, t.success);+ right = ir.left() - 6.0;+ }if in_worktree {let ir = Rect::from_center_size(pos2(right - 6.0, y), vec2(12.0, 12.0));icons::paint(ui, ir, "folder-tree", 12.0, t.text_dim);@@ -453,7 +965,39 @@ fn branch_row(resp}-fn plain_row(ui: &mut Ui, name: &str) -> Response {+/// A remote's branch, one level in under its remote.+fn branch_row_indented(ui: &mut Ui, name: &str, has_pr: bool) -> Response {+ let t = Tokens::get(ui.ctx());+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());+ if resp.hovered() {+ ui.painter().rect_filled(rect, 0.0, t.hover);+ }+ let y = rect.center().y;+ icons::paint(+ ui,+ Rect::from_center_size(pos2(rect.left() + 52.0, y), vec2(16.0, 16.0)),+ "git-branch",+ 13.0,+ t.text_faint,+ );+ let mut right = rect.right() - 8.0;+ if has_pr {+ let ir = Rect::from_center_size(pos2(right - 6.0, y), vec2(12.0, 12.0));+ icons::paint(ui, ir, "git-pull-request", 12.0, t.success);+ right = ir.left() - 6.0;+ }+ ui.painter_at(rect.with_max_x(right)).text(+ pos2(rect.left() + 66.0, y),+ Align2::LEFT_CENTER,+ name,+ egui::FontId::proportional(12.5),+ t.text,+ );+ resp+}++/// An icon, a name and optional faint text after it.+fn plain_row(ui: &mut Ui, icon: &str, name: &str, sub: &str) -> Response {let t = Tokens::get(ui.ctx());let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());if resp.hovered() {@@ -463,16 +1007,26 @@ fn plain_row(ui: &mut Ui, name: &str) -> Response {icons::paint(ui,Rect::from_center_size(pos2(rect.left() + 34.0, y), vec2(16.0, 16.0)),- "tag",+ icon,13.0,t.text_faint,);- ui.painter_at(rect).text(+ let p = ui.painter_at(rect);+ let r = p.text(pos2(rect.left() + 48.0, y),Align2::LEFT_CENTER,name,egui::FontId::proportional(12.5),t.text,);+ if !sub.is_empty() {+ p.text(+ pos2(r.right() + 8.0, y),+ Align2::LEFT_CENTER,+ sub,+ egui::FontId::proportional(11.0),+ t.text_faint,+ );+ }resp}diff --git a/src/repo/widgets.rs b/src/repo/widgets.rsindex 8b149ec..1190a20 100644--- a/src/repo/widgets.rs+++ b/src/repo/widgets.rs@@ -333,9 +333,15 @@ pub fn primary_button(ui: &mut Ui, text: &str, enabled: bool, width: f32) -> Res)}-/// A round initials avatar, coloured by name so a person keeps their colour everywhere.-pub fn avatar(painter: &egui::Painter, center: egui::Pos2, radius: f32, name: &str) {- let t = Tokens::get(painter.ctx());+/// A round avatar: the author's picture when one is loaded (see `avatars`), their initials in+/// a colour of their own until then.+pub fn avatar(ui: &Ui, center: egui::Pos2, radius: f32, name: &str, email: &str) {+ let rect = Rect::from_center_size(center, vec2(radius * 2.0, radius * 2.0));+ if crate::avatars::paint(ui, rect, email) {+ return;+ }+ let t = Tokens::get(ui.ctx());+ let painter = ui.painter();painter.circle_filled(center, radius, t.lane(name_hash(name)));painter.text(center,@@ -361,3 +367,147 @@ fn name_hash(name: &str) -> usize {name.bytes().fold(7usize, |h, b| h.wrapping_mul(31).wrapping_add(b as usize))}++/// A dot on the top-right corner of a toolbar button (incoming commits…).+pub fn count_badge(ui: &Ui, button: Rect, color: Color32) {+ ui.painter()+ .circle_filled(button.right_top() + vec2(-5.0, 6.0), 3.5, color);+}++/// The accent line under an active toolbar toggle.+pub fn active_underline(ui: &Ui, button: Rect, color: Color32) {+ ui.painter().line_segment(+ [+ button.left_bottom() + vec2(6.0, -1.0),+ button.right_bottom() + vec2(-6.0, -1.0),+ ],+ egui::Stroke::new(2.0, color),+ );+}++/// The terminal panel's strip: one tab per shell, `+` with a shell menu, and close.+pub fn terminal_tabs(+ ui: &mut Ui,+ terminals: &[crate::terminal::Terminal],+ active: usize,+ acts: &mut Vec<super::Action>,+) {+ let t = Tokens::get(ui.ctx());+ let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::hover());+ ui.painter().rect_filled(strip, 0.0, t.tab_strip);+ let mut child = ui.new_child(+ egui::UiBuilder::new()+ .max_rect(strip.shrink2(vec2(4.0, 0.0)))+ .layout(egui::Layout::left_to_right(egui::Align::Max)),+ );+ let ui = &mut child;+ ui.spacing_mut().item_spacing.x = 2.0;+ for (i, term) in terminals.iter().enumerate() {+ let selected = i == active;+ let label = format!("{} {}", i + 1, term.shell);+ let font = if selected {+ theme::semibold(11.5)+ } else {+ theme::medium(11.5)+ };+ let galley =+ ui.painter()+ .layout_no_wrap(label, font, if selected { t.text } else { t.text_dim });+ let (rect, resp) =+ ui.allocate_exact_size(vec2(galley.size().x + 44.0, 26.0), Sense::click());+ let shape = CornerRadius {+ nw: t.radius as u8,+ ne: t.radius as u8,+ sw: 0,+ se: 0,+ };+ if selected {+ ui.painter().rect_filled(rect, shape, t.card);+ } else if resp.hovered() {+ ui.painter().rect_filled(rect, shape, t.hover);+ }+ icons::paint(+ ui,+ Rect::from_center_size(pos2(rect.left() + 13.0, rect.center().y), vec2(14.0, 14.0)),+ "square-terminal",+ 12.0,+ t.text_faint,+ );+ ui.painter().galley(+ pos2(rect.left() + 24.0, rect.center().y - galley.size().y / 2.0),+ galley,+ t.text,+ );+ let x_rect =+ Rect::from_center_size(pos2(rect.right() - 11.0, rect.center().y), vec2(16.0, 16.0));+ let x = ui+ .interact(x_rect, resp.id.with("close"), Sense::click())+ .on_hover_text("Close (ends the shell)");+ if x.hovered() {+ ui.painter().rect_filled(x_rect, t.radius_sm, t.pressed);+ }+ icons::paint(ui, x_rect, "x", 11.0, t.text_faint);+ if x.clicked() {+ acts.push(super::Action::CloseTerminal(i));+ } else if resp.clicked() {+ acts.push(super::Action::SelectTerminal(i));+ }+ }+ ui.add_space(4.0);+ let plus = icons::small_button(ui, "plus", "New terminal");+ if plus.clicked() {+ acts.push(super::Action::NewTerminal {+ shell: None,+ cwd: None,+ });+ }+ egui::Popup::context_menu(&plus).show(|ui| {+ for shell in crate::terminal::available_shells() {+ if ui.button(&shell.label).clicked() {+ acts.push(super::Action::NewTerminal {+ shell: Some(shell),+ cwd: None,+ });+ }+ }+ });+ let more = icons::small_button(ui, "chevron-down", "New terminal with…");+ egui::Popup::menu(&more).show(|ui| {+ for shell in crate::terminal::available_shells() {+ if ui.button(&shell.label).clicked() {+ acts.push(super::Action::NewTerminal {+ shell: Some(shell),+ cwd: None,+ });+ }+ }+ });+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ ui.add_space(4.0);+ if icons::small_button(ui, "x", "Hide the panel (shells keep running)").clicked() {+ acts.push(super::Action::ToggleTerminal);+ }+ });+}++/// Right-click menu for a file of the working tree or a commit: open it, its folder, copy path.+pub fn file_menu(resp: &Response, path: &str, acts: &mut Vec<super::Action>) {+ resp.context_menu(|ui| {+ let rel = std::path::PathBuf::from(path);+ if ui.button("Open file").clicked() {+ acts.push(super::Action::OpenPath(rel.clone()));+ }+ if ui.button("Open in editor").clicked() {+ acts.push(super::Action::OpenInEditor(rel.clone()));+ }+ if ui.button(super::reveal_label()).clicked() {+ acts.push(super::Action::OpenPath(+ rel.parent().map(|p| p.to_path_buf()).unwrap_or_default(),+ ));+ }+ ui.separator();+ if ui.button("Copy path").clicked() {+ ui.ctx().copy_text(path.to_owned());+ }+ });+}diff --git a/src/settings.rs b/src/settings.rsnew file mode 100644index 0000000..98ea6d7--- /dev/null+++ b/src/settings.rs@@ -0,0 +1,204 @@+//! User settings: stored with the app state, readable from anywhere through the egui context.++use egui::{RichText, Ui};+use serde::{Deserialize, Serialize};++use crate::theme::{self, Tokens};++/// A name and email to commit with, applied per repository.+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Profile {+ pub label: String,+ pub name: String,+ pub email: String,+}++#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default)]+pub struct Settings {+ /// Interface zoom (1.0 = 100 %).+ pub ui_scale: f32,+ pub terminal_font: f32,+ /// Program of the default shell; empty = the platform's default.+ pub shell: String,+ /// Width of the branch/tag column of the graph.+ pub refs_width: f32,+ pub show_author: bool,+ /// An absolute date column (tips show a relative date either way).+ pub show_date: bool,+ pub show_hash: bool,+ /// Background fetch interval in minutes; 0 turns it off.+ pub auto_fetch_minutes: u32,+ /// Load avatars from Gravatar / GitHub (sends a hash of each author's email).+ pub avatars: bool,+ /// Command that opens a folder or file in the user's editor.+ pub editor: String,+ /// Desktop notifications when a long operation ends while the window is in the background.+ pub notifications: bool,+ pub profiles: Vec<Profile>,+}++impl Default for Settings {+ fn default() -> Self {+ Self {+ ui_scale: 1.0,+ terminal_font: 12.5,+ shell: String::new(),+ refs_width: 270.0,+ show_author: true,+ show_date: false,+ show_hash: false,+ auto_fetch_minutes: 10,+ avatars: true,+ editor: "code".to_owned(),+ notifications: true,+ profiles: Vec::new(),+ }+ }+}++fn id() -> egui::Id {+ egui::Id::new("gitcraft-settings")+}++impl Settings {+ pub fn get(ctx: &egui::Context) -> Settings {+ ctx.data(|d| d.get_temp::<Settings>(id()))+ .unwrap_or_default()+ }++ pub fn set(&self, ctx: &egui::Context) {+ ctx.data_mut(|d| d.insert_temp(id(), self.clone()));+ ctx.set_zoom_factor(self.ui_scale.clamp(0.7, 2.0));+ }++ /// The settings form. Returns true when something changed.+ pub fn ui(&mut self, ui: &mut Ui) -> bool {+ let t = Tokens::get(ui.ctx());+ let before = self.clone();+ let section = |ui: &mut Ui, title: &str| {+ ui.add_space(10.0);+ ui.label(+ RichText::new(title)+ .font(theme::semibold(10.5))+ .color(t.text_faint),+ );+ ui.add_space(2.0);+ };++ section(ui, "INTERFACE");+ egui::Grid::new("settings-ui").num_columns(2).spacing([16.0, 8.0]).show(ui, |ui| {+ ui.label("Zoom");+ ui.add(egui::Slider::new(&mut self.ui_scale, 0.7..=2.0).step_by(0.05).custom_formatter(|v, _| format!("{:.0} %", v * 100.0)));+ ui.end_row();+ ui.label("Branch column width");+ ui.add(egui::Slider::new(&mut self.refs_width, 180.0..=480.0).step_by(10.0).suffix(" px"));+ ui.end_row();+ ui.label("Graph columns");+ ui.horizontal(|ui| {+ ui.checkbox(&mut self.show_author, "Author");+ ui.checkbox(&mut self.show_date, "Date");+ ui.checkbox(&mut self.show_hash, "Hash");+ });+ ui.end_row();+ ui.label("Avatars");+ ui.checkbox(&mut self.avatars, "Load from Gravatar / GitHub")+ .on_hover_text("Sends an MD5 hash of each author's email to gravatar.com, or asks GitHub for noreply addresses. Cached on disk.");+ ui.end_row();+ ui.label("Notifications");+ ui.checkbox(&mut self.notifications, "When a long operation ends in the background");+ ui.end_row();+ });++ section(ui, "GIT");+ egui::Grid::new("settings-git")+ .num_columns(2)+ .spacing([16.0, 8.0])+ .show(ui, |ui| {+ ui.label("Fetch in the background");+ ui.horizontal(|ui| {+ ui.add(+ egui::DragValue::new(&mut self.auto_fetch_minutes)+ .range(0..=240)+ .suffix(" min"),+ );+ ui.label(RichText::new("0 = off").color(t.text_faint).small());+ });+ ui.end_row();+ ui.label("Editor command");+ ui.add(+ egui::TextEdit::singleline(&mut self.editor)+ .hint_text("code")+ .desired_width(200.0),+ )+ .on_hover_text("Run with a folder or file path, e.g. code, subl, idea");+ ui.end_row();+ });++ section(ui, "TERMINAL");+ egui::Grid::new("settings-term")+ .num_columns(2)+ .spacing([16.0, 8.0])+ .show(ui, |ui| {+ ui.label("Default shell");+ let shells = crate::terminal::available_shells();+ let current = shells+ .iter()+ .find(|s| s.program == self.shell)+ .map(|s| s.label.clone())+ .unwrap_or_else(|| "System default".to_owned());+ egui::ComboBox::from_id_salt("settings-shell")+ .selected_text(current)+ .show_ui(ui, |ui| {+ ui.selectable_value(&mut self.shell, String::new(), "System default");+ for s in &shells {+ ui.selectable_value(&mut self.shell, s.program.clone(), &s.label);+ }+ });+ ui.end_row();+ ui.label("Font size");+ ui.add(egui::Slider::new(&mut self.terminal_font, 9.0..=20.0).step_by(0.5));+ ui.end_row();+ });++ section(ui, "IDENTITIES");+ ui.label(+ RichText::new(+ "Name and email pairs you can apply to a repository from its commit box.",+ )+ .color(t.text_dim)+ .small(),+ );+ let mut remove = None;+ for (i, p) in self.profiles.iter_mut().enumerate() {+ ui.horizontal(|ui| {+ ui.add(+ egui::TextEdit::singleline(&mut p.label)+ .hint_text("Work")+ .desired_width(80.0),+ );+ ui.add(+ egui::TextEdit::singleline(&mut p.name)+ .hint_text("Name")+ .desired_width(140.0),+ );+ ui.add(+ egui::TextEdit::singleline(&mut p.email)+ .hint_text("[email protected]")+ .desired_width(190.0),+ );+ if crate::icons::small_button(ui, "x", "Remove").clicked() {+ remove = Some(i);+ }+ });+ }+ if let Some(i) = remove {+ self.profiles.remove(i);+ }+ if ui.button("Add identity").clicked() {+ self.profiles.push(Profile::default());+ }+ *self != before+ }+}diff --git a/src/terminal.rs b/src/terminal.rsindex 0fe0fc1..9636dfa 100644--- a/src/terminal.rs+++ b/src/terminal.rs@@ -17,7 +17,88 @@ use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system}use crate::theme::{self, Tokens};const SCROLLBACK: usize = 5000;-const FONT_SIZE: f32 = 12.5;++/// A shell the terminal can run.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ShellSpec {+ pub label: String,+ pub program: String,+ pub args: Vec<String>,+}++impl ShellSpec {+ fn new(label: &str, program: &str, args: &[&str]) -> Self {+ Self {+ label: label.to_owned(),+ program: program.to_owned(),+ args: args.iter().map(|a| (*a).to_owned()).collect(),+ }+ }+}++/// The shells installed on this machine, the platform default first.+pub fn available_shells() -> Vec<ShellSpec> {+ let mut list = Vec::new();+ #[cfg(windows)]+ {+ list.push(ShellSpec::new(+ "Windows PowerShell",+ "powershell.exe",+ &["-NoLogo"],+ ));+ if on_path("pwsh.exe") {+ list.insert(0, ShellSpec::new("PowerShell 7", "pwsh.exe", &["-NoLogo"]));+ }+ list.push(ShellSpec::new("Command Prompt", "cmd.exe", &[]));+ for dir in [+ r"C:\Program Files\Git\bin",+ r"C:\Program Files (x86)\Git\bin",+ ] {+ let bash = Path::new(dir).join("bash.exe");+ if bash.is_file() {+ let program = bash.display().to_string();+ list.push(ShellSpec::new("Git Bash", &program, &["--login", "-i"]));+ break;+ }+ }+ if on_path("wsl.exe") {+ list.push(ShellSpec::new("WSL", "wsl.exe", &[]));+ }+ }+ #[cfg(not(windows))]+ {+ if let Ok(shell) = std::env::var("SHELL") {+ let name = Path::new(&shell)+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| shell.clone());+ list.push(ShellSpec::new(&name, &shell, &[]));+ }+ for (label, program) in [+ ("bash", "/bin/bash"),+ ("zsh", "/bin/zsh"),+ ("fish", "/usr/bin/fish"),+ ("sh", "/bin/sh"),+ ] {+ if Path::new(program).is_file() && !list.iter().any(|s| s.program == program) {+ list.push(ShellSpec::new(label, program, &[]));+ }+ }+ }+ list+}++/// The shell to start: the one chosen in the settings when installed, else the default.+pub fn default_shell(ctx: &egui::Context) -> ShellSpec {+ let wanted = crate::settings::Settings::get(ctx).shell;+ let shells = available_shells();+ shells+ .iter()+ .find(|s| !wanted.is_empty() && s.program == wanted)+ .or_else(|| shells.first())+ .cloned()+ .unwrap_or_else(|| ShellSpec::new("sh", "sh", &[]))+}pub struct Terminal {parser: Arc<Mutex<vt100::Parser>>,@@ -32,12 +113,14 @@ pub struct Terminal {scroll: usize,/// Fractional wheel scrolling not yet turned into lines.scroll_rest: f32,+ /// Selected cells, (row, col) on screen, from where the drag started to where it is.+ selection: Option<((u16, u16), (u16, u16))>,pub shell: String,}impl Terminal {- /// Starts the user's shell in `cwd`.- pub fn spawn(cwd: &Path, ctx: &egui::Context) -> Result<Self, String> {+ /// Starts `shell` in `cwd`.+ pub fn spawn(cwd: &Path, shell: &ShellSpec, ctx: &egui::Context) -> Result<Self, String> {let (rows, cols) = (24, 100);let pair = native_pty_system().openpty(PtySize {@@ -47,9 +130,9 @@ impl Terminal {pixel_height: 0,}).map_err(|e| format!("could not open a terminal: {e}"))?;- let (program, args) = shell();+ let program = shell.program.clone();let mut cmd = CommandBuilder::new(&program);- cmd.args(&args);+ cmd.args(&shell.args);cmd.cwd(cwd);cmd.env("TERM", "xterm-256color");cmd.env("COLORTERM", "truecolor");@@ -108,10 +191,7 @@ impl Terminal {});}- let shell = Path::new(&program)- .file_stem()- .map(|s| s.to_string_lossy().into_owned())- .unwrap_or(program);+ let shell = shell.label.clone();Ok(Self {parser,writer,@@ -121,6 +201,7 @@ impl Terminal {size: (rows, cols),scroll: 0,scroll_rest: 0.0,+ selection: None,shell,})}@@ -144,6 +225,7 @@ impl Terminal {let _ = w.write_all(bytes);let _ = w.flush();}+ self.selection = None;// Typing follows the output again.if self.scroll != 0 {self.scroll = 0;@@ -154,7 +236,7 @@ impl Terminal {/// Paints the screen into all of `ui`'s remaining space and handles input.pub fn ui(&mut self, ui: &mut Ui) {let t = Tokens::get(ui.ctx());- let font = theme::mono(FONT_SIZE);+ let font = theme::mono(crate::settings::Settings::get(ui.ctx()).terminal_font);let glyph = ui.painter().layout_no_wrap("M".to_owned(), font.clone(), t.text);@@ -162,9 +244,29 @@ impl Terminal {let rect = ui.available_rect_before_wrap();let id = ui.id().with("terminal");- let resp = ui.interact(rect, id, Sense::click());+ let resp = ui.interact(rect, id, Sense::click_and_drag());ui.allocate_rect(rect, Sense::hover());- if resp.clicked() || resp.secondary_clicked() {+ let inner = rect.shrink2(vec2(8.0, 6.0));+ let cell_at = |p: egui::Pos2| -> (u16, u16) {+ let col = ((p.x - inner.left()) / cell.x).floor().max(0.0) as u16;+ let row = ((p.y - inner.top()) / cell.y).floor().max(0.0) as u16;+ (row.min(self.size.0.saturating_sub(1)), col.min(self.size.1))+ };+ // Drag to select; right-click copies the selection (like Windows Terminal).+ if resp.drag_started()+ && let Some(p) = resp.interact_pointer_pos()+ {+ let c = cell_at(p);+ self.selection = Some((c, c));+ } else if resp.dragged()+ && let (Some(p), Some((start, _))) = (resp.interact_pointer_pos(), self.selection)+ {+ self.selection = Some((start, cell_at(p)));+ }+ if resp.secondary_clicked() && self.copy_selection(ui.ctx()) {+ resp.request_focus();+ } else if resp.clicked() || resp.secondary_clicked() {+ self.selection = None;resp.request_focus();} else if resp.has_focus()&& ui.input(|i| i.pointer.any_pressed())@@ -190,7 +292,6 @@ impl Terminal {}// Size the pty to the panel.- let inner = rect.shrink2(vec2(8.0, 6.0));let cols = ((inner.width() / cell.x).floor() as u16).clamp(2, 1000);let rows = ((inner.height() / cell.y).floor() as u16).clamp(1, 500);if (rows, cols) != self.size {@@ -226,8 +327,13 @@ impl Terminal {self.send(text.as_bytes());}}- // egui turns Ctrl+C / Ctrl+X into clipboard events; the shell wants them.- Event::Copy => self.send(b"\x03"),+ // egui turns Ctrl+C / Ctrl+X into clipboard events: copy a selection,+ // otherwise the shell gets them.+ Event::Copy => {+ if !self.copy_selection(ui.ctx()) {+ self.send(b"\x03");+ }+ }Event::Cut => self.send(b"\x18"),Event::Key {key,@@ -235,7 +341,9 @@ impl Terminal {modifiers,..} => {- if let Some(bytes) = key_bytes(key, modifiers, app_cursor) {+ if key == Key::C && modifiers.ctrl && modifiers.shift {+ self.copy_selection(ui.ctx());+ } else if let Some(bytes) = key_bytes(key, modifiers, app_cursor) {self.send(&bytes);}}@@ -266,8 +374,29 @@ impl Terminal {let (rows, cols) = screen.size();let (rows, cols) = (rows.get(), cols.get());let palette = Palette::new(&t);+ let selected = self+ .selection+ .map(|(a, b)| if a <= b { (a, b) } else { (b, a) });for row in 0..rows {let y = inner.top() + row as f32 * cell.y;+ // Selection highlight, under the text.+ if let Some(((r0, c0), (r1, c1))) = selected+ && row >= r0+ && row <= r1+ {+ let from = if row == r0 { c0 } else { 0 };+ let to = if row == r1 { c1 } else { cols };+ if to > from {+ painter.rect_filled(+ Rect::from_min_size(+ pos2(inner.left() + from as f32 * cell.x, y),+ vec2((to - from) as f32 * cell.x, cell.y),+ ),+ 0.0,+ t.accent.gamma_multiply(0.35),+ );+ }+ }let mut job = LayoutJob::default();let mut col = 0;while col < cols {@@ -305,6 +434,7 @@ impl Terminal {col += 1;}let galley = ui.fonts_mut(|f| f.layout_job(job));+ let _ = selected;painter.galley(pos2(inner.left(), y), galley, t.text);}@@ -341,27 +471,31 @@ impl Terminal {}}-impl Drop for Terminal {- fn drop(&mut self) {- let _ = self.child.kill();+impl Terminal {+ /// Copies the selected text; false when nothing is selected.+ fn copy_selection(&mut self, ctx: &egui::Context) -> bool {+ let Some((a, b)) = self.selection else {+ return false;+ };+ let ((r0, c0), (r1, c1)) = if a <= b { (a, b) } else { (b, a) };+ if (r0, c0) == (r1, c1) {+ return false;+ }+ let text = lock(&self.parser).screen().contents_between(r0, c0, r1, c1);+ let text = text+ .lines()+ .map(str::trim_end)+ .collect::<Vec<_>>()+ .join("\n");+ ctx.copy_text(text);+ self.selection = None;+ true}}-/// The shell to run: PowerShell (7 if installed) on Windows, `$SHELL` elsewhere.-fn shell() -> (String, Vec<String>) {- #[cfg(windows)]- {- let program = if on_path("pwsh.exe") {- "pwsh.exe"- } else {- "powershell.exe"- };- (program.to_owned(), vec!["-NoLogo".to_owned()])- }- #[cfg(not(windows))]- {- let program = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_owned());- (program, Vec::new())+impl Drop for Terminal {+ fn drop(&mut self) {+ let _ = self.child.kill();}}