A visual git client, simple to use yet powerful. Light, fast and debloated.
Rust
feat: branch pills column, worktrees and an integrated terminal
Iván791c788efcfd
diff --git a/Cargo.lock b/Cargo.lockindex d5f5d58..de005d2 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -583,6 +583,12 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"+[[package]]+name = "cfg_aliases"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e"+[[package]]name = "cfg_aliases"version = "0.2.2"@@ -1156,6 +1162,17 @@ version = "0.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693"+[[package]]+name = "filedescriptor"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d"+dependencies = [+ "libc",+ "thiserror 1.0.69",+ "winapi",+]+[[package]]name = "find-msvc-tools"version = "0.1.15"@@ -1327,8 +1344,10 @@ dependencies = ["egui","egui_extras","egui_kittest",+ "portable-pty","rfd","serde",+ "vt100",][[package]]@@ -1377,7 +1396,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325"dependencies = ["bitflags 2.13.2",- "cfg_aliases",+ "cfg_aliases 0.2.2","cgl","dispatch2","glutin_egl_sys",@@ -1401,7 +1420,7 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f"dependencies = [- "cfg_aliases",+ "cfg_aliases 0.2.2","glutin","raw-window-handle","winit",@@ -1573,6 +1592,12 @@ dependencies = ["either",]+[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"+[[package]]name = "jni"version = "0.22.4"@@ -1845,7 +1870,7 @@ dependencies = ["bit-set","bitflags 2.13.2","cfg-if",- "cfg_aliases",+ "cfg_aliases 0.2.2","codespan-reporting","half","hashbrown 0.17.1",@@ -1903,6 +1928,18 @@ dependencies = ["jni-sys 0.3.1",]+[[package]]+name = "nix"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4"+dependencies = [+ "bitflags 2.13.2",+ "cfg-if",+ "cfg_aliases 0.1.1",+ "libc",+]+[[package]]name = "nohash-hasher"version = "0.2.0"@@ -2519,6 +2556,27 @@ dependencies = ["portable-atomic",]+[[package]]+name = "portable-pty"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e"+dependencies = [+ "anyhow",+ "bitflags 1.3.2",+ "downcast-rs",+ "filedescriptor",+ "lazy_static",+ "libc",+ "log",+ "nix",+ "serial2",+ "shared_library",+ "shell-words",+ "winapi",+ "winreg",+]+[[package]]name = "presser"version = "0.3.1"@@ -2885,6 +2943,33 @@ dependencies = ["serde_core",]+[[package]]+name = "serial2"+version = "0.2.39"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c924c7ef58d1fb741cfecb65b9b38a9e049841edd1e419544089f0cbb5a127e7"+dependencies = [+ "cfg-if",+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "shared_library"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11"+dependencies = [+ "lazy_static",+ "libc",+]++[[package]]+name = "shell-words"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77"+[[package]]name = "shlex"version = "2.0.1"@@ -3402,6 +3487,27 @@ version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"+[[package]]+name = "vt100"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb05cdd19ae8707bf6a0a269972c07e6358103a7079faec749dec318a5b3dc23"+dependencies = [+ "itoa",+ "unicode-width",+ "vte",+]++[[package]]+name = "vte"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd"+dependencies = [+ "arrayvec",+ "memchr",+]+[[package]]name = "walkdir"version = "2.5.0"@@ -3648,7 +3754,7 @@ dependencies = ["bitflags 2.13.2","bytemuck","cfg-if",- "cfg_aliases",+ "cfg_aliases 0.2.2","document-features","hashbrown 0.17.1","js-sys",@@ -3679,7 +3785,7 @@ dependencies = ["bit-vec","bitflags 2.13.2","bytemuck",- "cfg_aliases",+ "cfg_aliases 0.2.2","document-features","hashbrown 0.17.1","indexmap",@@ -3753,7 +3859,7 @@ dependencies = ["block2 0.6.2","bytemuck","cfg-if",- "cfg_aliases",+ "cfg_aliases 0.2.2","glow","glutin_wgl_sys","gpu-allocator",@@ -3821,6 +3927,22 @@ dependencies = ["web-sys",]+[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"+[[package]]name = "winapi-util"version = "0.1.11"@@ -3830,6 +3952,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"+[[package]]name = "windows"version = "0.62.2"@@ -4044,7 +4172,7 @@ dependencies = ["block2 0.5.1","bytemuck","calloop 0.13.0",- "cfg_aliases",+ "cfg_aliases 0.2.2","concurrent-queue","core-foundation","core-graphics",@@ -4091,6 +4219,15 @@ dependencies = ["memchr",]+[[package]]+name = "winreg"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d"+dependencies = [+ "winapi",+]+[[package]]name = "wit-bindgen"version = "0.57.1"diff --git a/Cargo.toml b/Cargo.tomlindex f64a2f5..03bcdca 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -11,8 +11,10 @@ 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"] }+portable-pty = "0.9"rfd = "0.17"serde = { version = "1", features = ["derive"] }+vt100 = "0.18"[lints.rust]unsafe_code = "forbid"diff --git a/README.md b/README.mdindex 721c97a..db7cf17 100644--- a/README.md+++ b/README.md@@ -5,6 +5,8 @@ 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@@ -15,8 +17,16 @@ so your config, credentials and hooks apply as usual.a filter. Click jumps to the commit; double-click checks out. Right-click: check out, merge intothe current branch, create a branch, copy the name, delete (with force option), delete from theremote, delete a tag.-- **Graph** (centre): every branch, coloured lanes, ref badges (a local branch in sync with its- remote shows one badge with a cloud), up to 5000 commits, ↑/↓ to move. An *Uncommitted changes*+- **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 itout (detached), cherry-pick, revert, copy hash or message.- **Detail** (right): commit message, author, parents (clickable), changed files with +/−.@@ -27,7 +37,11 @@ so your config, credentials and hooks apply as usual.- **Merges and conflicts**: a merge, cherry-pick or revert that stops on conflicts shows a bannerwith *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, refresh (F5; also when the window regains focus).+ `-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.## Build and run@@ -49,7 +63,8 @@ file dialogs).cargo run --example ui_shot -- path/to/repo /tmp/shot click:500,266 shot key:Escape shot```-Steps: `click:x,y`, `rclick:x,y`, `hover:x,y`, `key:Name`, `type:text`, `wait:ms`, `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.## Layout@@ -60,12 +75,13 @@ Steps: `click:x,y`, `rclick:x,y`, `hover:x,y`, `key:Name`, `type:text`, `wait:ms| `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 pane |-| `src/repo/graph_view.rs` | commit graph |+| `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 and confirmation dialogs |+| `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 |Assets and their licences: [ATTRIBUTION.md](ATTRIBUTION.md).diff --git a/assets/icons/folder-tree.svg b/assets/icons/folder-tree.svgnew file mode 100644index 0000000..9c0aedf--- /dev/null+++ b/assets/icons/folder-tree.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"+>+ <path d="M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z" />+ <path d="M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z" />+ <path d="M3 5a2 2 0 0 0 2 2h3" />+ <path d="M3 3v13a2 2 0 0 0 2 2h3" />+</svg>diff --git a/assets/icons/square-terminal.svg b/assets/icons/square-terminal.svgnew file mode 100644index 0000000..1c6a0f3--- /dev/null+++ b/assets/icons/square-terminal.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="m7 11 2-2-2-2" />+ <path d="M11 13h4" />+ <rect width="18" height="18" x="3" y="3" rx="2" ry="2" />+</svg>diff --git a/docs/screenshot.png b/docs/screenshot.pngnew file mode 100644index 0000000..7b49629Binary files /dev/null and b/docs/screenshot.png differdiff --git a/examples/ui_shot.rs b/examples/ui_shot.rsindex 712dff2..0be27f2 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`, `rclick:x,y`, `hover:x,y`, `key:Escape`, `type:text`, `wait:ms`, `shot`.+//! `click:x,y`, `dclick:x,y`, `rclick:x,y`, `hover:x,y`, `leave` (pointer off the window), `key:Escape`, `type:text`, `wait:ms`, `shot`.//! Each `shot` writes `<out-prefix>-<n>.png`.use std::time::{Duration, Instant};@@ -50,6 +50,27 @@ fn main() {}settle(&mut harness, 400);}+ "dclick" => {+ let pos = point(arg);+ harness.event(Event::PointerMoved(pos));+ harness.step();+ for _ in 0..2 {+ for pressed in [true, false] {+ harness.event(Event::PointerButton {+ pos,+ button: PointerButton::Primary,+ pressed,+ modifiers: Modifiers::NONE,+ });+ }+ harness.step();+ }+ settle(&mut harness, 600);+ }+ "leave" => {+ harness.remove_cursor();+ settle(&mut harness, 200);+ }"hover" => {harness.event(Event::PointerMoved(point(arg)));settle(&mut harness, 200);diff --git a/src/app.rs b/src/app.rsindex b770da4..f543507 100644--- a/src/app.rs+++ b/src/app.rs@@ -606,7 +606,8 @@ impl eframe::App for App {self.poll_clone(&ctx);// Shortcuts.- let modal_open = self.clone_form.is_some();+ // 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| {(i.modifiers.command && i.key_pressed(Key::T),@@ -625,7 +626,7 @@ impl eframe::App for App {let regained = focused && !self.was_focused;self.was_focused = focused;if let Some(Tab::Repo(r)) = self.tabs.get_mut(self.active)- && (refresh || regained)+ && ((refresh && !modal_open) || regained){r.reload(&ctx);}@@ -654,7 +655,13 @@ impl eframe::App for App {let active = self.active;match self.tabs.get_mut(active) {- Some(Tab::Repo(repo)) => repo.ui(ui),+ Some(Tab::Repo(repo)) => {+ repo.ui(ui);+ // A worktree asked to be opened in its own tab.+ if let Some(path) = repo.open_request.take() {+ self.open_repo(&path, &ctx);+ }+ }_ => {egui::CentralPanel::default().frame(egui::Frame::new().fill(t.dock))diff --git a/src/git.rs b/src/git.rsindex cbfc5ff..69ae4c3 100644--- a/src/git.rs+++ b/src/git.rs@@ -448,6 +448,82 @@ impl WorkStatus {}}+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Worktree {+ pub path: PathBuf,+ pub head: String,+ /// Short branch name, `None` when detached.+ pub branch: Option<String>,+ pub bare: bool,+ /// Lock reason (may be empty) when locked.+ pub locked: Option<String>,+ /// Why git would prune it (its folder is gone…).+ pub prunable: Option<String>,+ /// The main worktree (the first one git lists).+ pub main: bool,+ /// The worktree this tab shows.+ pub current: bool,+}++impl Worktree {+ pub fn name(&self) -> String {+ self.path+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| self.path.display().to_string())+ }+}++pub fn worktrees(repo: &Path) -> Result<Vec<Worktree>, String> {+ let out = run(Some(repo), &["worktree", "list", "--porcelain", "-z"])?;+ let mut list = parse_worktrees(&out);+ let here = std::fs::canonicalize(repo).ok();+ for wt in &mut list {+ wt.current = here.is_some() && std::fs::canonicalize(&wt.path).ok() == here;+ }+ Ok(list)+}++/// `worktree list --porcelain -z`: `key value\0` lines, an empty line between worktrees.+fn parse_worktrees(out: &str) -> Vec<Worktree> {+ let mut list: Vec<Worktree> = Vec::new();+ let mut current: Option<Worktree> = None;+ for line in out.split('\0') {+ if line.is_empty() {+ list.extend(current.take());+ continue;+ }+ let (key, value) = line.split_once(' ').unwrap_or((line, ""));+ if key == "worktree" {+ list.extend(current.take());+ current = Some(Worktree {+ path: PathBuf::from(value),+ main: list.is_empty(),+ ..Worktree::default()+ });+ continue;+ }+ let Some(wt) = current.as_mut() else { continue };+ match key {+ "HEAD" => wt.head = value.to_owned(),+ "branch" => {+ wt.branch = Some(+ value+ .strip_prefix("refs/heads/")+ .unwrap_or(value)+ .to_owned(),+ )+ }+ "bare" => wt.bare = true,+ "locked" => wt.locked = Some(value.to_owned()),+ "prunable" => wt.prunable = Some(value.to_owned()),+ _ => {}+ }+ }+ list.extend(current);+ list+}+pub fn status(repo: &Path) -> Result<WorkStatus, String> {let out = run(Some(repo),@@ -559,6 +635,21 @@ mod tests {assert_eq!(s.conflicted.len(), 1);}+ #[test]+ fn worktree_list() {+ let out = "worktree C:/src/app\0HEAD abc\0branch refs/heads/main\0\0\+ worktree C:/src/app-fix\0HEAD def\0detached\0locked moving disks\0\0\+ worktree C:/gone\0HEAD 123\0branch refs/heads/old\0prunable gitdir file points to non-existent location\0\0";+ let list = parse_worktrees(out);+ assert_eq!(list.len(), 3);+ assert!(list[0].main && !list[1].main);+ assert_eq!(list[0].branch.as_deref(), Some("main"));+ assert_eq!(list[1].branch, None);+ assert_eq!(list[1].locked.as_deref(), Some("moving disks"));+ assert!(list[2].prunable.is_some());+ assert_eq!(list[1].name(), "app-fix");+ }+#[test]fn clone_folder_names() {assert_eq!(clone_dir_name("https://github.com/a/b.git"), "b");diff --git a/src/icons.rs b/src/icons.rsindex cab70dd..2768957 100644--- a/src/icons.rs+++ b/src/icons.rs@@ -41,6 +41,8 @@ const SOURCES: &[(&str, &str)] = icons!["plus","refresh-cw","search",+ "square-terminal",+ "folder-tree","tag","undo-2","x",diff --git a/src/lib.rs b/src/lib.rsindex 62ceaa1..c01f722 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -5,4 +5,5 @@ mod git;mod graph;mod icons;mod repo;+mod terminal;mod theme;diff --git a/src/repo/detail.rs b/src/repo/detail.rsindex f0d77bb..3d29248 100644--- a/src/repo/detail.rs+++ b/src/repo/detail.rs@@ -71,15 +71,7 @@ impl RepoTab {ui.horizontal(|ui| {let (rect, _) =ui.allocate_exact_size(vec2(32.0, 32.0), Sense::hover());- let color = t.lane(name_hash(&detail.author));- ui.painter().circle_filled(rect.center(), 16.0, color);- ui.painter().text(- rect.center(),- Align2::CENTER_CENTER,- initials(&detail.author),- theme::semibold(12.5),- egui::Color32::from_rgb(16, 16, 16),- );+ widgets::avatar(ui.painter(), rect.center(), 16.0, &detail.author);ui.vertical(|ui| {ui.spacing_mut().item_spacing.y = 2.0;ui.label(RichText::new(&detail.author).font(theme::medium(12.5)))@@ -370,7 +362,7 @@ impl RepoTab {.desired_width(f32::INFINITY).margin(egui::Margin::symmetric(8, 6)),);- ui.add(+ let body = ui.add(egui::TextEdit::multiline(&mut self.commit_body).hint_text("Description (optional)").desired_width(f32::INFINITY)@@ -393,7 +385,8 @@ impl RepoTab {"Stage all and commit".to_owned()};let can = idle && !self.commit_summary.trim().is_empty() && self.work.conflicted.is_empty();- let shortcut = (summary.has_focus() || ui.ctx().egui_wants_keyboard_input())+ // Only from the message fields, so Ctrl+Enter in the terminal stays the shell's.+ let shortcut = (summary.has_focus() || body.has_focus())&& ui.input(|i| i.modifiers.command && i.key_pressed(Key::Enter));let resp = widgets::primary_button(ui, &label, can, ui.available_width());if (resp.clicked() || (shortcut && can)) && can {@@ -498,19 +491,3 @@ fn empty_hint(ui: &mut Ui, text: &str) {t.text_faint,);}--fn initials(name: &str) -> String {- let mut parts = name.split_whitespace().filter_map(|w| w.chars().next());- let first = parts.next().unwrap_or('?');- let last = parts.next_back();- let mut s: String = first.to_uppercase().collect();- if let Some(l) = last {- s.extend(l.to_uppercase());- }- s-}--fn name_hash(name: &str) -> usize {- name.bytes()- .fold(7usize, |h, b| h.wrapping_mul(31).wrapping_add(b as usize))-}diff --git a/src/repo/dialogs.rs b/src/repo/dialogs.rsindex 9df12b3..5b6c585 100644--- a/src/repo/dialogs.rs+++ b/src/repo/dialogs.rs@@ -1,5 +1,7 @@//! Modal dialogs: create a branch, confirm a destructive operation.+use std::path::{Path, PathBuf};+use egui::{Key, RichText};use super::widgets;@@ -16,6 +18,20 @@ pub enum Dialog {checkout: bool,focus: bool,},+ AddWorktree {+ /// The repository, to suggest a folder next to it.+ repo: PathBuf,+ path: String,+ /// The user typed a path; stop suggesting one.+ path_edited: bool,+ /// Create a new branch instead of checking out an existing one.+ new_branch: bool,+ branch: String,+ new_name: String,+ /// Where a new branch starts (HEAD's commit).+ base: String,+ focus: bool,+ },Confirm {title: String,body: String,@@ -57,6 +73,53 @@ impl Dialog {}}+ /// Add a worktree, checking out `branch` (or a new branch from `base` when `None`).+ pub fn add_worktree(repo: &Path, branch: Option<&str>, base: &str) -> Self {+ let mut dialog = Dialog::AddWorktree {+ repo: repo.to_path_buf(),+ path: String::new(),+ path_edited: false,+ new_branch: branch.is_none(),+ branch: branch.unwrap_or_default().to_owned(),+ new_name: String::new(),+ base: base.to_owned(),+ focus: true,+ };+ dialog.suggest_path();+ dialog+ }++ /// A folder beside the repository named after the branch: `app` + `feature/x` → `app-feature-x`.+ fn suggest_path(&mut self) {+ if let Dialog::AddWorktree {+ repo,+ path,+ path_edited: false,+ new_branch,+ branch,+ new_name,+ ..+ } = self+ {+ let name = if *new_branch {+ new_name.as_str()+ } else {+ branch.as_str()+ };+ let repo_name = repo+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| "worktree".to_owned());+ let folder = if name.trim().is_empty() {+ format!("{repo_name}-worktree")+ } else {+ format!("{repo_name}-{}", name.trim().replace(['/', '\\', ' '], "-"))+ };+ let parent = repo.parent().unwrap_or(repo.as_path());+ *path = parent.join(folder).display().to_string();+ }+ }+pub fn refresh(mut self, what: Refresh) -> Self {if let Dialog::Confirm { refresh, .. } = &mut self {*refresh = what;@@ -67,6 +130,8 @@ impl Dialog {enum Outcome {Open,+ /// Still open; the branch changed, so suggest a folder again.+ Suggest,Cancel,Done(Action),}@@ -87,6 +152,8 @@ impl RepoTab {.frame(frame).backdrop_color(egui::Color32::from_black_alpha(110));+ let local = &self.refs.local;+ let worktrees = &self.worktrees;let response = modal.show(ctx, |ui| {ui.set_width(380.0);let enter = ui.input(|i| i.key_pressed(Key::Enter));@@ -145,6 +212,161 @@ impl RepoTab {});outcome}+ Dialog::AddWorktree {+ path,+ path_edited,+ new_branch,+ branch,+ new_name,+ base,+ focus,+ ..+ } => {+ ui.label(RichText::new("Add worktree").font(theme::semibold(15.0)));+ ui.label(+ RichText::new(+ "A second working folder of this repository, on its own branch.",+ )+ .color(t.text_dim),+ );+ ui.add_space(10.0);+ let mut changed = false;+ ui.horizontal(|ui| {+ changed |= ui+ .radio_value(new_branch, false, "Existing branch")+ .changed();+ changed |= ui.radio_value(new_branch, true, "New branch").changed();+ });+ ui.add_space(4.0);+ if *new_branch {+ let edit = ui.add(+ egui::TextEdit::singleline(new_name)+ .hint_text("feature/my-branch")+ .desired_width(f32::INFINITY)+ .margin(egui::Margin::symmetric(8, 6)),+ );+ if *focus {+ edit.request_focus();+ *focus = false;+ }+ if new_name.contains(' ') {+ *new_name = new_name.replace(' ', "-");+ }+ changed |= edit.changed();+ ui.label(+ RichText::new(format!(+ "Starting at HEAD ({})",+ base.get(..8).unwrap_or(base)+ ))+ .color(t.text_faint)+ .small(),+ );+ } else {+ // Branches that aren't checked out in any worktree yet.+ let busy: Vec<&str> = worktrees+ .iter()+ .filter_map(|w| w.branch.as_deref())+ .collect();+ let free: Vec<&str> = local+ .iter()+ .map(|b| b.name.as_str())+ .filter(|n| !busy.contains(n))+ .collect();+ egui::ComboBox::from_id_salt("worktree-branch")+ .width(ui.available_width())+ .selected_text(if branch.is_empty() {+ "Choose a branch"+ } else {+ branch.as_str()+ })+ .show_ui(ui, |ui| {+ for name in &free {+ if ui.selectable_label(branch == name, *name).clicked() {+ *branch = (*name).to_owned();+ changed = true;+ }+ }+ if free.is_empty() {+ ui.label(+ RichText::new("Every branch is checked out somewhere")+ .color(t.text_faint),+ );+ }+ });+ }+ ui.add_space(8.0);+ ui.label(RichText::new("Folder").color(t.text_dim).small());+ ui.horizontal(|ui| {+ let edit = ui.add(+ egui::TextEdit::singleline(path)+ .desired_width(ui.available_width() - 90.0)+ .margin(egui::Margin::symmetric(8, 6)),+ );+ if edit.changed() {+ *path_edited = true;+ }+ if ui+ .add(egui::Button::new("Browse…").min_size(egui::vec2(80.0, 28.0)))+ .clicked()+ && let Some(dir) = rfd::FileDialog::new()+ .set_title("Worktree folder")+ .pick_folder()+ {+ *path = dir.display().to_string();+ *path_edited = true;+ }+ });+ ui.add_space(12.0);+ let name_ok = if *new_branch {+ !new_name.trim().is_empty()+ } else {+ !branch.is_empty()+ };+ let valid = name_ok && !path.trim().is_empty();+ let mut outcome = Outcome::Open;+ ui.horizontal(|ui| {+ if widgets::primary_button(ui, "Add", valid, 90.0).clicked()+ || (enter && valid)+ {+ let path = path.trim().to_owned();+ let args: Vec<String> = if *new_branch {+ vec![+ "worktree".into(),+ "add".into(),+ "-b".into(),+ new_name.trim().to_owned(),+ path.clone(),+ base.clone(),+ ]+ } else {+ vec![+ "worktree".into(),+ "add".into(),+ path.clone(),+ branch.clone(),+ ]+ };+ outcome = Outcome::Done(Action::Ops {+ label: "Add worktree".to_owned(),+ ops: vec![args],+ refresh: Refresh::All,+ });+ }+ if ui+ .add(egui::Button::new("Cancel").min_size(egui::vec2(80.0, 30.0)))+ .clicked()+ {+ outcome = Outcome::Cancel;+ }+ });+ if changed {+ outcome = match outcome {+ Outcome::Open => Outcome::Suggest,+ other => other,+ };+ }+ outcome+ }Dialog::Confirm {title,body,@@ -202,6 +424,7 @@ impl RepoTab {Outcome::Cancel => self.dialog = None,Outcome::Open if response.should_close() => self.dialog = None,Outcome::Open => {}+ Outcome::Suggest => dialog.suggest_path(),}}}diff --git a/src/repo/graph_view.rs b/src/repo/graph_view.rsindex 9e76c46..04e4fd0 100644--- a/src/repo/graph_view.rs+++ b/src/repo/graph_view.rs@@ -5,6 +5,7 @@ use egui::{epaint::CubicBezierShape, pos2, vec2,};+use super::widgets;use super::{Action, Dialog, Refresh, RepoTab, WIP_HASH, ops};use crate::git::Refs;use crate::icons;@@ -15,6 +16,9 @@ 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 AVATAR_D: f32 = 20.0;impl RepoTab {pub(super) fn graph_view(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {@@ -74,8 +78,9 @@ impl RepoTab {let y = header.center().y;let font = theme::semibold(10.5);for (x, label) in [- (header.left() + 10.0, "GRAPH"),- (header.left() + graph_w + 6.0, "DESCRIPTION"),+ (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"),] {@@ -200,19 +205,75 @@ impl RepoTab {painter.rect_filled(rect, 0.0, t.hover);}- // Graph.+ let (top, mid, bottom) = (rect.top(), rect.center().y, rect.bottom());+ let gx = rect.left() + REFS_W;+ let x = |lane: usize| gx + 6.0 + lane as f32 * LANE_W + LANE_W / 2.0;let row_color = self.graph.rows.get(i).map(|r| t.lane(r.col)).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.+ 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 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 pill = ref_pill(+ ui,+ &rp,+ pos2(rect.left() + 8.0, mid),+ first,+ row_color,+ max_w,+ );+ let mut end = pill.right();+ if more > 0 {+ let r = Rect::from_min_size(pos2(end + 3.0, mid - 10.0), vec2(more_w - 3.0, 20.0));+ rp.rect_filled(+ r,+ CornerRadius::same(t.radius as u8),+ row_color.lerp_to_gamma(Color32::BLACK, 0.35),+ );+ rp.text(+ r.center(),+ Align2::CENTER_CENTER,+ format!("+{more}"),+ theme::medium(10.5),+ Color32::WHITE,+ );+ end = r.right();+ }+ // Avatar of whoever made the tip commit.+ let avatar = pos2(end + 5.0 + AVATAR_D / 2.0, mid);+ // Connector to the dot, drawn first so the lanes cross over it.+ painter.line_segment(+ [pos2(avatar.x, 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);+ 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 {}",+ lines.join("\n"),+ commit.author+ ));+ }+ }++ // Graph.if let Some(row) = self.graph.rows.get(i) {let gp = painter.with_clip_rect(- rect.intersect(Rect::from_min_size(rect.min, vec2(graph_w, ROW_H))),+ rect.intersect(Rect::from_min_size(pos2(gx, top), vec2(graph_w, ROW_H))),);- let x = |lane: usize| rect.left() + 6.0 + lane as f32 * LANE_W + LANE_W / 2.0;- let (top, mid, bottom) = (rect.top(), rect.center().y, rect.bottom());let node = pos2(x(row.col), mid);let width = 2.0;@@ -250,8 +311,7 @@ impl RepoTab {}}- let mid = rect.center().y;- let mut x = rect.left() + graph_w + 6.0;+ let mut x = gx + graph_w + 6.0;let text_right = rect.right() - DATE_W - AUTHOR_W - 10.0;if is_wip {@@ -281,13 +341,6 @@ impl RepoTab {return resp;}- // Ref badges, then the summary.- for badge in badges(&commit.refs, &self.refs) {- if x > text_right - 40.0 {- break;- }- x += ref_badge(ui, &painter, pos2(x, mid), &badge, row_color, &t) + 4.0;- }painter.with_clip_rect(Rect::from_min_max(pos2(x, rect.top()),@@ -324,158 +377,224 @@ impl RepoTab {}}-/// One ref badge in the graph.+/// One pill in the refs column: a branch (local, remote or both), a tag or a detached HEAD.+#[derive(Debug)]struct Badge {label: String,kind: BadgeKind,- /// The local branch is checked out.+ /// The branch exists locally.+ local: bool,+ /// Remotes that have the branch at this commit.+ remotes: Vec<String>,+ /// The checked-out branch (or a detached HEAD).head: bool,- /// A local branch whose remote counterpart points at the same commit.- synced: bool,}-#[derive(PartialEq)]+#[derive(Debug, PartialEq)]enum BadgeKind {- Local,- Remote,+ Branch,Tag,DetachedHead,}-/// Turns `git log --format=%D` decorations into badges, folding `origin/x` into `x` when both-/// point at the same commit.+impl Badge {+ fn describe(&self) -> String {+ match self.kind {+ BadgeKind::Tag => format!("tag {}", self.label),+ BadgeKind::DetachedHead => "HEAD (detached)".to_owned(),+ BadgeKind::Branch => {+ let mut places = Vec::new();+ if self.local {+ places.push(if self.head {+ "local, checked out".to_owned()+ } else {+ "local".to_owned()+ });+ }+ places.extend(self.remotes.iter().cloned());+ format!("{} — {}", self.label, places.join(", "))+ }+ }+ }+}++/// Turns `git log --format=%D` decorations into pills: `x` and `origin/x` at the same commit+/// become one pill marked local and remote.fn badges(decorations: &[String], refs: &Refs) -> Vec<Badge> {- let is_remote = |d: &str| {- refs.remotes.iter().any(|(remote, _)| {+ let remote_of = |d: &str| {+ refs.remotes.iter().find_map(|(remote, _)| {d.strip_prefix(remote.as_str())- .is_some_and(|r| r.starts_with('/'))+ .and_then(|r| r.strip_prefix('/'))+ .map(|branch| (remote.clone(), branch.to_owned()))})};- let mut out = Vec::new();- let locals: Vec<&str> = decorations- .iter()- .filter_map(|d| {- let d = d.strip_prefix("HEAD -> ").unwrap_or(d);- (!d.starts_with("tag: ") && d != "HEAD" && !is_remote(d)).then_some(d)- })- .collect();- for d in decorations {- // `origin/HEAD` only says which branch the remote defaults to.- if is_remote(d) && d.ends_with("/HEAD") {- continue;+ fn branch(out: &mut Vec<Badge>, name: &str) -> usize {+ match out+ .iter()+ .position(|b| b.kind == BadgeKind::Branch && b.label == name)+ {+ Some(i) => i,+ None => {+ out.push(Badge {+ label: name.to_owned(),+ kind: BadgeKind::Branch,+ local: false,+ remotes: Vec::new(),+ head: false,+ });+ out.len() - 1+ }}- if let Some(branch) = d.strip_prefix("HEAD -> ") {- out.push(Badge {- label: branch.to_owned(),- kind: BadgeKind::Local,- head: true,- synced: false,- });+ }+ let mut out: Vec<Badge> = Vec::new();+ for d in decorations {+ if let Some(name) = d.strip_prefix("HEAD -> ") {+ let i = branch(&mut out, name);+ if let Some(b) = out.get_mut(i) {+ b.local = true;+ b.head = true;+ }} else if d == "HEAD" {out.push(Badge {label: "HEAD".to_owned(),kind: BadgeKind::DetachedHead,+ local: false,+ remotes: Vec::new(),head: true,- synced: false,});} else if let Some(tag) = d.strip_prefix("tag: ") {out.push(Badge {label: tag.to_owned(),kind: BadgeKind::Tag,+ local: false,+ remotes: Vec::new(),head: false,- synced: false,});- } else if is_remote(d) {- let short = d.split_once('/').map(|(_, b)| b).unwrap_or(d);- if !locals.contains(&short) {- out.push(Badge {- label: d.clone(),- kind: BadgeKind::Remote,- head: false,- synced: false,- });+ } else if let Some((remote, name)) = remote_of(d) {+ // `origin/HEAD` only says which branch the remote defaults to.+ if name == "HEAD" {+ continue;+ }+ let i = branch(&mut out, &name);+ if let Some(b) = out.get_mut(i) {+ b.remotes.push(remote);}} else {- out.push(Badge {- label: d.clone(),- kind: BadgeKind::Local,- head: false,- synced: false,- });- }- }- // Mark locals whose remote twin was folded in.- for badge in &mut out {- if badge.kind == BadgeKind::Local {- badge.synced = decorations.iter().any(|d| {- is_remote(d) && d.split_once('/').map(|(_, b)| b) == Some(badge.label.as_str())- });+ let i = branch(&mut out, d);+ if let Some(b) = out.get_mut(i) {+ b.local = true;+ }}}- // Checked-out branch first.- out.sort_by_key(|b| !b.head);+ // Checked out first, then local branches, remote-only ones, tags.+ out.sort_by_key(|b| match b.kind {+ _ if b.head => 0,+ BadgeKind::Branch if b.local => 1,+ BadgeKind::Branch => 2,+ BadgeKind::Tag => 3,+ BadgeKind::DetachedHead => 4,+ });out}-/// Paints a badge at `left_center`; returns its width.-fn ref_badge(+/// Paints a pill with white text and icons, at most `max_w` wide; returns its rect.+fn ref_pill(ui: &Ui,painter: &egui::Painter,left_center: Pos2,badge: &Badge,lane: Color32,- t: &Tokens,-) -> f32 {- let (fill, text) = match badge.kind {- BadgeKind::Local => (lane, Color32::from_rgb(16, 16, 16)),- BadgeKind::Remote => (lane.gamma_multiply(0.25), t.text),- BadgeKind::Tag => (t.field, t.text),- BadgeKind::DetachedHead => (t.warning, Color32::from_rgb(16, 16, 16)),+ max_w: f32,+) -> Rect {+ const ICON: f32 = 15.0;+ let t = Tokens::get(ui.ctx());+ let white = Color32::WHITE;+ let fill = match badge.kind {+ BadgeKind::Branch if badge.local => lane,+ // Only on a remote: a darker shade of the lane.+ BadgeKind::Branch => lane.lerp_to_gamma(Color32::BLACK, 0.35),+ BadgeKind::Tag => Color32::from_rgb(104, 104, 112),+ BadgeKind::DetachedHead => t.warning,};- let icon = match badge.kind {- _ if badge.head => Some("check"),- BadgeKind::Tag => Some("tag"),- BadgeKind::Remote => Some("cloud"),- _ => None,+ let mut lead = Vec::new();+ let mut trail = Vec::new();+ match badge.kind {+ BadgeKind::Tag => lead.push("tag"),+ BadgeKind::DetachedHead => lead.push("check"),+ BadgeKind::Branch => {+ if badge.head {+ lead.push("check");+ }+ // Where the branch lives: this computer, a remote, or both.+ if badge.local {+ trail.push("laptop");+ }+ if !badge.remotes.is_empty() {+ trail.push("cloud");+ }+ }+ }+ let font = if badge.head {+ theme::semibold(11.0)+ } else {+ theme::medium(11.0)};- let font = theme::medium(11.0);- let galley = painter.layout_no_wrap(badge.label.clone(), font, text);- let icon_w = if icon.is_some() { 14.0 } else { 0.0 };- let synced_w = if badge.synced { 16.0 } else { 0.0 };- let w = galley.size().x + 12.0 + icon_w + synced_w;- let r = Rect::from_min_size(pos2(left_center.x, left_center.y - 9.0), vec2(w, 18.0));+ let icons_w = (lead.len() + trail.len()) as f32 * ICON;+ let text_room = (max_w - 16.0 - icons_w).max(16.0);+ let label = truncate(painter, &badge.label, &font, text_room);+ let galley = painter.layout_no_wrap(label, font, white);+ let w = (galley.size().x + 16.0 + icons_w).min(max_w);+ let r = Rect::from_min_size(pos2(left_center.x, left_center.y - 10.0), vec2(w, 20.0));painter.rect_filled(r, CornerRadius::same(t.radius as u8), fill);- if badge.kind == BadgeKind::Tag {- painter.rect_stroke(- r,- CornerRadius::same(t.radius as u8),- Stroke::new(1.0, t.field_border),- egui::StrokeKind::Inside,- );- }- let mut x = r.left() + 6.0;- if let Some(icon) = icon {+ let mut x = r.left() + 7.0;+ for icon in lead {icons::paint(ui,- Rect::from_center_size(pos2(x + 5.0, r.center().y), vec2(12.0, 12.0)),+ Rect::from_center_size(pos2(x + 6.0, r.center().y), vec2(12.0, 12.0)),icon,11.0,- text,+ white,);- x += icon_w;+ x += ICON;}let gw = galley.size().x;- painter.galley(pos2(x, r.center().y - galley.size().y / 2.0), galley, text);- if badge.synced {+ painter.galley(pos2(x, r.center().y - galley.size().y / 2.0), galley, white);+ x += gw + 1.0;+ for icon in trail {icons::paint(ui,- Rect::from_center_size(pos2(x + gw + 9.0, r.center().y), vec2(12.0, 12.0)),- "cloud",+ Rect::from_center_size(pos2(x + 8.0, r.center().y), vec2(12.0, 12.0)),+ icon,11.0,- text,+ white,);+ x += ICON;}- w+ r+}++/// `text`, cut with an ellipsis to fit `width`.+fn truncate(painter: &egui::Painter, text: &str, font: &FontId, width: f32) -> String {+ let fits = |s: &str| {+ painter+ .layout_no_wrap(s.to_owned(), font.clone(), Color32::WHITE)+ .size()+ .x+ <= width+ };+ if fits(text) {+ return text.to_owned();+ }+ let chars: Vec<char> = text.chars().collect();+ let mut n = chars.len();+ while n > 1 {+ n -= 1;+ let s: String = chars.iter().take(n).collect::<String>() + "…";+ if fits(&s) {+ return s;+ }+ }+ "…".to_owned()}/// A small rounded count label; returns its width.@@ -529,8 +648,8 @@ mod tests {#[test]fn remote_twin_folds_into_local_badge() {let decos = [- "HEAD -> main","origin/main",+ "HEAD -> main","origin/HEAD","origin/dev","tag: v1",@@ -538,14 +657,16 @@ mod tests {.map(String::from);let b = badges(&decos, &refs_with_origin());let labels: Vec<&str> = b.iter().map(|b| b.label.as_str()).collect();- assert_eq!(labels, vec!["main", "origin/dev", "v1"]);- assert!(b[0].head && b[0].synced);+ assert_eq!(labels, vec!["main", "dev", "v1"]);+ assert!(b[0].head && b[0].local && b[0].remotes == ["origin"]);+ assert!(!b[1].local && b[1].remotes == ["origin"]);+ assert_eq!(b[2].kind, BadgeKind::Tag);}#[test]fn local_branch_with_slash_is_not_remote() {let decos = ["feature/x".to_owned()];let b = badges(&decos, &refs_with_origin());- assert!(b[0].kind == BadgeKind::Local && !b[0].synced);+ assert!(b[0].kind == BadgeKind::Branch && b[0].local && b[0].remotes.is_empty());}}diff --git a/src/repo/mod.rs b/src/repo/mod.rsindex cd7c97b..a1fd755 100644--- a/src/repo/mod.rs+++ b/src/repo/mod.rs@@ -14,9 +14,10 @@ use std::sync::mpsc::{Receiver, Sender, channel};use egui::{Key, Ui};-use crate::git::{self, Commit, CommitDetail, InProgress, Refs, StatusFile, WorkStatus};+use crate::git::{self, Commit, CommitDetail, InProgress, Refs, StatusFile, WorkStatus, Worktree};use crate::graph::{self, Graph};use crate::icons;+use crate::terminal::Terminal;use crate::theme::Tokens;pub use dialogs::Dialog;@@ -42,6 +43,7 @@ struct Loaded {refs: Refs,history: Vec<Commit>,work: WorkStatus,+ worktrees: Vec<Worktree>,}/// What to re-read after an operation.@@ -80,6 +82,10 @@ pub(crate) enum Action {Dialog(Dialog),Commit,Fetch,+ /// Open a folder (a worktree) in its own tab.+ OpenTab(PathBuf),+ ToggleTerminal,+ RestartTerminal,Pull,Push,Reload,@@ -117,6 +123,12 @@ pub struct RepoTab {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>,+ terminal_open: bool,+ terminal_error: Option<String>,+ /// A folder the app should open in a new tab (taken by `App`).+ pub open_request: Option<PathBuf>,}impl RepoTab {@@ -154,6 +166,11 @@ impl RepoTab {status: None,branch_filter: String::new(),focus_wip: false,+ worktrees: Vec::new(),+ terminal: None,+ terminal_open: false,+ terminal_error: None,+ open_request: None,};tab.reload(ctx);tab@@ -175,10 +192,13 @@ impl RepoTab {let refs = git::refs(&path)?;let history = git::log(&path)?;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();Ok(Box::new(Loaded {refs,history,work,+ worktrees,}))})())});@@ -467,6 +487,7 @@ impl RepoTab {self.refs = loaded.refs;self.history = loaded.history;self.work = loaded.work;+ self.worktrees = loaded.worktrees;self.rebuild(ctx);}Err(e) => self.load_error = Some(e),@@ -554,6 +575,17 @@ impl RepoTab {Action::Pull => self.run_ops("Pull", ops(&[&["pull", "--ff-only"]]), Refresh::All, ctx),Action::Push => self.push(ctx),Action::Reload => self.reload(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);+ }+ }+ Action::RestartTerminal => {+ self.terminal = None;+ self.start_terminal(ctx);+ }}}@@ -592,6 +624,14 @@ impl RepoTab {.size_range(280.0..=900.0).frame(side).show(ui, |ui| self.detail_panel(ui, &mut acts));+ if self.terminal_open {+ egui::Panel::bottom("repo_terminal")+ .resizable(true)+ .default_size(260.0)+ .size_range(90.0..=900.0)+ .frame(egui::Frame::new().fill(t.card))+ .show(ui, |ui| self.terminal_panel(ui, &mut acts));+ }egui::CentralPanel::default().frame(egui::Frame::new().fill(t.dock)).show(ui, |ui| {@@ -640,6 +680,20 @@ impl RepoTab {{acts.push(Action::Dialog(Dialog::create_branch(&head, "HEAD")));}+ 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),+ );+ }+ if terminal.clicked() {+ acts.push(Action::ToggleTerminal);+ }widgets::toolbar_separator(ui);if icons::tool_button(ui, "refresh-cw", "", !self.loading).on_hover_text("Reload (F5)")@@ -702,6 +756,57 @@ 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.+ 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);+ }+ });+ 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;+ }+ let Some(term) = &mut self.terminal 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);+ }+ });+ return;+ }+ term.ui(ui);+ }+}+fn abort_action(state: InProgress) -> Action {Action::Ops {label: format!("Abort {}", state.label().to_lowercase()),diff --git a/src/repo/sidebar.rs b/src/repo/sidebar.rsindex 1900ab2..56b6925 100644--- a/src/repo/sidebar.rs+++ b/src/repo/sidebar.rs@@ -39,21 +39,56 @@ impl RepoTab {if widgets::section(ui, "local", "laptop", "LOCAL", local.len(), true) {for b in local {let (ahead, behind) = b.ahead_behind();- let r = branch_row(ui, &b.name, b.is_head, ahead, behind, b.upstream_gone());+ // 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 = r.on_hover_text(format!("{tip}\nDouble-click to check out"));- if r.double_clicked() && !b.is_head && idle {+ 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| {- if ui.add_enabled(!b.is_head && idle, egui::Button::new("Check out")).clicked() {- acts.push(Action::Checkout(b.name.clone()));+ 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)));+ }}merge_item(ui, acts, &b.name, current.as_deref(), b.is_head || !idle);if ui.button("Create branch here…").clicked() {@@ -93,7 +128,7 @@ impl RepoTab {.name.strip_prefix(&format!("{remote}/")).unwrap_or(&b.name);- let r = branch_row(ui, short, false, 0, 0, false)+ 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()));@@ -127,6 +162,8 @@ impl RepoTab {}}+ self.worktree_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 {@@ -154,6 +191,167 @@ impl RepoTab {}}+impl RepoTab {+ fn worktree_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,+ "worktrees",+ "folder-tree",+ "WORKTREES",+ self.worktrees.len(),+ true,+ Some(("plus", "Add a worktree…")),+ );+ if add && idle {+ acts.push(Action::Dialog(Dialog::add_worktree(+ &self.path,+ None,+ &self.refs.head,+ )));+ }+ if !open {+ return;+ }+ let any_prunable = self.worktrees.iter().any(|w| w.prunable.is_some());+ for wt in &self.worktrees {+ let (rect, r) =+ ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());+ let painter = ui.painter_at(rect);+ if wt.current {+ painter.rect_filled(rect, 0.0, t.accent.gamma_multiply(0.14));+ }+ if r.hovered() {+ painter.rect_filled(rect, 0.0, t.hover);+ }+ let y = rect.center().y;+ let icon = if wt.current { "check" } else { "folder-git-2" };+ icons::paint(+ ui,+ Rect::from_center_size(pos2(rect.left() + 34.0, y), vec2(16.0, 16.0)),+ icon,+ 14.0,+ if wt.current { t.accent } else { t.text_faint },+ );+ let font = if wt.current {+ theme::semibold(12.5)+ } else {+ egui::FontId::proportional(12.5)+ };+ let mut right = rect.right() - 8.0;+ for (on, label, color) in [+ (wt.prunable.is_some(), "missing", t.danger),+ (wt.locked.is_some(), "locked", t.warning),+ (wt.main, "main", t.text_faint),+ ] {+ if on {+ let r = painter.text(+ pos2(right, y),+ Align2::RIGHT_CENTER,+ label,+ theme::medium(10.5),+ color,+ );+ right = r.left() - 6.0;+ }+ }+ let clip =+ painter.with_clip_rect(Rect::from_min_max(rect.min, pos2(right, rect.bottom())));+ clip.text(+ pos2(rect.left() + 48.0, y - 7.0),+ Align2::LEFT_CENTER,+ wt.name(),+ font,+ t.text,+ );+ let sub = match (&wt.branch, wt.bare) {+ (_, true) => "bare".to_owned(),+ (Some(branch), _) => branch.clone(),+ (None, _) => format!("detached at {}", wt.head.get(..8).unwrap_or(&wt.head)),+ };+ clip.text(+ pos2(rect.left() + 48.0, y + 8.0),+ Align2::LEFT_CENTER,+ sub,+ egui::FontId::proportional(11.0),+ t.text_faint,+ );++ let mut tip = wt.path.display().to_string();+ if let Some(reason) = wt.locked.as_deref().filter(|r| !r.is_empty()) {+ tip.push_str(&format!("\nLocked: {reason}"));+ }+ if let Some(reason) = &wt.prunable {+ tip.push_str(&format!("\nMissing: {reason}"));+ }+ if !wt.current {+ tip.push_str("\nDouble-click to open in a tab");+ }+ let r = r.on_hover_text(tip);+ if r.double_clicked() && !wt.current && wt.prunable.is_none() {+ acts.push(Action::OpenTab(wt.path.clone()));+ } else if r.clicked() && !wt.head.is_empty() {+ acts.push(Action::SelectHash(wt.head.clone()));+ }+ let path = wt.path.display().to_string();+ r.context_menu(|ui| {+ if ui+ .add_enabled(!wt.current && wt.prunable.is_none(), egui::Button::new("Open in a tab"))+ .clicked()+ {+ acts.push(Action::OpenTab(wt.path.clone()));+ }+ if ui.button("Copy path").clicked() {+ ui.ctx().copy_text(path.clone());+ }+ if !wt.main {+ ui.separator();+ let (label, args) = if wt.locked.is_some() {+ ("Unlock", vec!["worktree", "unlock", path.as_str()])+ } else {+ ("Lock", vec!["worktree", "lock", path.as_str()])+ };+ if ui.add_enabled(idle, egui::Button::new(label)).clicked() {+ acts.push(Action::Ops {+ label: format!("{label} worktree {}", wt.name()),+ ops: ops(&[&args]),+ refresh: Refresh::All,+ });+ }+ if ui+ .add_enabled(idle && !wt.current, egui::Button::new("Remove…"))+ .on_disabled_hover_text("Open another worktree to remove this one")+ .clicked()+ {+ acts.push(Action::Dialog(Dialog::confirm(+ "Remove worktree",+ format!(+ "Remove the worktree at {path}? Its folder is deleted; the branch stays."+ ),+ "Remove",+ ops(&[&["worktree", "remove", &path]]),+ Some((+ "Force, even with uncommitted changes or locked".to_owned(),+ ops(&[&["worktree", "remove", "--force", "--force", &path]]),+ )),+ )));+ }+ }+ if any_prunable {+ ui.separator();+ if ui.add_enabled(idle, egui::Button::new("Prune missing worktrees")).clicked() {+ acts.push(Action::Ops {+ label: "Prune worktrees".into(),+ ops: ops(&[&["worktree", "prune"]]),+ refresh: Refresh::All,+ });+ }+ }+ });+ }+ }+}+fn merge_item(ui: &mut Ui,acts: &mut Vec<Action>,@@ -185,6 +383,7 @@ fn branch_row(ahead: u32,behind: u32,gone: bool,+ in_worktree: bool,) -> Response {let t = Tokens::get(ui.ctx());let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());@@ -205,6 +404,11 @@ fn branch_row(let mut right = rect.right() - 8.0;let small = theme::mono(11.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);+ right = ir.left() - 6.0;+ }if gone {let r = painter.text(pos2(right, y),diff --git a/src/repo/widgets.rs b/src/repo/widgets.rsindex c96d6d7..8b149ec 100644--- a/src/repo/widgets.rs+++ b/src/repo/widgets.rs@@ -80,6 +80,20 @@ pub fn section(count: usize,default_open: bool,) -> bool {+ section_with_button(ui, id, icon, title, count, default_open, None).0+}++/// [`section`] with an icon button on the header, left of the count: `(icon, tooltip)`.+/// Returns (open, button clicked).+pub fn section_with_button(+ ui: &mut Ui,+ id: &str,+ icon: &str,+ title: &str,+ count: usize,+ default_open: bool,+ button: Option<(&str, &str)>,+) -> (bool, bool) {let t = Tokens::get(ui.ctx());let id = ui.id().with(("section", id));let mut open = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(default_open);@@ -126,7 +140,19 @@ pub fn section(theme::medium(11.0),t.text_faint,);- open+ let mut clicked = false;+ if let Some((icon, tooltip)) = button {+ let r = Rect::from_center_size(pos2(rect.right() - 36.0, y), vec2(20.0, 20.0));+ let b = ui+ .interact(r, id.with("button"), Sense::click())+ .on_hover_text(tooltip);+ if b.hovered() {+ ui.painter().rect_filled(r, t.radius_sm, t.pressed);+ }+ icons::paint(ui, r, icon, 13.0, if b.hovered() { t.text } else { t.icon });+ clicked = b.clicked();+ }+ (open, clicked)}pub fn status_color(t: &Tokens, code: char) -> Color32 {@@ -306,3 +332,32 @@ pub fn primary_button(ui: &mut Ui, text: &str, enabled: bool, width: f32) -> Res.min_size(vec2(width, 30.0)),)}++/// 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());+ painter.circle_filled(center, radius, t.lane(name_hash(name)));+ painter.text(+ center,+ Align2::CENTER_CENTER,+ initials(name),+ theme::semibold(radius * 0.8),+ Color32::WHITE,+ );+}++fn initials(name: &str) -> String {+ let mut parts = name.split_whitespace().filter_map(|w| w.chars().next());+ let first = parts.next().unwrap_or('?');+ let last = parts.next_back();+ let mut s: String = first.to_uppercase().collect();+ if let Some(l) = last {+ s.extend(l.to_uppercase());+ }+ s+}++fn name_hash(name: &str) -> usize {+ name.bytes()+ .fold(7usize, |h, b| h.wrapping_mul(31).wrapping_add(b as usize))+}diff --git a/src/terminal.rs b/src/terminal.rsnew file mode 100644index 0000000..0fe0fc1--- /dev/null+++ b/src/terminal.rs@@ -0,0 +1,566 @@+//! An integrated terminal: the user's shell in a pseudo-terminal (ConPTY on Windows), its output+//! interpreted by `vt100` and painted with egui.++use std::io::{Read, Write};+use std::num::NonZeroU16;+use std::path::Path;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, MutexGuard};++use egui::{+ Color32, Event, FontId, Key, Modifiers, Rect, Sense, Stroke, Ui, pos2,+ text::{LayoutJob, TextFormat},+ vec2,+};+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;++pub struct Terminal {+ parser: Arc<Mutex<vt100::Parser>>,+ /// Shared with the reader thread, which answers the shell's cursor-position queries.+ writer: Arc<Mutex<Box<dyn Write + Send>>>,+ master: Box<dyn MasterPty + Send>,+ child: Box<dyn Child + Send + Sync>,+ exited: Arc<AtomicBool>,+ /// (rows, cols) the pty was last sized to.+ size: (u16, u16),+ /// Lines scrolled back into history (0 = following the output).+ scroll: usize,+ /// Fractional wheel scrolling not yet turned into lines.+ scroll_rest: f32,+ pub shell: String,+}++impl Terminal {+ /// Starts the user's shell in `cwd`.+ pub fn spawn(cwd: &Path, ctx: &egui::Context) -> Result<Self, String> {+ let (rows, cols) = (24, 100);+ let pair = native_pty_system()+ .openpty(PtySize {+ rows,+ cols,+ pixel_width: 0,+ pixel_height: 0,+ })+ .map_err(|e| format!("could not open a terminal: {e}"))?;+ let (program, args) = shell();+ let mut cmd = CommandBuilder::new(&program);+ cmd.args(&args);+ cmd.cwd(cwd);+ cmd.env("TERM", "xterm-256color");+ cmd.env("COLORTERM", "truecolor");+ let child = pair+ .slave+ .spawn_command(cmd)+ .map_err(|e| format!("could not start {program}: {e}"))?;+ // The child holds its own handle; ours would keep the pty open after it exits.+ drop(pair.slave);+ let mut reader = pair+ .master+ .try_clone_reader()+ .map_err(|e| format!("terminal: {e}"))?;+ let writer = Arc::new(Mutex::new(+ pair.master+ .take_writer()+ .map_err(|e| format!("terminal: {e}"))?,+ ));++ let parser = Arc::new(Mutex::new(vt100::Parser::new(+ nz(rows),+ nz(cols),+ SCROLLBACK,+ )));+ let exited = Arc::new(AtomicBool::new(false));+ {+ let parser = Arc::clone(&parser);+ let exited = Arc::clone(&exited);+ let writer = Arc::clone(&writer);+ let ctx = ctx.clone();+ std::thread::spawn(move || {+ let mut buf = [0u8; 16 * 1024];+ loop {+ match reader.read(&mut buf) {+ Ok(0) | Err(_) => break,+ Ok(n) => {+ let bytes = buf.get(..n).unwrap_or_default();+ let mut parser = lock(&parser);+ parser.process(bytes);+ // ConPTY (and some programs) ask where the cursor is and wait for+ // the answer before printing anything (DSR 6 → CPR).+ if contains(bytes, b"[6n") {+ let (row, col) = parser.screen().cursor_position();+ let reply = format!("[{};{}R", row + 1, col + 1);+ let mut w = lock(&writer);+ let _ = w.write_all(reply.as_bytes());+ let _ = w.flush();+ }+ drop(parser);+ ctx.request_repaint();+ }+ }+ }+ exited.store(true, Ordering::Relaxed);+ ctx.request_repaint();+ });+ }++ let shell = Path::new(&program)+ .file_stem()+ .map(|s| s.to_string_lossy().into_owned())+ .unwrap_or(program);+ Ok(Self {+ parser,+ writer,+ master: pair.master,+ child,+ exited,+ size: (rows, cols),+ scroll: 0,+ scroll_rest: 0.0,+ shell,+ })+ }++ pub fn has_exited(&mut self) -> bool {+ if !self.exited.load(Ordering::Relaxed)+ && let Ok(Some(_)) = self.child.try_wait()+ {+ // ConPTY doesn't always end the read when the shell exits.+ self.exited.store(true, Ordering::Relaxed);+ }+ self.exited.load(Ordering::Relaxed)+ }++ fn send(&mut self, bytes: &[u8]) {+ if bytes.is_empty() {+ return;+ }+ {+ let mut w = lock(&self.writer);+ let _ = w.write_all(bytes);+ let _ = w.flush();+ }+ // Typing follows the output again.+ if self.scroll != 0 {+ self.scroll = 0;+ lock(&self.parser).screen_mut().set_scrollback(0);+ }+ }++ /// 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 glyph = ui+ .painter()+ .layout_no_wrap("M".to_owned(), font.clone(), t.text);+ let cell = vec2(glyph.size().x.max(1.0), glyph.size().y.max(1.0));++ let rect = ui.available_rect_before_wrap();+ let id = ui.id().with("terminal");+ let resp = ui.interact(rect, id, Sense::click());+ ui.allocate_rect(rect, Sense::hover());+ if resp.clicked() || resp.secondary_clicked() {+ resp.request_focus();+ } else if resp.has_focus()+ && ui.input(|i| i.pointer.any_pressed())+ && !ui.rect_contains_pointer(rect)+ {+ // Like a text field: a click anywhere else gives the keyboard back to the app.+ resp.surrender_focus();+ }+ let focused = resp.has_focus();+ if focused {+ // Keep Tab, arrows and Escape for the shell.+ ui.memory_mut(|m| {+ m.set_focus_lock_filter(+ id,+ egui::EventFilter {+ tab: true,+ horizontal_arrows: true,+ vertical_arrows: true,+ escape: true,+ },+ )+ });+ }++ // 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 {+ self.size = (rows, cols);+ let _ = self.master.resize(PtySize {+ rows,+ cols,+ pixel_width: 0,+ pixel_height: 0,+ });+ lock(&self.parser).set_size(nz(rows), nz(cols));+ }++ // Input.+ if focused {+ let (events, app_cursor, bracketed) = {+ let parser = lock(&self.parser);+ let screen = parser.screen();+ (+ ui.input(|i| i.events.clone()),+ screen.application_cursor(),+ screen.bracketed_paste(),+ )+ };+ for event in events {+ match event {+ Event::Text(text) => self.send(text.as_bytes()),+ Event::Paste(text) => {+ let text = text.replace("\r\n", "\r").replace('\n', "\r");+ if bracketed {+ self.send(format!("\x1b[200~{text}\x1b[201~").as_bytes());+ } else {+ self.send(text.as_bytes());+ }+ }+ // egui turns Ctrl+C / Ctrl+X into clipboard events; the shell wants them.+ Event::Copy => self.send(b"\x03"),+ Event::Cut => self.send(b"\x18"),+ Event::Key {+ key,+ pressed: true,+ modifiers,+ ..+ } => {+ if let Some(bytes) = key_bytes(key, modifiers, app_cursor) {+ self.send(&bytes);+ }+ }+ _ => {}+ }+ }+ }++ // Wheel scrolls through history.+ if resp.hovered() {+ let dy = ui.input(|i| i.smooth_scroll_delta.y);+ if dy != 0.0 {+ self.scroll_rest += dy / cell.y;+ let lines = self.scroll_rest.trunc();+ self.scroll_rest -= lines;+ let mut parser = lock(&self.parser);+ let wanted = (self.scroll as f32 + lines).max(0.0) as usize;+ parser.screen_mut().set_scrollback(wanted);+ self.scroll = parser.screen().scrollback();+ }+ }++ // Paint.+ let painter = ui.painter_at(rect);+ painter.rect_filled(rect, 0.0, t.field);+ let parser = lock(&self.parser);+ let screen = parser.screen();+ let (rows, cols) = screen.size();+ let (rows, cols) = (rows.get(), cols.get());+ let palette = Palette::new(&t);+ for row in 0..rows {+ let y = inner.top() + row as f32 * cell.y;+ let mut job = LayoutJob::default();+ let mut col = 0;+ while col < cols {+ let Some(c) = screen.cell(row, col) else {+ break;+ };+ let (fg, bg) = palette.colors(c);+ if let Some(bg) = bg {+ let x = inner.left() + col as f32 * cell.x;+ let w = if c.is_wide() { 2.0 } else { 1.0 };+ painter.rect_filled(+ Rect::from_min_size(pos2(x, y), vec2(cell.x * w, cell.y)),+ 0.0,+ bg,+ );+ }+ if !c.is_wide_continuation() {+ let text = if c.has_contents() { c.contents() } else { " " };+ job.append(+ text,+ 0.0,+ TextFormat {+ font_id: font.clone(),+ color: fg,+ underline: if c.underline() {+ Stroke::new(1.0, fg)+ } else {+ Stroke::NONE+ },+ italics: c.italic(),+ ..Default::default()+ },+ );+ }+ col += 1;+ }+ let galley = ui.fonts_mut(|f| f.layout_job(job));+ painter.galley(pos2(inner.left(), y), galley, t.text);+ }++ // Cursor (only when following the output).+ if self.scroll == 0 && !screen.hide_cursor() && !self.exited.load(Ordering::Relaxed) {+ let (cr, cc) = screen.cursor_position();+ let r = Rect::from_min_size(+ pos2(+ inner.left() + cc as f32 * cell.x,+ inner.top() + cr as f32 * cell.y,+ ),+ cell,+ );+ if focused {+ painter.rect_filled(r, 0.0, t.text.gamma_multiply(0.7));+ } else {+ painter.rect_stroke(+ r,+ 0.0,+ Stroke::new(1.0, t.text_faint),+ egui::StrokeKind::Inside,+ );+ }+ }+ if self.scroll > 0 {+ painter.text(+ rect.right_top() + vec2(-10.0, 8.0),+ egui::Align2::RIGHT_TOP,+ format!("↑ {} lines", self.scroll),+ FontId::proportional(11.0),+ t.text_faint,+ );+ }+ }+}++impl Drop for Terminal {+ fn drop(&mut self) {+ let _ = self.child.kill();+ }+}++/// 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())+ }+}++#[cfg(windows)]+fn on_path(exe: &str) -> bool {+ std::env::var_os("PATH")+ .map(|paths| std::env::split_paths(&paths).any(|dir| dir.join(exe).is_file()))+ .unwrap_or(false)+}++fn nz(n: u16) -> NonZeroU16 {+ NonZeroU16::new(n).unwrap_or(NonZeroU16::MIN)+}++fn contains(haystack: &[u8], needle: &[u8]) -> bool {+ haystack.windows(needle.len()).any(|w| w == needle)+}++/// A poisoned lock still holds usable data.+fn lock<T: ?Sized>(m: &Mutex<T>) -> MutexGuard<'_, T> {+ match m.lock() {+ Ok(guard) => guard,+ Err(poisoned) => poisoned.into_inner(),+ }+}++/// What a key sends to the shell (xterm sequences).+fn key_bytes(key: Key, mods: Modifiers, app_cursor: bool) -> Option<Vec<u8>> {+ let csi_or_ss3 = |c: char| {+ if app_cursor {+ format!("\x1bO{c}")+ } else {+ format!("\x1b[{c}")+ }+ };+ if mods.ctrl && !mods.alt {+ // Ctrl+letter → control character (Ctrl+C and Ctrl+X arrive as Copy / Cut).+ let name = key.name();+ if name.len() == 1+ && let Some(c) = name.chars().next()+ && c.is_ascii_alphabetic()+ {+ return Some(vec![(c.to_ascii_uppercase() as u8) - b'A' + 1]);+ }+ }+ let s: String = match key {+ Key::Enter => "\r".into(),+ Key::Tab if mods.shift => "\x1b[Z".into(),+ Key::Tab => "\t".into(),+ Key::Backspace => "\x7f".into(),+ Key::Escape => "\x1b".into(),+ Key::ArrowUp => csi_or_ss3('A'),+ Key::ArrowDown => csi_or_ss3('B'),+ Key::ArrowRight => csi_or_ss3('C'),+ Key::ArrowLeft => csi_or_ss3('D'),+ Key::Home => csi_or_ss3('H'),+ Key::End => csi_or_ss3('F'),+ Key::PageUp => "\x1b[5~".into(),+ Key::PageDown => "\x1b[6~".into(),+ Key::Insert => "\x1b[2~".into(),+ Key::Delete => "\x1b[3~".into(),+ Key::F1 => "\x1bOP".into(),+ Key::F2 => "\x1bOQ".into(),+ Key::F3 => "\x1bOR".into(),+ Key::F4 => "\x1bOS".into(),+ _ => return None,+ };+ Some(s.into_bytes())+}++/// Terminal colours tuned to the app theme.+struct Palette {+ fg: Color32,+ ansi: [Color32; 16],+}++impl Palette {+ fn new(t: &Tokens) -> Self {+ let ansi = if t.dark() {+ [+ Color32::from_rgb(40, 40, 40),+ Color32::from_rgb(236, 91, 98),+ Color32::from_rgb(92, 196, 122),+ Color32::from_rgb(232, 176, 70),+ Color32::from_rgb(64, 156, 255),+ Color32::from_rgb(200, 110, 230),+ Color32::from_rgb(60, 205, 210),+ Color32::from_rgb(200, 200, 200),+ Color32::from_rgb(110, 110, 110),+ Color32::from_rgb(255, 120, 125),+ Color32::from_rgb(130, 225, 150),+ Color32::from_rgb(250, 205, 100),+ Color32::from_rgb(110, 180, 255),+ Color32::from_rgb(220, 150, 245),+ Color32::from_rgb(110, 225, 230),+ Color32::from_rgb(245, 245, 245),+ ]+ } else {+ [+ Color32::from_rgb(20, 20, 20),+ Color32::from_rgb(200, 40, 50),+ Color32::from_rgb(30, 140, 70),+ Color32::from_rgb(170, 110, 0),+ Color32::from_rgb(20, 100, 210),+ Color32::from_rgb(150, 60, 190),+ Color32::from_rgb(0, 140, 150),+ Color32::from_rgb(110, 110, 110),+ Color32::from_rgb(90, 90, 90),+ Color32::from_rgb(230, 60, 70),+ Color32::from_rgb(40, 170, 90),+ Color32::from_rgb(200, 140, 0),+ Color32::from_rgb(40, 120, 240),+ Color32::from_rgb(180, 80, 220),+ Color32::from_rgb(0, 170, 180),+ Color32::from_rgb(40, 40, 40),+ ]+ };+ Self { fg: t.text, ansi }+ }++ fn color(&self, c: vt100::Color) -> Option<Color32> {+ match c {+ vt100::Color::Default => None,+ vt100::Color::Idx(i) if i < 16 => self.ansi.get(i as usize).copied(),+ vt100::Color::Idx(i) if i < 232 => {+ let i = i - 16;+ let level = |v: u8| if v == 0 { 0 } else { 55 + v * 40 };+ Some(Color32::from_rgb(+ level(i / 36),+ level((i / 6) % 6),+ level(i % 6),+ ))+ }+ vt100::Color::Idx(i) => {+ let v = 8 + (i - 232).saturating_mul(10);+ Some(Color32::from_gray(v))+ }+ vt100::Color::Rgb(r, g, b) => Some(Color32::from_rgb(r, g, b)),+ }+ }++ /// (foreground, background-if-not-default) of a cell.+ fn colors(&self, cell: &vt100::Cell) -> (Color32, Option<Color32>) {+ let mut fg = self.color(cell.fgcolor()).unwrap_or(self.fg);+ let mut bg = self.color(cell.bgcolor());+ if cell.bold()+ && let vt100::Color::Idx(i) = cell.fgcolor()+ && i < 8+ {+ fg = self.ansi.get(i as usize + 8).copied().unwrap_or(fg);+ }+ if cell.dim() {+ fg = fg.gamma_multiply(0.6);+ }+ if cell.inverse() {+ let old_fg = fg;+ fg = bg.unwrap_or(Color32::from_rgb(30, 30, 30));+ bg = Some(old_fg);+ }+ (fg, bg)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn keys_to_bytes() {+ assert_eq!(+ key_bytes(Key::Enter, Modifiers::NONE, false),+ Some(b"\r".to_vec())+ );+ assert_eq!(+ key_bytes(Key::ArrowUp, Modifiers::NONE, false),+ Some(b"\x1b[A".to_vec())+ );+ assert_eq!(+ key_bytes(Key::ArrowUp, Modifiers::NONE, true),+ Some(b"\x1bOA".to_vec())+ );+ assert_eq!(key_bytes(Key::D, Modifiers::CTRL, false), Some(vec![4]));+ assert_eq!(key_bytes(Key::A, Modifiers::NONE, false), None);+ }++ #[test]+ fn indexed_colours() {+ let p = Palette::new(&Tokens::for_kind(crate::theme::ThemeKind::Dark));+ assert_eq!(+ p.color(vt100::Color::Idx(16)),+ Some(Color32::from_rgb(0, 0, 0))+ );+ assert_eq!(+ p.color(vt100::Color::Idx(231)),+ Some(Color32::from_rgb(255, 255, 255))+ );+ assert_eq!(+ p.color(vt100::Color::Idx(255)),+ Some(Color32::from_gray(238))+ );+ }+}