A visual git client, simple to use yet powerful. Light, fast and debloated.
Rust
feat: gitcraft 0.4.0 - move branches with autostash, hide and solo branches, quick commit edits, CodeCraft and VS Code themes, SSH questions in a dialog
Ivándce6fde7fa99
diff --git a/Cargo.lock b/Cargo.lockindex ed7fdc4..af30b7d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1447,7 +1447,7 @@ dependencies = [[[package]]name = "gitcraft"-version = "0.3.4"+version = "0.4.0"dependencies = ["eframe","egui",diff --git a/Cargo.toml b/Cargo.tomlindex a464464..1af7a74 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[package]name = "gitcraft"-version = "0.3.4"+version = "0.4.0"edition = "2024"rust-version = "1.95"license = "MIT OR Apache-2.0"diff --git a/README.md b/README.mdindex 8b5788a..6d78a17 100644--- a/README.md+++ b/README.md@@ -15,8 +15,8 @@ so your config, credentials and hooks apply as usual.- 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.+- Browser-like tabs, one per repository (Ctrl+T, Ctrl+W, middle-click; Ctrl+Shift+T reopens the+ one closed last). Open tabs, recents, theme and settings are remembered.- Changes made elsewhere (editor, terminal) show up by themselves: the folder is watched.**Graph**@@ -30,11 +30,22 @@ so your config, credentials and hooks apply as usual.- The checked-out branch's pill is solid, the others a darker shade. Double-click a pill tocheck that branch (or tag) out; hover `+N` to list every pill of the commit and double-clickthe one you want.+- Double-click a pill further on than its branch (the remote's, say) to move the branch there,+ checking it out if needed: uncommitted changes are stashed and applied again on top (if they+ clash, the files are left with conflicts to fix and the stash is kept). When the two have+ diverged, the toolbar turns into the choices for a moment: rebase, merge or reset.+- Hide or solo branches: an eye on each branch in the left pane (on hover) hides it from the+ graph, with its own commits; _Solo_ in its menu draws only the soloed ones. The headers show+ how many are drawn (`4/5`), the toolbar says how many are hidden and shows them all again on a+ click. Kept per repository.+- Stashes in the graph, above the commit they were made on, marked with their icon.- Each commit's summary, followed by the rest of its message, faded and cut to fit.- An _Uncommitted changes_ row on top while the working tree is dirty.- Search (Ctrl+F) through messages, authors and hashes of all history, or switch to _Code_ tofind the commits that added or removed a piece of text in a file (`git log -S`); Enter /Shift+Enter jump between results, loading older history when needed.+- Right-click a commit of the checked-out branch to edit its message, move it up or down, or+ drop it, without going through the interactive rebase (Ctrl+Z undoes each).- Right-click a commit: create a branch or a tag, check it out, interactive rebase onto it,cherry-pick, revert, reset the current branch to it (soft / mixed / hard, confirmed), the menuof each branch on it, copy the hash, message or branch name. Right-click a branch's pill to get@@ -83,10 +94,14 @@ so your config, credentials and hooks apply as usual.the changed part of each line marked, whitespace changes optional, images shown before / after.Esc closes.- Only the changes or the whole file, and side by side or unified, both kept for next time. A- strip beside the scrollbar marks where the changes are; click it to jump there. Drag over the- lines to select text, Ctrl+C or right-click to copy it.-- Code takes the colours of the theme VS Code (or Insiders, VSCodium) is using, read from its- settings and extensions, when it is dark or light like gitcraft's; a setting turns it off.+ strip beside the scrollbar marks where the changes are; click it to jump there, or use the+ arrows (Alt+Up / Alt+Down) for the change before or after. Drag over the lines to select text,+ Ctrl+C or right-click to copy it.+- A commit's files as a list of paths or a tree of their folders (a switch above them).+- Code colours: four styles of gitcraft's own (CodeCraft's), or any colour theme installed in+ VS Code (or Insiders, VSCodium) imported in Settings › Themes, which then colours the whole+ window as well.+- Double-click a line of a diff, or right-click it, to open the file in your editor at that line.- 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@@ -111,8 +126,11 @@ so your config, credentials and hooks apply as usual.- Avatars: on a GitHub repository, the authors' GitHub accounts (through `gh` when installed, elseGitHub's API); on GitLab, the host's avatar API; elsewhere Gravatar (a hash of the email).Cached on disk; can be turned off.-- Settings: zoom, branch column width, graph columns, avatars, notifications, update check,- background fetch, editor command, default shell and terminal font size, saved identities.+- Settings: zoom (applied with a button), branch column width, graph columns, avatars,+ notifications, update check, code themes, background fetch, editor command, default shell and+ terminal font size, saved identities.+- On macOS and Linux, ssh's questions (a password, a key's passphrase, trusting a new host) come+ up in a dialog: gitcraft is ssh's `SSH_ASKPASS`.- Checks GitHub every 12 hours for a newer release and shows a pill to download it (can be turnedoff).- Toasts, and a desktop notification when a long operation ends while the window is in the@@ -189,11 +207,14 @@ was made this way, on a demo repository.| `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/branch_filter.rs` | branches hidden from or soloed in the graph || `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, with bat's syntaxes from `two-face`) |-| `src/vscode_theme.rs` | VS Code's current colour theme as a syntect theme |+| `src/vscode/` | VS Code's colour themes: finding them, and reading one for code and window |+| `src/code_theme.rs` | gitcraft's code styles and the code theme in use |+| `src/askpass.rs` | ssh's questions shown in the window (`SSH_ASKPASS`) || `src/repo/conflict.rs` | three-pane conflict editor || `src/repo/rebase.rs` | interactive rebase editor and its todo list || `src/repo/file_view.rs` | a file's history and blame |diff --git a/assets/icons/eye-off.svg b/assets/icons/eye-off.svgnew file mode 100644index 0000000..0083aaa--- /dev/null+++ b/assets/icons/eye-off.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="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49" />+ <path d="M14.084 14.158a3 3 0 0 1-4.242-4.242" />+ <path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143" />+ <path d="m2 2 20 20" />+</svg>diff --git a/assets/icons/eye.svg b/assets/icons/eye.svgnew file mode 100644index 0000000..e5e7870--- /dev/null+++ b/assets/icons/eye.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="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0" />+ <circle cx="12" cy="12" r="3" />+</svg>diff --git a/assets/icons/list.svg b/assets/icons/list.svgnew file mode 100644index 0000000..9de09ad--- /dev/null+++ b/assets/icons/list.svg@@ -0,0 +1,18 @@+<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="M3 12h.01" />+ <path d="M3 18h.01" />+ <path d="M3 6h.01" />+ <path d="M8 12h13" />+ <path d="M8 18h13" />+ <path d="M8 6h13" />+</svg>diff --git a/examples/ui_shot.rs b/examples/ui_shot.rsindex ec3cff3..0325b58 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`, `drag:x1,y1,x2,y2`, `press:x,y` / `move:x,y` / `release:x,y` (a drag in parts), `leave` (pointer off the window), `open:path` (a repository in a new tab), `key:Escape`, `ckey:P` (Ctrl/Cmd+key), `type:text`, `wait:ms`, `shot`.+//! `click:x,y`, `dclick:x,y`, `rclick:x,y`, `hover:x,y`, `drag:x1,y1,x2,y2`, `press:x,y` / `move:x,y` / `release:x,y` (a drag in parts), `leave` (pointer off the window), `open:path` (a repository in a new tab), `askpass:prompt` (ssh asking, `|` for a new line), `key:Escape`, `ckey:P` (Ctrl/Cmd+key), `cskey:T` (Ctrl/Cmd+Shift+key), `type:text`, `wait:ms`, `shot`.//! Each `shot` writes `<out-prefix>-<n>.png`.use std::time::{Duration, Instant};@@ -88,6 +88,11 @@ fn main() {.open_tab(std::path::Path::new(arg), &ctx);settle(&mut harness, 1500);}+ "askpass" => {+ let prompt = arg.replace('|', "\n");+ std::thread::spawn(move || gitcraft::askpass::ask_window(&prompt));+ settle(&mut harness, 600);+ }"leave" => {harness.remove_cursor();settle(&mut harness, 200);@@ -183,6 +188,12 @@ fn main() {}settle(&mut harness, 300);}+ "cskey" => {+ if let Some(key) = Key::from_name(arg) {+ harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, key);+ }+ settle(&mut harness, 600);+ }"type" => {harness.event(Event::Text(arg.to_owned()));settle(&mut harness, 200);diff --git a/src/app.rs b/src/app.rsindex 82b3b87..373aaa3 100644--- a/src/app.rs+++ b/src/app.rs@@ -8,13 +8,16 @@ use std::sync::mpsc::{Receiver, channel};use egui::{Align2, Key, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};use serde::{Deserialize, Serialize};+use crate::askpass;+use crate::code_theme::{self, CodeColors, SyntaxStyle};use crate::git;use crate::icons;-use crate::repo::RepoTab;-use crate::settings::Settings;+use crate::repo::{BranchFilter, RepoTab};+use crate::settings::{CodeTheme, Settings};use crate::tab_look::{self, TabLook};use crate::theme::{self, ThemeKind, Tokens};use crate::update;+use crate::vscode;const MAX_RECENT: usize = 12;const TAB_H: f32 = 40.0;@@ -40,6 +43,8 @@ struct Saved {skipped_version: String,/// Repository tabs given their own icon or colour.tab_looks: BTreeMap<PathBuf, TabLook>,+ /// Branches hidden from or soloed in each repository's graph.+ branch_filters: BTreeMap<PathBuf, BranchFilter>,}enum Tab {@@ -83,13 +88,27 @@ pub struct App {update_checked: i64,skipped_version: String,tab_looks: BTreeMap<PathBuf, TabLook>,+ branch_filters: BTreeMap<PathBuf, BranchFilter>,settings: Settings,manual_open: bool,palette: Option<Palette>,toasts: Vec<Toast>,tab_drag: Option<TabDrag>,+ /// A question from ssh on screen, with what is typed in answer.+ askpass: Option<(askpass::Request, String)>,+ /// Tabs closed, latest last, with where they were: Ctrl+Shift+T opens them again.+ closed: Vec<(Closed, usize)>,}+/// A tab closed, as it can be opened again.+enum Closed {+ Repo(PathBuf),+ Settings,+}++/// How many closed tabs are remembered.+const MAX_CLOSED: usize = 20;+/// A tab being dragged along the strip.#[derive(Clone, Copy)]struct TabDrag {@@ -118,6 +137,7 @@ struct Toast {/// What a palette entry does outside the open repository.enum AppCommand {NewTab,+ ReopenTab,Open,Create,Clone,@@ -141,8 +161,8 @@ impl App {.unwrap_or_default();let ctx = &cc.egui_ctx;egui_extras::install_image_loaders(ctx);+ askpass::init(ctx);theme::install_fonts(ctx);- theme::apply(ctx, saved.theme);saved.settings.set(ctx);crate::desktop_entry::refresh();@@ -158,6 +178,8 @@ impl App {palette: None,toasts: Vec::new(),tab_drag: None,+ askpass: None,+ closed: Vec::new(),error: None,was_focused: true,clone_form: None,@@ -168,7 +190,9 @@ impl App {update_checked: saved.update_checked,skipped_version: saved.skipped_version,tab_looks: saved.tab_looks,+ branch_filters: saved.branch_filters,};+ app.apply_theme(ctx);if saved.settings.check_updates && git::now() - saved.update_checked > update::INTERVAL {let (tx, rx) = channel();let ctx2 = ctx.clone();@@ -181,7 +205,9 @@ impl App {if app.git_version.is_ok() {for path in saved.open {if path.is_dir() {- app.tabs.push(Tab::Repo(Box::new(RepoTab::new(path, ctx))));+ let filter = app.branch_filters.get(&path).cloned().unwrap_or_default();+ app.tabs+ .push(Tab::Repo(Box::new(RepoTab::with_filter(path, filter, ctx))));}}}@@ -224,7 +250,8 @@ impl App {self.active = i;return;}- let tab = Tab::Repo(Box::new(RepoTab::new(root, ctx)));+ let filter = self.branch_filters.get(&root).cloned().unwrap_or_default();+ let tab = Tab::Repo(Box::new(RepoTab::with_filter(root, filter, ctx)));if matches!(self.tabs.get(self.active), Some(Tab::Home)) {self.tabs[self.active] = tab;} else {@@ -294,11 +321,68 @@ impl App {});}+ /// Opens the tab closed last again, where it was (Ctrl+Shift+T).+ fn reopen_tab(&mut self, ctx: &egui::Context) {+ let Some((closed, at)) = self.closed.pop() else {+ return;+ };+ let tab = match closed {+ Closed::Settings => {+ if let Some(i) = self.tabs.iter().position(|t| matches!(t, Tab::Settings)) {+ self.active = i;+ return;+ }+ Tab::Settings+ }+ Closed::Repo(path) => {+ if let Some(i) = self+ .tabs+ .iter()+ .position(|t| matches!(t, Tab::Repo(r) if r.path == path))+ {+ self.active = i;+ return;+ }+ if !path.is_dir() {+ return self.reopen_tab(ctx);+ }+ let filter = self.branch_filters.get(&path).cloned().unwrap_or_default();+ Tab::Repo(Box::new(RepoTab::with_filter(path, filter, ctx)))+ }+ };+ // A lone start page gives its place up.+ if self.tabs.len() == 1 && matches!(self.tabs.first(), Some(Tab::Home)) {+ self.tabs.clear();+ }+ let at = at.min(self.tabs.len());+ self.tabs.insert(at, tab);+ self.active = at;+ }+fn close_tab(&mut self, i: usize) {if i >= self.tabs.len() {return;}- self.tabs.remove(i);+ let closed = match self.tabs.remove(i) {+ Tab::Repo(r) => {+ // Its graph filter outlives the tab.+ if r.graph_filter.is_active() {+ self.branch_filters+ .insert(r.path.clone(), r.graph_filter.clone());+ } else {+ self.branch_filters.remove(&r.path);+ }+ Some(Closed::Repo(r.path.clone()))+ }+ Tab::Settings => Some(Closed::Settings),+ Tab::Home => None,+ };+ if let Some(closed) = closed {+ self.closed.push((closed, i));+ if self.closed.len() > MAX_CLOSED {+ self.closed.remove(0);+ }+ }if self.tabs.is_empty() {self.tabs.push(Tab::Home);}@@ -332,7 +416,31 @@ impl App {fn set_theme(&mut self, ctx: &egui::Context, kind: ThemeKind) {self.theme = kind;- theme::apply(ctx, kind);+ self.apply_theme(ctx);+ }++ /// Applies the themes chosen: a VS Code one colours the whole window and the code; with+ /// gitcraft's own, the window takes the look picked in the theme menu and code the style+ /// picked in the settings. Open diffs are coloured again.+ fn apply_theme(&mut self, ctx: &egui::Context) {+ let vs = self.settings.vscode_theme().and_then(vscode::color_theme);+ let (tokens, colors) = match vs {+ Some(vs) => (Tokens::with_vscode(&vs), CodeColors::VsCode(vs)),+ None => (+ Tokens::for_kind(self.theme),+ CodeColors::Builtin(match &self.settings.theme {+ CodeTheme::Builtin(style) => *style,+ CodeTheme::VsCode(_) => SyntaxStyle::default(),+ }),+ ),+ };+ code_theme::set_current(colors);+ theme::apply(ctx, tokens);+ for tab in &mut self.tabs {+ if let Tab::Repo(r) = tab {+ r.recolor(ctx);+ }+ }}/// PhotoCraft-style document tabs on a dark strip, `+` after them, the theme menu at the end.@@ -582,9 +690,29 @@ impl App {.font(theme::semibold(10.5)).color(t.text_faint),);- for kind in ThemeKind::ALL {- if ui.radio(self.theme == kind, kind.label()).clicked() {- self.set_theme(ui.ctx(), kind);+ let following = self.settings.vscode_theme().map(|vs| vs.name.clone());+ ui.add_enabled_ui(following.is_none(), |ui| {+ for kind in ThemeKind::ALL {+ if ui.radio(self.theme == kind, kind.label()).clicked() {+ self.set_theme(ui.ctx(), kind);+ }+ }+ });+ if let Some(name) = following {+ ui.separator();+ egui::Frame::new()+ .inner_margin(egui::Margin::symmetric(16, 2))+ .show(ui, |ui| {+ ui.label(+ RichText::new(format!("VS Code theme: {name}"))+ .color(t.text_faint)+ .small(),+ );+ });+ if ui.button("Use gitcraft's themes").clicked() {+ self.settings.theme = CodeTheme::default();+ self.settings.set(ui.ctx());+ self.apply_theme(ui.ctx());}}});@@ -1015,12 +1143,14 @@ 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()+ || self.askpass.is_some()|| self.palette.is_some()|| self.manual_open|| ctx.egui_wants_keyboard_input();- let (new_tab, close, refresh, focused, palette, manual) = ctx.input(|i| {+ let (new_tab, reopen, close, refresh, focused, palette, manual) = ctx.input(|i| {(- i.modifiers.command && i.key_pressed(Key::T),+ i.modifiers.command && !i.modifiers.shift && i.key_pressed(Key::T),+ i.modifiers.command && i.modifiers.shift && i.key_pressed(Key::T),i.modifiers.command && i.key_pressed(Key::W),i.key_pressed(Key::F5),i.focused,@@ -1041,6 +1171,9 @@ impl eframe::App for App {if new_tab && !modal_open {self.new_tab();}+ if reopen && !modal_open {+ self.reopen_tab(&ctx);+ }if close && !modal_open {self.close_tab(self.active);}@@ -1078,8 +1211,10 @@ 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.manual_open || self.clone_form.is_some();+ repo.keys_blocked = self.palette.is_some()+ || self.manual_open+ || self.clone_form.is_some()+ || self.askpass.is_some();repo.ui(ui);// A worktree asked to be opened in its own tab.if let Some(path) = repo.open_request.take() {@@ -1100,6 +1235,7 @@ impl eframe::App for App {self.clone_dialog(&ctx);self.palette_ui(&ctx);self.manual_ui(&ctx);+ self.askpass_ui(&ctx);// Long operations that ended: a toast, and a desktop notification when away.for tab in &mut self.tabs {@@ -1120,6 +1256,17 @@ impl eframe::App for App {}fn save(&mut self, storage: &mut dyn eframe::Storage) {+ // Each open repository's graph filter; one emptied is forgotten.+ for tab in &self.tabs {+ if let Tab::Repo(r) = tab {+ if r.graph_filter.is_active() {+ self.branch_filters+ .insert(r.path.clone(), r.graph_filter.clone());+ } else {+ self.branch_filters.remove(&r.path);+ }+ }+ }let open: Vec<PathBuf> = self.tabs.iter()@@ -1146,6 +1293,7 @@ impl eframe::App for App {update_checked: self.update_checked,skipped_version: self.skipped_version.clone(),tab_looks: self.tab_looks.clone(),+ branch_filters: self.branch_filters.clone(),};eframe::set_value(storage, eframe::APP_KEY, &saved);}@@ -1299,6 +1447,11 @@ impl App {"Ctrl+T".to_owned(),Entry::App(AppCommand::NewTab),),+ (+ "Reopen closed tab".to_owned(),+ "Ctrl+Shift+T".to_owned(),+ Entry::App(AppCommand::ReopenTab),+ ),("Open repository…".to_owned(),"app".to_owned(),@@ -1343,6 +1496,7 @@ impl App {fn run_entry(&mut self, entry: Entry, ctx: &egui::Context) {match entry {Entry::App(AppCommand::NewTab) => self.new_tab(),+ Entry::App(AppCommand::ReopenTab) => self.reopen_tab(ctx),Entry::App(AppCommand::Open) => self.pick_existing(ctx),Entry::App(AppCommand::Create) => self.pick_new(ctx),Entry::App(AppCommand::Clone) => self.start_clone(),@@ -1502,8 +1656,14 @@ impl App {ui.add_space(32.0);ui.label(RichText::new("Settings").font(theme::semibold(22.0)));ui.add_space(4.0);+ let before = self.settings.clone();if self.settings.ui(ui) {self.settings.set(ui.ctx());+ if self.settings.theme != before.theme+ || self.settings.imported_themes != before.imported_themes+ {+ self.apply_theme(ui.ctx());+ }}ui.add_space(32.0);});@@ -1511,6 +1671,82 @@ impl App {});}+ /// ssh asking for a password or passphrase, or whether to trust a host it hasn't seen.+ fn askpass_ui(&mut self, ctx: &egui::Context) {+ if self.askpass.is_none() {+ self.askpass = askpass::take().map(|r| (r, String::new()));+ }+ let Some((request, typed)) = &mut self.askpass else {+ 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 confirm = request.is_confirmation();+ let mut answer: Option<Option<String>> = None;+ let resp = egui::Modal::new(egui::Id::new("askpass"))+ .frame(frame)+ .backdrop_color(egui::Color32::from_black_alpha(110))+ .show(ctx, |ui| {+ ui.set_width(460.0);+ ui.horizontal(|ui| {+ icons::inline(ui, "server", 16.0, t.icon);+ let title = if confirm {+ "Trust this host?"+ } else if request.prompt.to_lowercase().contains("passphrase") {+ "SSH asks for your key's passphrase"+ } else {+ "SSH asks for a password"+ };+ ui.label(RichText::new(title).font(theme::semibold(15.0)));+ });+ ui.add_space(8.0);+ ui.label(RichText::new(&request.prompt).color(t.text_dim));+ ui.add_space(10.0);+ if !confirm {+ let field = ui.add(+ egui::TextEdit::singleline(typed)+ .password(true)+ .desired_width(f32::INFINITY),+ );+ if !field.has_focus() {+ field.request_focus();+ }+ if field.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {+ answer = Some(Some(typed.clone()));+ }+ ui.add_space(10.0);+ }+ ui.horizontal(|ui| {+ let ok = if confirm { "Trust and connect" } else { "OK" };+ let primary =+ egui::Button::new(RichText::new(ok).color(t.accent_text)).fill(t.accent);+ if ui.add(primary).clicked() {+ answer = Some(Some(if confirm {+ "yes".to_owned()+ } else {+ typed.clone()+ }));+ }+ if ui.button("Cancel").clicked() {+ answer = Some(None);+ }+ });+ });+ if resp.should_close() && answer.is_none() {+ answer = Some(None);+ }+ if let Some(answer) = answer+ && let Some((request, _)) = self.askpass.take()+ {+ request.answer(answer);+ }+ }+fn manual_ui(&mut self, ctx: &egui::Context) {if !self.manual_open {return;diff --git a/src/askpass.rs b/src/askpass.rsnew file mode 100644index 0000000..c14dd41--- /dev/null+++ b/src/askpass.rs@@ -0,0 +1,199 @@+//! Questions ssh asks while git runs: a password, a key's passphrase, whether to trust a host+//! seen for the first time. gitcraft runs git with no terminal, so ssh can't ask there; it asks+//! the program in `SSH_ASKPASS` instead, which is gitcraft itself started again as a helper.+//!+//! The helper passes the question to the running window over a localhost port (with a random+//! token, so nothing else can ask), the window shows it in a dialog, and the answer goes back+//! the same way for the helper to print to ssh. Windows' git brings its own dialogs, so this is+//! for macOS and Linux.++use std::collections::hash_map::RandomState;+use std::hash::{BuildHasher, Hasher};+use std::io::{BufRead, BufReader, Read, Write};+use std::net::{Ipv4Addr, Shutdown, SocketAddr, TcpListener, TcpStream};+use std::process::Command;+use std::sync::mpsc::{Sender, channel};+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++/// Tells the helper where the window listens: `port token`.+const ENV: &str = "GITCRAFT_ASKPASS";+/// How long a question waits for its answer before ssh is told no.+const ANSWER_TIMEOUT: Duration = Duration::from_secs(600);++/// A question from ssh, waiting for the user.+pub struct Request {+ pub prompt: String,+ reply: Sender<Option<String>>,+}++impl Request {+ /// A yes / no question (trusting a new host) rather than a secret to type.+ pub fn is_confirmation(&self) -> bool {+ self.prompt.contains("(yes/no")+ }++ /// Sends the answer; `None` cancels, and ssh gives up.+ pub fn answer(self, answer: Option<String>) {+ let _ = self.reply.send(answer);+ }+}++struct Server {+ port: u16,+ token: String,+}++static CTX: OnceLock<egui::Context> = OnceLock::new();+static SERVER: OnceLock<Option<Server>> = OnceLock::new();+static QUEUE: Mutex<Vec<Request>> = Mutex::new(Vec::new());++/// The window to wake when a question arrives.+pub fn init(ctx: &egui::Context) {+ let _ = CTX.set(ctx.clone());+}++/// The next question waiting, if any.+pub fn take() -> Option<Request> {+ let mut queue = QUEUE.lock().ok()?;+ (!queue.is_empty()).then(|| queue.remove(0))+}++/// Lets ssh in `cmd` ask its questions in the window (macOS and Linux).+pub fn apply(cmd: &mut Command) {+ if cfg!(windows) {+ return;+ }+ let (Some(server), Ok(exe)) = (server(), std::env::current_exe()) else {+ return;+ };+ cmd.env("SSH_ASKPASS", exe);+ // Ask even when gitcraft was started from a terminal (OpenSSH 8.4 and later)…+ cmd.env("SSH_ASKPASS_REQUIRE", "force");+ // …and older ones only ask with a display set.+ if std::env::var_os("DISPLAY").is_none() {+ cmd.env("DISPLAY", ":0");+ }+ cmd.env(ENV, format!("{} {}", server.port, server.token));+}++/// Starts listening the first time it's needed.+fn server() -> Option<&'static Server> {+ SERVER.get_or_init(start).as_ref()+}++fn start() -> Option<Server> {+ let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).ok()?;+ let port = listener.local_addr().ok()?.port();+ let token = format!(+ "{:016x}{:016x}",+ RandomState::new().build_hasher().finish(),+ RandomState::new().build_hasher().finish()+ );+ let expected = token.clone();+ std::thread::spawn(move || {+ for stream in listener.incoming().flatten() {+ let token = expected.clone();+ // Each question waits for its answer on a thread of its own.+ std::thread::spawn(move || serve(stream, &token));+ }+ });+ Some(Server { port, token })+}++/// One helper's question: the token on the first line, then the prompt; back goes `ok` and+/// the answer, or `cancel`.+fn serve(stream: TcpStream, token: &str) {+ let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));+ let mut reader = BufReader::new(&stream);+ let mut sent = String::new();+ if reader.read_line(&mut sent).is_err() || sent.trim_end() != token {+ return;+ }+ let mut prompt = String::new();+ if reader.read_to_string(&mut prompt).is_err() {+ return;+ }+ let (reply, answer) = channel();+ let Ok(mut queue) = QUEUE.lock() else {+ return;+ };+ queue.push(Request {+ prompt: prompt.trim().to_owned(),+ reply,+ });+ drop(queue);+ if let Some(ctx) = CTX.get() {+ ctx.request_repaint();+ }+ let out = match answer.recv_timeout(ANSWER_TIMEOUT) {+ Ok(Some(answer)) => format!("ok\n{answer}"),+ _ => "cancel\n".to_owned(),+ };+ let _ = (&stream).write_all(out.as_bytes());+}++/// When this process was started by ssh as `SSH_ASKPASS`: asks the window and returns the+/// exit code (0 with the answer printed, 1 when cancelled). `None` for a normal start.+pub fn run_if_asked() -> Option<i32> {+ let info = std::env::var(ENV).ok()?;+ let prompt = std::env::args().nth(1).unwrap_or_default();+ // git's own username / password prompts for HTTPS keep failing as before: gitcraft asks+ // for those itself and remembers them for the tab.+ if prompt.starts_with("Username for '") || prompt.starts_with("Password for '") {+ return Some(1);+ }+ Some(match ask(&info, &prompt) {+ Some(answer) => {+ println!("{answer}");+ 0+ }+ None => 1,+ })+}++/// Asks the window `prompt` as ssh would, for `examples/ui_shot.rs`.+#[doc(hidden)]+pub fn ask_window(prompt: &str) -> Option<String> {+ let server = server()?;+ ask(&format!("{} {}", server.port, server.token), prompt)+}++fn ask(info: &str, prompt: &str) -> Option<String> {+ let (port, token) = info.trim().split_once(' ')?;+ let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port.parse::<u16>().ok()?));+ let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(2)).ok()?;+ write!(stream, "{token}\n{prompt}").ok()?;+ stream.shutdown(Shutdown::Write).ok()?;+ let mut reply = String::new();+ stream.read_to_string(&mut reply).ok()?;+ let answer = reply.strip_prefix("ok\n")?;+ Some(answer.to_owned())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_question_reaches_the_window_and_its_answer_comes_back() {+ let Some(server) = server() else {+ return;+ };+ let info = format!("{} {}", server.port, server.token);+ let asker = std::thread::spawn(move || ask(&info, "[email protected]'s password: "));+ let request = loop {+ if let Some(r) = take() {+ break r;+ }+ std::thread::sleep(Duration::from_millis(10));+ };+ assert_eq!(request.prompt, "[email protected]'s password:");+ assert!(!request.is_confirmation());+ request.answer(Some("hunter2".to_owned()));+ assert_eq!(asker.join().ok().flatten().as_deref(), Some("hunter2"));+ // A wrong token is never asked.+ let bad = format!("{} nope", server.port);+ assert_eq!(ask(&bad, "x"), None);+ }+}diff --git a/src/code_theme.rs b/src/code_theme.rsnew file mode 100644index 0000000..97e5192--- /dev/null+++ b/src/code_theme.rs@@ -0,0 +1,273 @@+//! The colours code is shown with in diffs and blame: one of gitcraft's own styles (the same as+//! CodeCraft's), or a VS Code colour theme imported in the settings, which also colours the rest+//! of the window.+//!+//! Diffs are coloured on background threads, so the choice lives here, behind a lock.++use std::sync::{Arc, OnceLock, RwLock};++use serde::{Deserialize, Serialize};+use syntect::highlighting::{Color, StyleModifier, Theme, ThemeItem, ThemeSettings};++use crate::vscode::theme::EditorTheme;++/// What code is coloured with now.+#[derive(Clone)]+pub enum CodeColors {+ Builtin(SyntaxStyle),+ VsCode(Arc<EditorTheme>),+}++static CURRENT: RwLock<Option<CodeColors>> = RwLock::new(None);++pub fn set_current(colors: CodeColors) {+ if let Ok(mut current) = CURRENT.write() {+ *current = Some(colors);+ }+}++/// The syntect theme for a dark or light background. A VS Code theme is used as it is: it+/// colours the window too, so the background is its own.+pub fn current_theme(dark: bool) -> Theme {+ let current = CURRENT.read().ok().and_then(|c| c.clone());+ match current {+ Some(CodeColors::VsCode(vs)) => vs.syntax.clone(),+ Some(CodeColors::Builtin(style)) => style.theme(dark).clone(),+ None => SyntaxStyle::default().theme(dark).clone(),+ }+}++/// gitcraft's own code colours (CodeCraft's), for when a VS Code theme isn't chosen.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub enum SyntaxStyle {+ /// Warm: orange keywords, olive strings, gold functions.+ Ember,+ /// Cool: blue keywords, mint strings, violet types.+ Tide,+ /// Bright and balanced: purple keywords, green strings, blue functions, yellow types.+ #[default]+ Orchard,+ /// Mostly plain text: muted keywords and strings, dim comments.+ Quiet,+}++/// A style's colours (0xRRGGBB) for each kind of token; `None` leaves it as plain text.+struct Palette {+ comment: u32,+ keyword: u32,+ operator: Option<u32>,+ string: u32,+ number: u32,+ function: Option<u32>,+ kind: u32,+ macros: u32,+ this: u32,+ namespace: Option<u32>,+}++impl SyntaxStyle {+ /// In the order the settings show them, two to a row.+ pub const ALL: [SyntaxStyle; 4] = [+ SyntaxStyle::Orchard,+ SyntaxStyle::Ember,+ SyntaxStyle::Quiet,+ SyntaxStyle::Tide,+ ];++ pub fn label(self) -> &'static str {+ match self {+ SyntaxStyle::Ember => "Ember",+ SyntaxStyle::Tide => "Tide",+ SyntaxStyle::Orchard => "Orchard",+ SyntaxStyle::Quiet => "Quiet",+ }+ }++ /// The style as a syntect theme, for dark or light backgrounds. Plain text is left+ /// transparent: it takes the editor's text colour.+ pub fn theme(self, dark: bool) -> &'static Theme {+ static THEMES: OnceLock<Vec<Theme>> = OnceLock::new();+ let themes = THEMES.get_or_init(|| {+ Self::ALL+ .iter()+ .flat_map(|s| [s.build(true), s.build(false)])+ .collect()+ });+ let i = Self::ALL.iter().position(|s| *s == self).unwrap_or(0) * 2 + usize::from(!dark);+ &themes[i]+ }++ fn palette(self, dark: bool) -> Palette {+ match (self, dark) {+ (SyntaxStyle::Ember, true) => Palette {+ comment: 0x7d756c,+ keyword: 0xf28c5b,+ operator: Some(0xd9a385),+ string: 0xb5c77a,+ number: 0xd49be0,+ function: Some(0xf2c96b),+ kind: 0x7fc8c2,+ macros: 0xe6828f,+ this: 0xe6828f,+ namespace: Some(0xc9b79c),+ },+ (SyntaxStyle::Ember, false) => Palette {+ comment: 0x8c857c,+ keyword: 0xc2501b,+ operator: Some(0xa0622e),+ string: 0x5e7a1e,+ number: 0x8a3fa0,+ function: Some(0x9a6a00),+ kind: 0x1e7f78,+ macros: 0xb53a4c,+ this: 0xb53a4c,+ namespace: Some(0x7a6648),+ },+ (SyntaxStyle::Tide, true) => Palette {+ comment: 0x6a7a8c,+ keyword: 0x6fa8f7,+ operator: Some(0x8fb3d9),+ string: 0x7fd1b9,+ number: 0xf5b971,+ function: Some(0x82d3f0),+ kind: 0xb49cf5,+ macros: 0xf08fb5,+ this: 0xf08fb5,+ namespace: Some(0xa9bcd6),+ },+ (SyntaxStyle::Tide, false) => Palette {+ comment: 0x7d8a99,+ keyword: 0x1d5fc4,+ operator: Some(0x3f6a99),+ string: 0x0e7c64,+ number: 0xb0620c,+ function: Some(0x0b7aa3),+ kind: 0x6a45c9,+ macros: 0xb8336e,+ this: 0xb8336e,+ namespace: Some(0x4a5f7d),+ },+ (SyntaxStyle::Orchard, true) => Palette {+ comment: 0x6f7782,+ keyword: 0xc38ae6,+ operator: Some(0x5cc9c9),+ string: 0x98c97a,+ number: 0xe8a56a,+ function: Some(0x6eb4f0),+ kind: 0xe9c46a,+ macros: 0x5cc9c9,+ this: 0xe87a7a,+ namespace: Some(0xe9c46a),+ },+ (SyntaxStyle::Orchard, false) => Palette {+ comment: 0x8a9099,+ keyword: 0x8a3fb8,+ operator: Some(0x157f82),+ string: 0x3f7f2a,+ number: 0xb5600e,+ function: Some(0x1f64b8),+ kind: 0x946c00,+ macros: 0x157f82,+ this: 0xc03d3d,+ namespace: Some(0x946c00),+ },+ (SyntaxStyle::Quiet, true) => Palette {+ comment: 0x6b6b6b,+ keyword: 0x8fa8c8,+ operator: None,+ string: 0xa8c49a,+ number: 0xc8a88f,+ function: None,+ kind: 0xb8b0d0,+ macros: 0x8fa8c8,+ this: 0x8fa8c8,+ namespace: None,+ },+ (SyntaxStyle::Quiet, false) => Palette {+ comment: 0x9a9a9a,+ keyword: 0x3d5f8a,+ operator: None,+ string: 0x4e7240,+ number: 0x8a5a35,+ function: None,+ kind: 0x5a4e86,+ macros: 0x3d5f8a,+ this: 0x3d5f8a,+ namespace: None,+ },+ }+ }++ fn build(self, dark: bool) -> Theme {+ let p = self.palette(dark);+ let rules: [(&str, Option<u32>); 12] = [+ ("comment, punctuation.definition.comment", Some(p.comment)),+ (+ "keyword, storage, entity.name.tag, markup.heading",+ Some(p.keyword),+ ),+ ("keyword.operator", p.operator),+ ("string, punctuation.definition.string", Some(p.string)),+ (+ "constant.numeric, constant.language, constant.character, constant.other, markup.bold",+ Some(p.number),+ ),+ (+ "entity.name.function, support.function, variable.function, \+ meta.function-call.identifier, entity.other.attribute-name",+ p.function,+ ),+ (+ "entity.name.type, entity.name.struct, entity.name.enum, entity.name.trait, \+ entity.name.class, entity.name.impl, support.type, support.class, \+ storage.type.primitive, storage.type.numeric",+ Some(p.kind),+ ),+ (+ "entity.name.macro, support.macro, entity.name.function.macro, \+ meta.annotation, meta.attribute, punctuation.definition.annotation",+ Some(p.macros),+ ),+ ("variable.language", Some(p.this)),+ ("entity.name.namespace, entity.name.module", p.namespace),+ ("markup.inline.raw, markup.raw", Some(p.string)),+ ("invalid", Some(0xe05252)),+ ];+ let color = |rgb: u32| Color {+ r: (rgb >> 16) as u8,+ g: (rgb >> 8) as u8,+ b: rgb as u8,+ a: 0xff,+ };+ Theme {+ name: Some(format!(+ "gitcraft {} {}",+ self.label(),+ if dark { "Dark" } else { "Light" }+ )),+ settings: ThemeSettings {+ foreground: Some(Color {+ r: 0,+ g: 0,+ b: 0,+ a: 0,+ }),+ ..Default::default()+ },+ scopes: rules+ .iter()+ .filter_map(|(selector, rgb)| {+ Some(ThemeItem {+ scope: selector.parse().ok()?,+ style: StyleModifier {+ foreground: Some(color((*rgb)?)),+ background: None,+ font_style: None,+ },+ })+ })+ .collect(),+ ..Default::default()+ }+ }+}diff --git a/src/git.rs b/src/git.rsindex 3eaf6b9..0b6eacd 100644--- a/src/git.rs+++ b/src/git.rs@@ -54,7 +54,7 @@ pub fn run_bytes(dir: Option<&Path>, args: &[&str]) -> Result<Vec<u8>, String> {/// 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> {- run_inner(dir, args, ok, None)+ run_inner(dir, args, ok, None, true)}/// A username and password (or token) for an HTTPS remote, typed into gitcraft.@@ -75,7 +75,17 @@ pub fn run_with(args: &[&str],creds: Option<&Credentials>,) -> Result<String, String> {- run_inner(dir, args, &[0], creds)+ run_inner(dir, args, &[0], creds, true)+}++/// [`run_with`] for work in the background (the periodic fetch): ssh asks the user nothing and+/// fails instead, as it can't be answered by someone who didn't start it.+pub fn run_quiet_with(+ dir: Option<&Path>,+ args: &[&str],+ creds: Option<&Credentials>,+) -> Result<String, String> {+ run_inner(dir, args, &[0], creds, false)}/// Whether `err` says git needed a username / password it couldn't get or that were refused.@@ -100,8 +110,12 @@ fn run_inner(args: &[&str],ok: &[i32],creds: Option<&Credentials>,+ ask: bool,) -> Result<String, String> {let mut cmd = git_cmd();+ if ask {+ crate::askpass::apply(&mut cmd);+ }if let Some(dir) = dir {cmd.arg("-C").arg(dir);}@@ -272,25 +286,23 @@ pub struct Commit {pub refs: Vec<String>,}-/// 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> {+/// The commits reachable from `revs` (every branch but the stash, unless the graph hides or+/// solos some), newest first, in an order fit for drawing the graph: `limit` of them after the+/// first `skip`.+pub fn log(repo: &Path, revs: &[String], 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{FS}%b{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,- ],- ) {+ let mut args = vec!["log"];+ args.extend(revs.iter().map(String::as_str));+ args.extend([+ "--date-order",+ "--date=format-local:%Y-%m-%d %H:%M",+ &skip,+ &limit,+ &format,+ ]);+ let out = match run(Some(repo), &args) {Ok(out) => out,// A freshly initialised repository has no commits yet.Err(e) if e.contains("does not have any commits") => String::new(),diff --git a/src/icons.rs b/src/icons.rsindex 18dee80..2404732 100644--- a/src/icons.rs+++ b/src/icons.rs@@ -35,6 +35,8 @@ const SOURCES: &[(&str, &str)] = icons!["copy","database","external-link",+ "eye",+ "eye-off","file-diff","flask-conical","folder-git-2",@@ -50,6 +52,7 @@ const SOURCES: &[(&str, &str)] = icons!["heart","history","laptop",+ "list","log-in","minus","package",diff --git a/src/lib.rs b/src/lib.rsindex e510d38..30f06b6 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -1,7 +1,9 @@//! gitcraft: a small, personal visual git client (egui front end over the git command line).pub mod app;+pub mod askpass;mod avatars;+mod code_theme;mod desktop_entry;mod forge;mod git;@@ -15,4 +17,4 @@ mod tab_look;mod terminal;mod theme;mod update;-mod vscode_theme;+mod vscode;diff --git a/src/main.rs b/src/main.rsindex be26987..cc303ed 100644--- a/src/main.rs+++ b/src/main.rs@@ -6,6 +6,10 @@ use std::sync::atomic::Ordering;use gitcraft::app;fn main() -> eframe::Result {+ // Started by ssh to ask the user something (see `askpass`): ask the window and exit.+ if let Some(code) = gitcraft::askpass::run_if_asked() {+ std::process::exit(code);+ }let options = eframe::NativeOptions {viewport: egui::ViewportBuilder::default().with_title("GitCraft")diff --git a/src/manual.rs b/src/manual.rsindex 2aad2b5..069598f 100644--- a/src/manual.rs+++ b/src/manual.rs@@ -21,6 +21,7 @@ const FEATURES: &[(&str, &[&str])] = &["Open, create or clone a repository from the start page; recent ones are listed there.","One tab per repository. Changes made elsewhere (editor, terminal) show up by themselves.","Right-click a tab to give it its own icon and highlight colour.",+ "Settings › Themes: four code styles, or a VS Code theme imported from your VS Code, which colours the whole window. The palette icon switches between Dark, Medium Gray and Light.","Drag a tab along the strip to reorder the tabs.",],),@@ -28,10 +29,13 @@ const FEATURES: &[(&str, &[&str])] = &["Graph",&["Every branch with its pill on its latest commit: solid for the checked-out one, a laptop when it is local, a cloud when a remote has it.",- "Double-click a pill to check that branch out (and pull it when its remote is ahead; on the checked-out branch's remote pill, just pull); hover +N to see every branch of the commit, and right-click any of them.",+ "Double-click a pill to check that branch out; hover +N to see every branch of the commit, and right-click any of them.",+ "Double-click a branch's pill further on than the branch (its remote, say) to move the branch there: your uncommitted changes are stashed and brought back on top. When the two have diverged, the toolbar offers to rebase, merge or reset instead.",+ "Hover a branch in the left pane for its eye: hide it from the graph, or right-click it and Solo to draw only that one. The headers count the branches shown; the toolbar shows them all again.","Right-click a commit or a pill for branches, tags, merge, rebase, cherry-pick, revert, reset and more.","Search messages, authors and hashes, or switch to Code to find the commits that added or removed some text.","Interactive rebase: reorder, reword, squash, fix up or drop commits, then start it.",+ "Right-click a commit of the checked-out branch to edit its message, move it up or down, or drop it, without the rebase screen.","Stashes show in the graph as dashed boxes above the commit they were made on; click one to see it, right-click it to apply, pop or drop it.",],),@@ -47,7 +51,9 @@ const FEATURES: &[(&str, &[&str])] = &[&["Stage, unstage or discard whole files from the right pane.","In a file's diff, stage, unstage or discard one hunk, or click the lines you want and act on only those.",- "A diff shows only the changes or the whole file, unified or side by side, and remembers both. Drag over its lines to select text and Ctrl+C to copy it; the strip by the scrollbar marks where the changes are.",+ "A diff shows only the changes or the whole file, unified or side by side, and remembers both. Drag over its lines to select text and Ctrl+C to copy it; the strip by the scrollbar marks where the changes are, and the arrows (Alt+Up / Alt+Down) jump between them.",+ "A commit's files as a list of paths or a tree of folders: the switch above them.",+ "Double-click a line of a diff (or right-click it) to open the file in your editor at that line; the <> button opens it at the first change. The editor is set in Settings.","Write the summary and description and commit; amend the last commit; pick the identity you commit as.","Double-click a commit's message in the right pane to edit it (any commit of the checked-out branch with no merges after it).","Undo and redo commits, merges, rebases, resets, checkouts, branches, tags and stashes.",@@ -60,6 +66,7 @@ const FEATURES: &[(&str, &[&str])] = &["Conflicts open in a three-pane editor with Ours, Theirs and Both for each conflict.","Right-click a file for its history and blame.","A terminal panel with tabs, in the repository's folder.",+ "When ssh needs a password, a key's passphrase or to trust a new host, gitcraft asks in a dialog (macOS and Linux).",],),];@@ -71,6 +78,7 @@ const SHORTCUTS: &[(&str, &[(&str, &str)])] = &[&[("Cmd+T", "New tab"),("Cmd+W", "Close the tab (or middle-click it)"),+ ("Cmd+Shift+T", "Reopen the tab closed last"),("Cmd+P", "Command palette: every action and branch"),("F5", "Reload the repository"),("F1", "This manual"),@@ -83,7 +91,10 @@ const SHORTCUTS: &[(&str, &[(&str, &str)])] = &[("Cmd+F", "Search commits"),("Enter / Shift+Enter", "Next / previous search result"),("Cmd+click", "Compare with the selected commit"),- ("Double-click a pill", "Check out that branch or tag"),+ (+ "Double-click a pill",+ "Check out that branch or tag, or move it there",+ ),("Esc", "Close the diff, comparison or search"),],),@@ -91,6 +102,7 @@ const SHORTCUTS: &[(&str, &[(&str, &str)])] = &["Changes",&[("Cmd+Enter", "Commit (from the message fields)"),+ ("Alt+↑ / Alt+↓", "Previous / next change in a diff"),("Click / Shift+click","Pick lines in a diff, or a range of them",diff --git a/src/repo/branch_filter.rs b/src/repo/branch_filter.rsnew file mode 100644index 0000000..0149de0--- /dev/null+++ b/src/repo/branch_filter.rs@@ -0,0 +1,122 @@+//! Branches hidden from the graph, or shown alone ("solo"), as GitKraken does: in a repository+//! with hundreds of branches, the graph only draws the ones that matter. A hidden branch's own+//! commits leave the graph; commits other branches share stay. Kept per repository.++use std::collections::BTreeSet;++use serde::{Deserialize, Serialize};++/// Full ref names (`refs/heads/x`, `refs/remotes/origin/x`).+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(default)]+pub struct BranchFilter {+ pub hidden: BTreeSet<String>,+ /// When any, only these are drawn (and HEAD).+ pub solo: BTreeSet<String>,+}++/// What the user asked of a branch's visibility.+pub(crate) enum Change {+ /// The eye: hidden ↔ shown (while soloing: in the solo ↔ out of it).+ Toggle(String),+ Solo(String),+ Unsolo(String),+ /// Everything shown again.+ Clear,+}++pub fn local_ref(name: &str) -> String {+ format!("refs/heads/{name}")+}++/// `origin/main` → `refs/remotes/origin/main`.+pub fn remote_ref(name: &str) -> String {+ format!("refs/remotes/{name}")+}++impl BranchFilter {+ pub fn is_active(&self) -> bool {+ !self.hidden.is_empty() || !self.solo.is_empty()+ }++ pub fn shows(&self, full: &str) -> bool {+ if self.solo.is_empty() {+ !self.hidden.contains(full)+ } else {+ self.solo.contains(full)+ }+ }++ pub fn soloed(&self, full: &str) -> bool {+ self.solo.contains(full)+ }++ pub(crate) fn apply(&mut self, change: Change) {+ match change {+ Change::Toggle(full) if !self.solo.is_empty() => {+ if !self.solo.remove(&full) {+ self.solo.insert(full);+ }+ }+ Change::Toggle(full) => {+ if !self.hidden.remove(&full) {+ self.hidden.insert(full);+ }+ }+ Change::Solo(full) => {+ self.hidden.remove(&full);+ self.solo.insert(full);+ }+ Change::Unsolo(full) => {+ self.solo.remove(&full);+ }+ Change::Clear => *self = BranchFilter::default(),+ }+ }++ /// What `git log` is given to walk: every ref but the hidden ones (and the stash), or the+ /// soloed ones and HEAD. Refs that no longer exist are skipped.+ pub fn revs(&self) -> Vec<String> {+ let mut revs = vec!["--ignore-missing".to_owned()];+ if self.solo.is_empty() {+ revs.push("--exclude=refs/stash".to_owned());+ revs.extend(self.hidden.iter().map(|r| format!("--exclude={r}")));+ revs.push("--all".to_owned());+ } else {+ revs.extend(self.solo.iter().cloned());+ revs.push("HEAD".to_owned());+ }+ revs+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn hiding_and_soloing() {+ let mut f = BranchFilter::default();+ let (a, b) = (local_ref("a"), remote_ref("origin/b"));+ assert!(f.shows(&a) && !f.is_active());+ f.apply(Change::Toggle(a.clone()));+ assert!(!f.shows(&a) && f.shows(&b));+ assert!(f.revs().contains(&"--exclude=refs/heads/a".to_owned()));+ // Soloing shows only the solo, whatever was hidden; the eye then adds to the solo.+ f.apply(Change::Solo(b.clone()));+ assert!(f.shows(&b) && !f.shows(&a));+ f.apply(Change::Toggle(a.clone()));+ assert!(f.shows(&a));+ assert_eq!(+ f.revs(),+ [+ "--ignore-missing",+ "refs/heads/a",+ "refs/remotes/origin/b",+ "HEAD"+ ]+ );+ f.apply(Change::Clear);+ assert!(!f.is_active());+ }+}diff --git a/src/repo/detail.rs b/src/repo/detail.rsindex 8331a11..54ee581 100644--- a/src/repo/detail.rs+++ b/src/repo/detail.rs@@ -1,12 +1,13 @@//! Right pane: the selected commit, or the working-tree changes with staging and the commit box.-use egui::{Align2, Key, RichText, Sense, Ui, pos2, vec2};+use egui::{Align2, Key, Rect, RichText, Sense, Ui, pos2, vec2};use super::diff::unstage_args;use super::widgets::{self, RowExtra};use super::{Action, Dialog, DiffKey, DiffView, Refresh, RepoTab, Reword, abort_action, ops};use crate::git::{Area, ChangedFile, StatusFile};use crate::icons;+use crate::settings::Settings;use crate::theme::{self, Tokens};impl RepoTab {@@ -87,6 +88,11 @@ impl RepoTab {// Taken out while the pane borrows `self`; put back after it.let mut reword = self.reword.take();+ // "Edit message…" from the commit's menu, now that its details are here.+ let wants_edit = self.edit_message.as_deref() == Some(detail.hash.as_str());+ if wants_edit {+ self.edit_message = None;+ }let head = self.refs.head.clone();egui::ScrollArea::vertical().id_salt("detail_scroll")@@ -153,7 +159,7 @@ impl RepoTab {).double_clicked();}- if clicked && editable {+ if (clicked || wants_edit) && editable {reword = Some(Reword {hash: detail.hash.clone(),subject: subject.to_owned(),@@ -264,6 +270,10 @@ impl RepoTab {rev: Option<&str>,key: impl Fn(&str) -> DiffKey,) {+ if Settings::get(ui.ctx()).files_as_tree {+ let tree = FileTree::build(files);+ return self.file_tree(ui, acts, &tree, "", 0, rev, &key);+ }for f in files {let key = key(&f.path);let selected = self.open_key() == Some(&key);@@ -282,6 +292,96 @@ impl RepoTab {}}+ /// One folder of [`FileTree`]: its subfolders (collapsible), then its files, `depth` in.+ #[allow(clippy::too_many_arguments)]+ fn file_tree(+ &self,+ ui: &mut Ui,+ acts: &mut Vec<Action>,+ folder: &FileTree<'_>,+ parent: &str,+ depth: usize,+ rev: Option<&str>,+ key: &dyn Fn(&str) -> DiffKey,+ ) {+ let t = Tokens::get(ui.ctx());+ let indent = depth as f32 * TREE_INDENT;+ for (name, sub) in &folder.folders {+ // A folder holding only one folder reads as one row: `src/repo`.+ let (mut name, mut sub) = (name.clone(), sub);+ while sub.files.is_empty() && sub.folders.len() == 1 {+ let Some((next, inner)) = sub.folders.iter().next() else {+ break;+ };+ name = format!("{name}/{next}");+ sub = inner;+ }+ let path = if parent.is_empty() {+ name.clone()+ } else {+ format!("{parent}/{name}")+ };+ let id = ui.id().with(("files-folder", &path));+ let mut open = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(true);+ let (rect, r) =+ ui.allocate_exact_size(vec2(ui.available_width(), widgets::ROW_H), Sense::click());+ if r.hovered() {+ ui.painter().rect_filled(rect, 0.0, t.hover);+ }+ if r.clicked() {+ open = !open;+ ui.data_mut(|d| d.insert_temp(id, open));+ }+ let y = rect.center().y;+ let x = rect.left() + indent;+ icons::paint(+ ui,+ Rect::from_center_size(pos2(x + 12.0, y), vec2(12.0, 12.0)),+ if open {+ "chevron-down"+ } else {+ "chevron-right"+ },+ 11.0,+ t.text_faint,+ );+ icons::paint(+ ui,+ Rect::from_center_size(pos2(x + 28.0, y), vec2(14.0, 14.0)),+ "folder-open",+ 13.0,+ t.text_dim,+ );+ ui.painter_at(rect).text(+ pos2(x + 42.0, y),+ Align2::LEFT_CENTER,+ &name,+ egui::FontId::proportional(12.5),+ t.text_dim,+ );+ if open {+ self.file_tree(ui, acts, sub, &path, depth + 1, rev, key);+ }+ }+ for f in &folder.files {+ let k = key(&f.path);+ let selected = self.open_key() == Some(&k);+ let r = widgets::file_row_in(+ ui,+ f.status,+ &f.path,+ f.old_path.as_deref(),+ Some(indent + 16.0),+ selected,+ RowExtra::Stats(f.added, f.removed),+ );+ widgets::file_menu(&r.row, &f.path, rev, false, acts);+ if r.row.clicked() {+ acts.push(Action::OpenDiff(k));+ }+ }+ }+/// Right pane while comparing: the two ends, how far apart they are, and the files that/// differ.fn compare_panel(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {@@ -733,7 +833,33 @@ fn discard_dialog(f: &StatusFile) -> Dialog {}}-/// "N files changed +a −d", and an optional note on the right.+/// How much further in each level of a file tree is.+const TREE_INDENT: f32 = 14.0;++/// Changed files grouped by folder, for the tree view.+#[derive(Default)]+struct FileTree<'a> {+ folders: std::collections::BTreeMap<String, FileTree<'a>>,+ files: Vec<&'a ChangedFile>,+}++impl<'a> FileTree<'a> {+ fn build(files: &'a [ChangedFile]) -> Self {+ let mut root = FileTree::default();+ for f in files {+ let mut node = &mut root;+ let mut parts: Vec<&str> = f.path.split('/').collect();+ parts.pop();+ for part in parts {+ node = node.folders.entry(part.to_owned()).or_default();+ }+ node.files.push(f);+ }+ root+ }+}++/// "N files changed +a −d", an optional note, and the Path / Tree switch on the right.fn files_header(ui: &mut Ui, files: &[ChangedFile], note: Option<&str>) {let t = Tokens::get(ui.ctx());let (adds, dels) = files.iter().fold((0, 0), |(a, d), f| {@@ -768,9 +894,44 @@ fn files_header(ui: &mut Ui, files: &[ChangedFile], note: Option<&str>) {theme::mono(11.0),t.danger,);+ // Path / Tree, the one in use underlined.+ let mut settings = Settings::get(ui.ctx());+ let mut right = rect.right() - 6.0;+ for (tree, icon, tip) in [+ (true, "folder-tree", "Files in a tree of their folders"),+ (false, "list", "Files as a list of paths"),+ ] {+ let r = Rect::from_center_size(pos2(right - 10.0, y), vec2(20.0, 20.0));+ let b = ui+ .interact(r, ui.id().with(("files-view", tree)), Sense::click())+ .on_hover_text(tip);+ let on = settings.files_as_tree == tree;+ if b.hovered() {+ ui.painter().rect_filled(r, t.radius_sm, t.pressed);+ }+ icons::paint(+ ui,+ r,+ icon,+ 13.0,+ if on || b.hovered() {+ t.text+ } else {+ t.text_faint+ },+ );+ if on {+ widgets::active_underline(ui, r, t.accent);+ }+ if b.clicked() && !on {+ settings.files_as_tree = tree;+ settings.set(ui.ctx());+ }+ right = r.left() - 2.0;+ }if let Some(note) = note {- p.text(- pos2(rect.right() - 10.0, y),+ ui.painter().text(+ pos2(right - 6.0, y),Align2::RIGHT_CENTER,note,egui::FontId::proportional(11.0),diff --git a/src/repo/diff.rs b/src/repo/diff.rsindex 5909c87..f14c358 100644--- a/src/repo/diff.rs+++ b/src/repo/diff.rs@@ -594,6 +594,17 @@ impl RepoTab {settings.diff_whole_file,);let mut clear = false;+ // -1 / 1: to the change before / after what is on screen.+ let mut jump: i32 = 0;+ if !self.keys_blocked && !ui.ctx().egui_wants_keyboard_input() {+ ui.input(|i| {+ if i.modifiers.alt && i.key_pressed(egui::Key::ArrowUp) {+ jump = -1;+ } else if i.modifiers.alt && i.key_pressed(egui::Key::ArrowDown) {+ jump = 1;+ }+ });+ }egui::Frame::new().fill(t.chrome).inner_margin(egui::Margin::symmetric(10, 6))@@ -668,6 +679,37 @@ impl RepoTab {}}ui.add_space(8.0);+ if icons::small_button(ui, "chevron-down", "Next change (Alt+Down)")+ .clicked()+ {+ jump = 1;+ }+ if icons::small_button(ui, "chevron-up", "Previous change (Alt+Up)")+ .clicked()+ {+ jump = -1;+ }+ ui.add_space(4.0);+ let first_change = match &view.data {+ Some(Ok(d)) => d+ .lines+ .iter()+ .position(|l| matches!(l.kind, Kind::Add | Kind::Del))+ .and_then(|i| editor_line(&d.lines, i)),+ _ => None,+ };+ if icons::small_button(+ ui,+ "code",+ "Open in the editor (or double-click a line to open it there)",+ )+ .clicked()+ {+ acts.push(match first_change {+ Some(line) => Action::OpenInEditorAt(path.clone().into(), line),+ None => Action::OpenInEditor(path.clone().into()),+ });+ }let ws = icons::small_button(ui,"pilcrow",@@ -798,6 +840,8 @@ impl RepoTab {// Each with whether the pointer is over that line's half, not only at its height.let mut pointer_hits: Vec<((usize, Side, usize), bool)> = Vec::new();let mut text_hover = false;+ // A line double-clicked: opened in the editor.+ let mut open_at: Option<usize> = None;let mut paint = |ui: &mut Ui, rect: Rect, i: usize, side: Side, scroll_x: f32| {let kind = data.lines.get(i).map(|l| l.kind);let pickable = partial && matches!(kind, Some(Kind::Add | Kind::Del));@@ -825,6 +869,9 @@ impl RepoTab {if resp.clicked() {clicked = Some(i);}+ if resp.double_clicked() {+ open_at = Some(i);+ }}if kind == Some(Kind::Hunk) && !hunk_picks.is_empty() {// At the visible right end, however wide the line is.@@ -875,6 +922,11 @@ impl RepoTab {let mut scroll = egui::ScrollArea::both().id_salt(("diff_scroll", &path, split)).auto_shrink(false);+ if jump != 0+ && let Some(y) = jump_target(&runs, view.scroll_y, jump)+ {+ scroll = scroll.vertical_scroll_offset(y);+ }if (map.clicked() || map.dragged())&& let Some(p) = map.interact_pointer_pos(){@@ -977,6 +1029,23 @@ impl RepoTab {ui.ctx().copy_text(text.clone());}}+ // The line under the pointer, on the half it is over.+ let line_under = pointer_hits+ .iter()+ .find(|(_, over)| *over)+ .map(|((i, _, _), _)| *i);+ if text_drag.double_clicked() {+ open_at = open_at.or(line_under);+ }+ if let Some(line) = open_at.and_then(|i| editor_line(&data.lines, i)) {+ acts.push(Action::OpenInEditorAt(path.clone().into(), line));+ }+ // Where the menu was opened, kept while it is open.+ let menu_line = ui.id().with("diff-menu-line");+ if text_drag.secondary_clicked() {+ let line = line_under.and_then(|i| editor_line(&data.lines, i));+ ui.data_mut(|d| d.insert_temp(menu_line, line));+ }egui::Popup::context_menu(&text_drag).style(crate::theme::menu_style).show(|ui| {@@ -987,9 +1056,22 @@ impl RepoTab {{ui.ctx().copy_text(text.clone());}+ ui.separator();+ let line = ui.data(|d| d.get_temp::<Option<u32>>(menu_line)).flatten();+ let label = match line {+ Some(n) => format!("Open in editor at line {n}"),+ None => "Open in editor".to_owned(),+ };+ if ui.button(label).clicked() {+ acts.push(match line {+ Some(n) => Action::OpenInEditorAt(path.clone().into(), n),+ None => Action::OpenInEditor(path.clone().into()),+ });+ }});if let Some(view) = &mut self.diff {+ view.scroll_y = shown.state.offset.y;view.text_sel = sel;if clear {view.chosen.clear();@@ -1182,6 +1264,33 @@ fn change_runs(rows: impl Iterator<Item = (bool, bool)>) -> ChangeRuns {runs}+/// Lines of context kept above a change jumped to.+const JUMP_CONTEXT: usize = 3;++/// Where to scroll to show the change before (`dir` -1) or after (1) the one at `scroll_y`,+/// with a few lines above it; `None` when there is none that way.+fn jump_target(runs: &ChangeRuns, scroll_y: f32, dir: i32) -> Option<f32> {+ // A removal and the addition right after it are one change.+ let mut all: Vec<Range<usize>> = runs.removed.iter().chain(&runs.added).cloned().collect();+ all.sort_by_key(|r| r.start);+ let mut starts: Vec<usize> = Vec::new();+ let mut end = 0;+ for r in all {+ if starts.is_empty() || r.start > end {+ starts.push(r.start);+ }+ end = end.max(r.end);+ }+ let offsets = starts+ .into_iter()+ .map(|row| row.saturating_sub(JUMP_CONTEXT) as f32 * LINE_H);+ if dir > 0 {+ offsets.into_iter().find(|y| *y > scroll_y + 1.0)+ } else {+ offsets.into_iter().rev().find(|y| *y < scroll_y - 1.0)+ }+}+/// The strip beside the diff's scrollbar: a mark for each run of changes where it sits in the/// file (side by side: removals on the left half, additions on the right), and the part on/// screen. `view`: (scroll offset, visible height, content height).@@ -1358,6 +1467,16 @@ fn paint_line(Some((origin, galley))}+/// The line of the file (as it is now) that diff line `i` stands for: its own new-side number,+/// or for a removed line the next line kept after it.+fn editor_line(lines: &[DiffLine], i: usize) -> Option<u32> {+ lines+ .get(i..)?+ .iter()+ .find_map(|l| l.new)+ .or_else(|| lines.get(..i)?.iter().rev().find_map(|l| l.new))+}+/// A layout job for `spans`, with the chars in `changed` on `strong`.fn line_job(spans: &[(Color32, &str)],diff --git a/src/repo/graph_view.rs b/src/repo/graph_view.rsindex 9b58259..ca44be9 100644--- a/src/repo/graph_view.rs+++ b/src/repo/graph_view.rs@@ -5,10 +5,11 @@ use egui::{Align2, Color32, CornerRadius, FontId, Key, Pos2, Rect, Response, Sense, Stroke, Ui, pos2, vec2,};+use super::branch_filter::{local_ref, remote_ref};use super::widgets;use super::{- Action, Dialog, Refresh, RepoTab, Undo, WIP_HASH, compare_action, fast_forward_action,- merge_action, ops, rebase_action,+ Action, Dialog, QuickEdit, Refresh, RepoTab, Undo, WIP_HASH, compare_action,+ fast_forward_action, merge_action, ops, rebase_action,};use crate::git::{self, Refs};use crate::icons;@@ -430,6 +431,52 @@ impl RepoTab {});}ui.separator();+ // Quick edits of a commit of the checked-out branch; the rebase they run says when one+ // can't be done (a commit elsewhere, merges after it).+ let in_branch = self.refs.current.is_some();+ let has_parent = !commit.parents.is_empty();+ if ui+ .add_enabled(idle && in_branch, egui::Button::new("Edit message…"))+ .clicked()+ {+ acts.push(Action::EditMessage(hash.clone()));+ }+ if ui+ .add_enabled(idle && in_branch && !is_head, egui::Button::new("Move up"))+ .on_hover_text("Swap it with the commit after it")+ .clicked()+ {+ acts.push(Action::QuickEdit(hash.clone(), QuickEdit::MoveUp));+ }+ let grandparent = commit+ .parents+ .first()+ .and_then(|p| self.index.get(p))+ .and_then(|&row| self.commits.get(row))+ .is_some_and(|p| !p.parents.is_empty());+ if ui+ .add_enabled(+ idle && in_branch && grandparent,+ egui::Button::new("Move down"),+ )+ .on_hover_text("Swap it with the commit before it")+ .clicked()+ {+ acts.push(Action::QuickEdit(hash.clone(), QuickEdit::MoveDown));+ }+ if ui+ .add_enabled(+ idle && in_branch && has_parent,+ egui::Button::new("Drop commit"),+ )+ .on_hover_text(+ "Remove the commit and its changes from the branch (Undo brings it back)",+ )+ .clicked()+ {+ acts.push(Action::QuickEdit(hash.clone(), QuickEdit::Drop));+ }+ ui.separator();if ui.add_enabled(idle && !is_head,@@ -508,39 +555,54 @@ impl RepoTab {/// a remote, and pulling a local one behind its upstream) or tag; pull when it is the/// checked-out branch's remote, further on. Nothing for the checked-out one or while an/// operation runs.+ /// The pills of branches the graph shows: hidden branches (and those left out of a solo)+ /// lose theirs, even on commits other branches still bring into the graph.+ fn shown_badges(&self, badges: Vec<Badge>) -> Vec<Badge> {+ let f = &self.graph_filter;+ if !f.is_active() {+ return badges;+ }+ badges+ .into_iter()+ .filter_map(|mut b| {+ if b.kind != BadgeKind::Branch {+ return Some(b);+ }+ let label = b.label.clone();+ b.remotes+ .retain(|r| f.shows(&remote_ref(&format!("{r}/{label}"))));+ b.local = b.local && (b.head || f.shows(&local_ref(&label)));+ (b.head || b.local || !b.remotes.is_empty()).then_some(b)+ })+ .collect()+ }+fn pill_checkout(&self, badge: &Badge) -> Option<Action> {if badge.head || self.busy_op.is_some() {return None;}- // The checked-out branch's remote pill, further on than the branch: pull.- let current = self.refs.current.as_deref() == Some(badge.label.as_str());- if badge.kind == BadgeKind::Branch && !badge.local && current {- let behind = self- .refs- .local- .iter()- .find(|b| b.name == badge.label)- .is_some_and(|b| b.ahead_behind().1 > 0);- return behind.then_some(Action::Pull);- }+ let local = self.refs.local.iter().find(|b| b.name == badge.label);+ let behind = local.is_some_and(|b| b.ahead_behind().1 > 0);match badge.kind {- BadgeKind::Branch if badge.local => {- let behind = self- .refs- .local- .iter()- .find(|b| b.name == badge.label)- .is_some_and(|b| matches!(b.ahead_behind(), (0, behind) if behind > 0));- Some(if behind {- Action::CheckoutPull(badge.label.clone())- } else {- Action::Checkout(badge.label.clone())+ // A local branch its remote is further on than: there, with the changes kept.+ BadgeKind::Branch if badge.local => Some(match local {+ Some(b) if behind && !b.upstream.is_empty() => Action::MoveBranch {+ branch: b.name.clone(),+ target: b.upstream.clone(),+ },+ _ => Action::Checkout(badge.label.clone()),+ }),+ // A remote pill further on than its local branch: the local branch moves here.+ BadgeKind::Branch => {+ let remote = format!("{}/{}", badge.remotes.first()?, badge.label);+ Some(match local {+ Some(b) if behind && b.upstream == remote => Action::MoveBranch {+ branch: b.name.clone(),+ target: remote,+ },+ _ => Action::CheckoutRemote(remote),})}- BadgeKind::Branch => badge- .remotes- .first()- .map(|remote| Action::CheckoutRemote(format!("{remote}/{}", badge.label))),BadgeKind::Tag => Some(Action::Checkout(format!("refs/tags/{}", badge.label))),BadgeKind::DetachedHead => None,}@@ -603,7 +665,9 @@ impl RepoTab {ref_pill(ui, ui.painter(), slot.left_center(), b, lane, slot_w, pr);let hint = match self.pill_checkout(b) {_ if b.head => "checked out",- Some(Action::Pull) => "double-click to pull",+ Some(Action::MoveBranch { .. }) => {+ "double-click to move the branch here"+ }_ => "double-click to check out",};let resp = resp.on_hover_text(format!("{} ({hint})", b.describe()));@@ -791,7 +855,7 @@ impl RepoTab {// 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 badges = self.shown_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));@@ -994,6 +1058,17 @@ impl RepoTab {} else {FontId::proportional(12.5)};+ // A stash is marked before its message, to tell it from the commits around it.+ if stash.is_some() {+ icons::paint(+ ui,+ Rect::from_center_size(pos2(x + 9.0, mid), vec2(14.0, 14.0)),+ "archive",+ 13.0,+ t.text_dim,+ );+ x += 20.0;+ }// The summary, then the rest of the message faded, cut with an ellipsis.let text_clip = painter.with_clip_rect(Rect::from_min_max(pos2(x, rect.top()),diff --git a/src/repo/highlight.rs b/src/repo/highlight.rsindex a753b69..66098e5 100644--- a/src/repo/highlight.rs+++ b/src/repo/highlight.rs@@ -1,12 +1,14 @@//! Syntax colouring for diffs (syntect with bat's syntaxes, pure-Rust regex engine), chosen by-//! file extension or name.+//! file extension or name, in the colours picked in the settings (see `crate::code_theme`).use std::sync::OnceLock;use egui::Color32;use syntect::easy::HighlightLines;-use syntect::highlighting::ThemeSet;-use syntect::parsing::SyntaxSet;+use syntect::highlighting::Theme;+use syntect::parsing::{SyntaxReference, SyntaxSet};++use crate::theme::{ThemeKind, Tokens};/// Coloured pieces of one line.pub type Spans = Vec<(Color32, String)>;@@ -19,9 +21,16 @@ fn syntaxes() -> &'static SyntaxSet {SET.get_or_init(two_face::syntax::extra_newlines)}-fn themes() -> &'static ThemeSet {- static SET: OnceLock<ThemeSet> = OnceLock::new();- SET.get_or_init(ThemeSet::load_defaults)+/// The syntax for `path`, by extension or by the whole name for files like `Dockerfile` and+/// `Makefile`; `None` for plain text.+fn syntax_for(path: &str) -> Option<&'static SyntaxReference> {+ let ss = syntaxes();+ let file = std::path::Path::new(path);+ let name = file.file_name()?.to_string_lossy();+ file.extension()+ .and_then(|e| ss.find_syntax_by_extension(&e.to_string_lossy().to_lowercase()))+ .or_else(|| ss.find_syntax_by_extension(&name))+ .filter(|s| s.name != "Plain Text")}/// Colours `lines` (one file's text, in order) for `path`; `None` for plain text, unknown@@ -34,30 +43,35 @@ pub fn highlight<'a>(if lines.len() > MAX_LINES {return None;}+ let syntax = syntax_for(path)?;+ let theme = crate::code_theme::current_theme(dark);+ // gitcraft's styles leave plain text uncoloured, for the text colour of the theme.+ let plain = Tokens::for_kind(if dark {+ ThemeKind::Dark+ } else {+ ThemeKind::Light+ })+ .text;+ colour(syntax, &theme, lines, plain)+}++/// Colours `lines` of `path` with `theme`, plain text in `plain`: the settings' theme previews.+pub fn highlight_with<'a>(+ path: &str,+ theme: &Theme,+ lines: impl Iterator<Item = &'a str>,+ plain: Color32,+) -> Option<Vec<Spans>> {+ colour(syntax_for(path)?, theme, lines, plain)+}++fn colour<'a>(+ syntax: &SyntaxReference,+ theme: &Theme,+ lines: impl Iterator<Item = &'a str>,+ plain: Color32,+) -> Option<Vec<Spans>> {let ss = syntaxes();- let file = std::path::Path::new(path);- let name = file.file_name()?.to_string_lossy();- // By extension, or by the whole name for files like `Dockerfile` and `Makefile`.- let syntax = file- .extension()- .and_then(|e| ss.find_syntax_by_extension(&e.to_string_lossy().to_lowercase()))- .or_else(|| ss.find_syntax_by_extension(&name))?;- if syntax.name == "Plain Text" {- return None;- }- // VS Code's theme when it suits the background: a dark theme on a light gitcraft reads badly.- let editor = crate::vscode_theme::enabled()- .then(crate::vscode_theme::current)- .flatten()- .filter(|e| e.dark == dark);- let theme = match &editor {- Some(e) => &e.theme,- None => themes().themes.get(if dark {- "base16-ocean.dark"- } else {- "InspiredGitHub"- })?,- };let mut h = HighlightLines::new(syntax, theme);let mut out = Vec::new();for line in lines {@@ -68,10 +82,12 @@ pub fn highlight<'a>(.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(),- )+ let color = if c.a == 0 {+ plain+ } else {+ Color32::from_rgb(c.r, c.g, c.b)+ };+ (color, text.trim_end_matches('\n').to_owned())}).filter(|(_, t)| !t.is_empty()).collect(),diff --git a/src/repo/mod.rs b/src/repo/mod.rsindex 178a1d0..4442012 100644--- a/src/repo/mod.rs+++ b/src/repo/mod.rs@@ -1,13 +1,14 @@//! 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 branch_filter;mod conflict;mod detail;mod dialogs;mod diff;mod file_view;mod graph_view;-mod highlight;+pub(crate) mod highlight;mod rebase;mod sidebar;pub(crate) mod widgets;@@ -29,6 +30,7 @@ use crate::icons;use crate::settings::Settings;use crate::terminal::{ShellSpec, Terminal};use crate::theme::Tokens;+pub(crate) use branch_filter::BranchFilter;pub use dialogs::Dialog;pub use widgets::primary_button;@@ -59,10 +61,10 @@ enum Msg {/// A comparison's files, for the request numbered so.Compare(u64, Result<CompareData, String>),Prs(Result<Vec<PullRequest>, String>),- /// The commits to replay when rewording `hash`.- RewordCommits {+ /// The commits to replay for a quick edit of `hash`.+ QuickEditCommits {hash: String,- message: String,+ edit: QuickEdit,result: Result<Vec<git::RebaseCommit>, String>,},OpDone {@@ -124,6 +126,19 @@ struct PendingOp {refresh: Refresh,kind: OpKind,quiet: bool,+ autostash: bool,+}++/// Uncommitted changes stashed around an operation and applied again after it.+const AUTOSTASH: &str = "gitcraft: autostash";+/// Starts the error of an operation whose stashed changes didn't apply cleanly after it.+const AUTOSTASH_CONFLICT: &str = "Your changes conflict with the new files";++/// Choices shown in place of the toolbar for a moment, when what was asked needs one.+pub(crate) struct Prompt {+ text: String,+ /// (label, tooltip, what it does, whether it throws something away)+ options: Vec<(String, String, Action, bool)>,}#[derive(Clone, Debug)]@@ -161,6 +176,8 @@ pub(crate) struct DiffView {/// The latest read of this diff: only its answer is shown, so a slower answer to an older/// read (before the whitespace or whole-file setting changed…) can't replace it.request: u64,+ /// How far down it was scrolled last frame, to jump to the change before or after.+ scroll_y: f32,}/// Numbers the diff reads of every tab, so no two diffs ever wait for the same number.@@ -175,6 +192,7 @@ impl DiffView {anchor: None,text_sel: None,request: 0,+ scroll_y: 0.0,}}@@ -197,6 +215,17 @@ impl DiffView {}}+/// A change to one commit of the checked-out branch, made from its menu (or its message in the+/// right pane) without the interactive rebase screen.+pub(crate) enum QuickEdit {+ Reword(String),+ Drop,+ /// Swapped with the commit after it.+ MoveUp,+ /// Swapped with the commit before it.+ MoveDown,+}+/// A commit's message being edited in the right pane (double-click on it).pub(crate) struct Reword {pub hash: String,@@ -284,7 +313,15 @@ pub(crate) enum Action {},Checkout(String),/// Checks out a local branch behind its upstream, then fast-forwards it.- CheckoutPull(String),+ /// Hides, shows or solos a branch in the graph.+ BranchFilter(branch_filter::Change),+ /// Moves local `branch` to `target` (further on): checks it out if needed and+ /// fast-forwards it, the uncommitted changes stashed around; when they have diverged, the+ /// toolbar offers what can be done instead.+ MoveBranch {+ branch: String,+ target: String,+ },CheckoutRemote(String),Dialog(Dialog),Commit,@@ -318,6 +355,8 @@ pub(crate) enum Action {/// Open a path (relative to the repository) with the system's default app.OpenPath(PathBuf),OpenInEditor(PathBuf),+ /// A file in the editor, at a line (1-based).+ OpenInEditorAt(PathBuf, u32),SetIdentity(String, String),/// How diffs show: side by side, without whitespace changes, the whole file.SetDiffOptions {@@ -340,6 +379,10 @@ pub(crate) enum Action {hash: String,message: String,},+ /// Drops a commit, or swaps it with its neighbour, by a rebase from below it.+ QuickEdit(String, QuickEdit),+ /// Shows a commit with its message open for editing in the right pane.+ EditMessage(String),InteractiveRebase {onto: String,label: String,@@ -442,6 +485,12 @@ pub struct RepoTab {branch_filter: String,/// Jump to the changes row on the next rebuild (after an operation left conflicts).focus_wip: bool,+ /// A question in place of the toolbar (see [`Prompt`]).+ prompt: Option<Prompt>,+ /// A commit whose message opens for editing once its details are shown.+ edit_message: Option<String>,+ /// Branches hidden from the graph or soloed in it.+ pub(crate) graph_filter: BranchFilter,last_fetch: Instant,terminals: Vec<Terminal>,@@ -465,7 +514,8 @@ pub struct RepoTab {}impl RepoTab {- pub fn new(path: PathBuf, ctx: &egui::Context) -> Self {+ /// A tab whose graph starts with `filter`'s branches hidden or soloed.+ pub fn with_filter(path: PathBuf, filter: BranchFilter, ctx: &egui::Context) -> Self {let name = path.file_name().map(|n| n.to_string_lossy().into_owned())@@ -527,6 +577,9 @@ impl RepoTab {status: None,branch_filter: String::new(),focus_wip: false,+ prompt: None,+ edit_message: None,+ graph_filter: BranchFilter::default(),last_fetch: Instant::now(),terminals: Vec::new(),active_terminal: 0,@@ -541,6 +594,7 @@ impl RepoTab {finished: None,};tab.watch(ctx);+ tab.graph_filter = filter;tab.reload(ctx);tab}@@ -563,10 +617,11 @@ impl RepoTab {let path = self.path.clone();// Keep the pages already loaded.let count = self.history.len().clamp(git::LOG_PAGE, MAX_HISTORY);+ let revs = self.graph_filter.revs();spawn(&self.tx, ctx, move || {Msg::Loaded((|| {let refs = git::refs(&path)?;- let history = git::log(&path, 0, count)?;+ let history = git::log(&path, &revs, 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();@@ -599,8 +654,9 @@ impl RepoTab {self.loading_more = true;let path = self.path.clone();let skip = self.history.len();+ let revs = self.graph_filter.revs();spawn(&self.tx, ctx, move || {- Msg::More(git::log(&path, skip, git::LOG_PAGE))+ Msg::More(git::log(&path, &revs, skip, git::LOG_PAGE))});}@@ -905,6 +961,11 @@ impl RepoTab {});}+ /// The theme changed: the open diff is coloured again.+ pub(crate) fn recolor(&mut self, ctx: &egui::Context) {+ self.refresh_diff(ctx);+ }+/// Starts comparing two points of history (replacing the comparison shown).fn compare(&mut self, compare: Compare, ctx: &egui::Context) {if matches!(@@ -1012,9 +1073,32 @@ impl RepoTab {kind: OpKind,ctx: &egui::Context,) {- self.run_ops_ex(label, ops, refresh, kind, false, ctx);+ self.run_ops_ex(label, ops, refresh, kind, false, false, ctx);+ }++ /// [`run_undoable`](Self::run_undoable) with the uncommitted changes stashed first and+ /// applied again afterwards, whether the operation worked or not.+ fn run_undoable_autostash(+ &mut self,+ label: &str,+ ops: Vec<Vec<String>>,+ undo: Undo,+ ctx: &egui::Context,+ ) {+ let before = self.refs.head.clone();+ let autostash = !self.work.is_clean();+ self.run_ops_ex(+ label,+ ops,+ Refresh::All,+ OpKind::Normal(undo, before),+ false,+ autostash,+ ctx,+ );}+ #[allow(clippy::too_many_arguments)]fn run_ops_ex(&mut self,label: &str,@@ -1022,11 +1106,13 @@ impl RepoTab {refresh: Refresh,kind: OpKind,quiet: bool,+ autostash: bool,ctx: &egui::Context,) {if self.busy_op.is_some() {return;}+ self.prompt = None;self.busy_op = Some(label.to_owned());self.op_started = Some(Instant::now());if !quiet {@@ -1038,18 +1124,41 @@ impl RepoTab {refresh,kind: kind.clone(),quiet,+ autostash,});let path = self.path.clone();let label = label.to_owned();let creds = self.credentials.clone();spawn(&self.tx, ctx, move || {let mut result = Ok(String::new());+ let mut stashed = false;+ if autostash {+ match git::run(Some(&path), &["stash", "push", "-m", AUTOSTASH]) {+ Ok(out) => stashed = !out.contains("No local changes"),+ Err(e) => result = Err(format!("could not stash your changes: {e}")),+ }+ }for op in &ops {- let args: Vec<&str> = op.iter().map(String::as_str).collect();- result = git::run_with(Some(&path), &args, creds.as_ref());if result.is_err() {break;}+ let args: Vec<&str> = op.iter().map(String::as_str).collect();+ result = if quiet {+ git::run_quiet_with(Some(&path), &args, creds.as_ref())+ } else {+ git::run_with(Some(&path), &args, creds.as_ref())+ };+ }+ // The changes come back however it went; staged ones staged again when possible.+ if stashed {+ let pop = git::run(Some(&path), &["stash", "pop", "--index"])+ .or_else(|_| git::run(Some(&path), &["stash", "pop"]));+ if let Err(e) = pop {+ result = Err(match result {+ Ok(_) => format!("{AUTOSTASH_CONFLICT}: {e}"),+ Err(before) => format!("{before}\n{AUTOSTASH_CONFLICT}: {e}"),+ });+ }}// For HEAD moves, the new HEAD is what redo goes back to.let kind = match kind {@@ -1107,13 +1216,11 @@ impl RepoTab {);}- /// Checkout and `pull --ff-only`; undoing goes back and puts the branch where it was.- fn checkout_pull(&mut self, branch: &str, ctx: &egui::Context) {- let previous = self- .refs- .current- .clone()- .unwrap_or_else(|| self.refs.head.clone());+ /// Moves `branch` to `target`, further on: checks it out if it isn't, and fast-forwards+ /// it with the uncommitted changes stashed around. Branches that have diverged get the+ /// choice of rebasing, merging or resetting in the toolbar instead. Undoing goes back and+ /// puts the branch where it was.+ fn move_branch(&mut self, branch: &str, target: &str, ctx: &egui::Context) {let Some(was) = self.refs.local@@ -1123,22 +1230,134 @@ impl RepoTab {else {return self.checkout(branch, ctx);};- let run = ops(&[&["checkout", branch], &["pull", "--ff-only"]]);- let undo = if previous.is_empty() {- Undo::None+ let current = self.refs.current.as_deref() == Some(branch);+ let (only_here, only_there) = self.divergence(branch, target);+ if only_here > 0 {+ self.prompt = Some(self.diverged_prompt(branch, target, only_here, only_there));+ return;+ }+ let mut run = Vec::new();+ if !current {+ run.push(vec!["checkout".to_owned(), branch.to_owned()]);+ }+ run.push(vec![+ "merge".to_owned(),+ "--ff-only".to_owned(),+ target.to_owned(),+ ]);+ let (label, undo) = if current {+ (+ format!("Fast-forward {branch} to {target}"),+ Undo::HeadMove { mode: "--keep" },+ )} else {- Undo::Custom {- undo: ops(&[&["checkout", &previous], &["branch", "-f", branch, &was]]),- redo: run.clone(),+ (+ format!("Checkout {branch} at {target}"),+ self.back_to_previous(branch, &was, run.clone()),+ )+ };+ self.run_undoable_autostash(&label, run, undo, ctx);+ }++ /// Undoing a move of `branch` that checked it out: back to the branch before, and+ /// `branch` back at `was`.+ fn back_to_previous(&self, branch: &str, was: &str, redo: Vec<Vec<String>>) -> Undo {+ let previous = self+ .refs+ .current+ .clone()+ .unwrap_or_else(|| self.refs.head.clone());+ if previous.is_empty() {+ return Undo::None;+ }+ Undo::Custom {+ undo: ops(&[&["checkout", &previous], &["branch", "-f", branch, was]]),+ redo,+ }+ }++ /// Commits only on `a`, and only on `b`.+ fn divergence(&self, a: &str, b: &str) -> (u32, u32) {+ let range = format!("{a}...{b}");+ git::run(+ Some(&self.path),+ &["rev-list", "--left-right", "--count", &range],+ )+ .ok()+ .and_then(|out| {+ let (l, r) = out.trim().split_once(char::is_whitespace)?;+ Some((l.trim().parse().ok()?, r.trim().parse().ok()?))+ })+ .unwrap_or((0, 0))+ }++ /// What can be done when `branch` can't simply move to `target`: rebase it, merge, or+ /// reset it there (git's own `--autostash` keeps the changes through each).+ fn diverged_prompt(&self, branch: &str, target: &str, here: u32, there: u32) -> Prompt {+ let current = self.refs.current.as_deref() == Some(branch);+ let was = self+ .refs+ .local+ .iter()+ .find(|b| b.name == branch)+ .map(|b| b.target.clone())+ .unwrap_or_default();+ let commits = |n: u32| {+ if n == 1 {+ "1 commit".to_owned()+ } else {+ format!("{n} commits")}};- self.run_undoable(- &format!("Checkout and pull {branch}"),- run,- Refresh::All,- undo,- ctx,- );+ let option = |label: String, tip: String, step: &[&str], danger: bool| {+ let mut run = Vec::new();+ if !current {+ run.push(vec!["checkout".to_owned(), branch.to_owned()]);+ }+ run.push(step.iter().map(|s| (*s).to_owned()).collect());+ let undo = if current {+ Undo::HeadMove { mode: "--keep" }+ } else {+ self.back_to_previous(branch, &was, run.clone())+ };+ let action = Action::UndoableOps {+ label: label.clone(),+ ops: run,+ refresh: Refresh::All,+ undo,+ };+ (label, tip, action, danger)+ };+ Prompt {+ text: format!(+ "{branch} and {target} have diverged: {} only on {branch}, {} only on {target}.",+ commits(here),+ commits(there)+ ),+ options: vec![+ option(+ format!("Rebase {branch} onto {target}"),+ format!("Replays {branch}'s {} on top of {target}", commits(here)),+ &["rebase", "--autostash", target],+ false,+ ),+ option(+ format!("Merge {target} into {branch}"),+ "A merge commit joins the two".to_owned(),+ &["merge", "--autostash", "--no-edit", target],+ false,+ ),+ option(+ format!("Reset {branch} to {target}"),+ format!(+ "Moves {branch} to {target}, leaving out its {}; Undo brings them back",+ commits(here)+ ),+ &["reset", "--keep", target],+ true,+ ),+ ],+ }}/// The latest commit is amended (its message only, whatever is staged); an older one is@@ -1170,14 +1389,34 @@ impl RepoTab {);return;}+ self.quick_edit(hash, QuickEdit::Reword(message), ctx);+ }++ /// Lists the commits a quick edit of `hash` replays (from its parent; from its+ /// grandparent to move it down), then runs the rebase (see `Msg::QuickEditCommits`).+ fn quick_edit(&mut self, hash: String, edit: QuickEdit, ctx: &egui::Context) {+ if self.busy_op.is_some() {+ return;+ }+ // The latest commit dropped: a reset, which keeps the uncommitted changes.+ if matches!(edit, QuickEdit::Drop) && hash == self.refs.head {+ self.run_undoable(+ &format!("Drop {}", short(&hash)),+ ops(&[&["reset", "--keep", &format!("{hash}^")]]),+ Refresh::All,+ Undo::HeadMove { mode: "--keep" },+ ctx,+ );+ return;+ }+ let onto = match edit {+ QuickEdit::MoveDown => format!("{hash}~2"),+ _ => format!("{hash}^"),+ };let path = self.path.clone();spawn(&self.tx, ctx, move || {- let result = git::rebase_commits(&path, &format!("{hash}^"));- Msg::RewordCommits {- hash,- message,- result,- }+ let result = git::rebase_commits(&path, &onto);+ Msg::QuickEditCommits { hash, edit, result }});}@@ -1481,6 +1720,7 @@ impl RepoTab {Refresh::All,OpKind::Normal(Undo::None, String::new()),true,+ false,ctx,);}@@ -1596,22 +1836,46 @@ impl RepoTab {}Err(e) => self.status = Some((format!("Interactive rebase: {e}"), true)),},- Msg::RewordCommits {- hash,- message,- result,- } => {+ Msg::QuickEditCommits { hash, edit, result } => {+ let label = match &edit {+ QuickEdit::Reword(_) => format!("Edit the message of {}", short(&hash)),+ QuickEdit::Drop => format!("Drop {}", short(&hash)),+ QuickEdit::MoveUp => format!("Move {} up", short(&hash)),+ QuickEdit::MoveDown => format!("Move {} down", short(&hash)),+ };let result = result.and_then(|commits| {- let onto = format!("{hash}^");+ let onto = match edit {+ QuickEdit::MoveDown => format!("{hash}~2"),+ _ => format!("{hash}^"),+ };let mut editor =rebase::RebaseEditor::new(onto, short(&hash).to_owned(), commits);- let entry = editor+ let i = editor.entries- .iter_mut()- .find(|e| e.commit.hash == hash)+ .iter()+ .position(|e| e.commit.hash == hash).ok_or("only commits of the checked-out branch can be edited")?;- entry.step = rebase::Step::Reword;- entry.message = message;+ match edit {+ QuickEdit::Reword(message) => {+ if let Some(entry) = editor.entries.get_mut(i) {+ entry.step = rebase::Step::Reword;+ entry.message = message;+ }+ }+ QuickEdit::Drop => {+ if let Some(entry) = editor.entries.get_mut(i) {+ entry.step = rebase::Step::Drop;+ }+ }+ // Oldest first: up is towards the end.+ QuickEdit::MoveUp if i + 1 < editor.entries.len() => {+ editor.entries.swap(i, i + 1);+ }+ QuickEdit::MoveDown if i > 0 => editor.entries.swap(i - 1, i),+ QuickEdit::MoveUp | QuickEdit::MoveDown => {+ return Err("there is no commit there to swap it with".to_owned());+ }+ }if let Some(problem) = editor.problem() {return Err(problem);}@@ -1619,13 +1883,13 @@ impl RepoTab {});match result {Ok(command) => self.run_undoable(- &format!("Edit the message of {}", short(&hash)),+ &label,vec![command],Refresh::All,Undo::HeadMove { mode: "--keep" },ctx,),- Err(e) => self.status = Some((format!("Edit message: {e}"), true)),+ Err(e) => self.status = Some((format!("{label}: {e}"), true)),}}Msg::FileHistory(path, result) => {@@ -1718,6 +1982,34 @@ impl RepoTab {.unwrap_or_default();self.dialog = Some(Dialog::credentials(&url, refused));}+ Err(e) if e.contains(AUTOSTASH_CONFLICT) => {+ self.focus_wip = true;+ self.status = Some((format!("{label}: done"), false));+ self.prompt = Some(Prompt {+ text: "Your changes didn't apply cleanly on top: fix the files \+ marked as conflicted in Changes. They are kept in the stash \+ as well."+ .to_owned(),+ options: Vec::new(),+ });+ self.record_undo(&label, kind);+ }+ Err(e)+ if label == "Pull"+ && (e.contains("Not possible to fast-forward")+ || e.contains("Diverging branches")) =>+ {+ let current = self.refs.current.clone().unwrap_or_default();+ let upstream = self+ .refs+ .local+ .iter()+ .find(|b| b.name == current)+ .map(|b| b.upstream.clone())+ .unwrap_or_default();+ let (here, there) = self.divergence(¤t, &upstream);+ self.prompt = Some(self.diverged_prompt(¤t, &upstream, here, there));+ }Err(e) => {self.focus_wip = e.contains("CONFLICT") || e.contains("could not apply");self.status = Some((format!("{label} failed: {e}"), true));@@ -1801,7 +2093,11 @@ impl RepoTab {undo,} => self.run_undoable(&label, ops, refresh, undo, ctx),Action::Checkout(name) => self.checkout(&name, ctx),- Action::CheckoutPull(name) => self.checkout_pull(&name, ctx),+ Action::MoveBranch { branch, target } => self.move_branch(&branch, &target, ctx),+ Action::BranchFilter(change) => {+ self.graph_filter.apply(change);+ self.reload(ctx);+ }Action::CheckoutRemote(name) => self.checkout_remote(&name, ctx),Action::Dialog(dialog) => self.dialog = Some(dialog),Action::Commit => self.commit(ctx),@@ -1817,7 +2113,7 @@ impl RepoTab {}Action::Pull => self.run_undoable("Pull",- ops(&[&["pull", "--ff-only"]]),+ ops(&[&["pull", "--ff-only", "--autostash"]]),Refresh::All,Undo::HeadMove { mode: "--keep" },ctx,@@ -1896,7 +2192,13 @@ impl RepoTab {}Action::OpenInEditor(rel) => {let editor = Settings::get(ctx).editor;- if let Err(e) = open_in_editor(&editor, &self.path.join(rel)) {+ if let Err(e) = open_in_editor(&editor, &self.path.join(rel), None) {+ self.status = Some((e, true));+ }+ }+ Action::OpenInEditorAt(rel, line) => {+ let editor = Settings::get(ctx).editor;+ if let Err(e) = open_in_editor(&editor, &self.path.join(rel), Some(line)) {self.status = Some((e, true));}}@@ -1941,6 +2243,11 @@ impl RepoTab {});}Action::Reword { hash, message } => self.reword_commit(hash, message, ctx),+ Action::QuickEdit(hash, edit) => self.quick_edit(hash, edit, ctx),+ Action::EditMessage(hash) => {+ self.goto(&hash, ctx);+ self.edit_message = Some(hash);+ }Action::RunRebase => {let Some(editor) = &self.rebase else { return };if editor.problem().is_some() || self.busy_op.is_some() {@@ -1965,7 +2272,15 @@ impl RepoTab {Action::SignIn(creds) => {self.credentials = Some(creds);if let Some(op) = self.last_op.take() {- self.run_ops_ex(&op.label, op.ops, op.refresh, op.kind, op.quiet, ctx);+ self.run_ops_ex(+ &op.label,+ op.ops,+ op.refresh,+ op.kind,+ op.quiet,+ op.autostash,+ ctx,+ );}}Action::Ignore { pattern, path } => match git::add_to_gitignore(&self.path, &pattern) {@@ -2206,6 +2521,9 @@ impl RepoTab {}fn toolbar(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {+ if self.prompt.is_some() {+ return self.prompt_bar(ui, acts);+ }let t = Tokens::get(ui.ctx());ui.horizontal(|ui| {ui.spacing_mut().item_spacing.x = 2.0;@@ -2345,6 +2663,25 @@ impl RepoTab {}}+ // Branches left out of the graph: how many, and a way back to all of them.+ if self.graph_filter.is_active() {+ ui.add_space(10.0);+ let f = &self.graph_filter;+ let text = if f.solo.is_empty() {+ let n = f.hidden.len();+ format!("{n} branch{} hidden", if n == 1 { "" } else { "es" })+ } else {+ let n = f.solo.len();+ format!("{n} branch{} soloed", if n == 1 { "" } else { "es" })+ };+ if icons::tool_button(ui, "eye-off", &text, true)+ .on_hover_text("Show every branch in the graph again")+ .clicked()+ {+ acts.push(Action::BranchFilter(branch_filter::Change::Clear));+ }+ }+if let Some(state) = self.work.in_progress {ui.add_space(10.0);widgets::chip(ui, &format!("{} in progress", state.label()), t.warning);@@ -2570,9 +2907,9 @@ pub(crate) fn reveal_label() -> &'static str {}}-/// 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> {+/// Runs the user's editor command with `path`, at `line` when the editor is one that can be+/// told (through `cmd` on Windows, where editors are usually `.cmd` scripts).+pub(crate) fn open_in_editor(editor: &str, path: &Path, line: Option<u32>) -> Result<(), String> {let editor = if editor.trim().is_empty() {"code"} else {@@ -2580,11 +2917,13 @@ pub(crate) fn open_in_editor(editor: &str, path: &Path) -> Result<(), String> {};let mut cmd = if cfg!(windows) {let mut c = std::process::Command::new("cmd");- c.arg("/C").arg(editor).arg(path);+ c.arg("/C")+ .arg(editor)+ .args(editor_args(editor, path, line));c} else {let mut c = std::process::Command::new(editor);- c.arg(path);+ c.args(editor_args(editor, path, line));crate::shell_path::apply(&mut c);c};@@ -2598,6 +2937,39 @@ pub(crate) fn open_in_editor(editor: &str, path: &Path) -> Result<(), String> {.map_err(|e| format!("Could not run {editor}: {e}"))}+/// The arguments that open `path` at `line` in `editor`, by the editor's family; just the path+/// for an editor that isn't known.+fn editor_args(editor: &str, path: &Path, line: Option<u32>) -> Vec<std::ffi::OsString> {+ let Some(line) = line else {+ return vec![path.into()];+ };+ let program = editor.split_whitespace().next().unwrap_or(editor);+ let name = Path::new(program)+ .file_stem()+ .map(|s| s.to_string_lossy().to_lowercase())+ .unwrap_or_default();+ let at = |sep: &str| {+ let mut s = path.as_os_str().to_owned();+ s.push(format!("{sep}{line}"));+ s+ };+ match name.as_str() {+ "code" | "code-insiders" | "codium" | "vscodium" | "cursor" | "windsurf" => {+ vec!["-g".into(), at(":")]+ }+ "subl" | "sublime_text" | "zed" | "zeditor" | "atom" | "pulsar" | "lapce" => vec![at(":")],+ "idea" | "idea64" | "pycharm" | "pycharm64" | "webstorm" | "webstorm64" | "phpstorm"+ | "phpstorm64" | "rider" | "rider64" | "clion" | "clion64" | "goland" | "goland64"+ | "rubymine" | "rubymine64" | "rustrover" | "rustrover64" | "studio" | "studio64" => {+ vec!["--line".into(), line.to_string().into(), path.into()]+ }+ "vim" | "nvim" | "gvim" | "mvim" | "emacs" | "emacsclient" | "nano" | "micro" | "kak" => {+ vec![format!("+{line}").into(), path.into()]+ }+ _ => vec![path.into()],+ }+}+fn short_duration(d: Duration) -> String {let s = d.as_secs();match s {@@ -2607,6 +2979,59 @@ fn short_duration(d: Duration) -> String {}}+impl RepoTab {+ /// A question in place of the toolbar: what happened, the choices, and a close button+ /// (Esc) that puts the toolbar back.+ fn prompt_bar(&mut self, ui: &mut Ui, acts: &mut Vec<Action>) {+ let t = Tokens::get(ui.ctx());+ let mut chosen = None;+ let mut close = ui.input(|i| i.key_pressed(egui::Key::Escape)) && !self.keys_blocked;+ if let Some(prompt) = &self.prompt {+ ui.horizontal(|ui| {+ ui.set_min_height(ui.spacing().interact_size.y + 4.0);+ ui.add_space(4.0);+ icons::inline(ui, "circle-alert", 16.0, t.warning);+ ui.label(egui::RichText::new(&prompt.text).color(t.text));+ ui.add_space(6.0);+ let idle = self.busy_op.is_none();+ for (i, (label, tip, _, danger)) in prompt.options.iter().enumerate() {+ let text = if *danger {+ egui::RichText::new(label).color(t.danger)+ } else if i == 0 {+ egui::RichText::new(label).color(t.accent_text)+ } else {+ egui::RichText::new(label)+ };+ let mut button = egui::Button::new(text);+ if i == 0 && !*danger {+ button = button.fill(t.accent);+ }+ if ui+ .add_enabled(idle, button)+ .on_hover_text(tip.as_str())+ .clicked()+ {+ chosen = Some(i);+ }+ }+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {+ if icons::small_button(ui, "x", "Close (Esc)").clicked() {+ close = true;+ }+ });+ });+ }+ if let Some(i) = chosen+ && let Some(prompt) = self.prompt.take()+ && let Some((_, _, action, _)) = prompt.options.into_iter().nth(i)+ {+ acts.push(action);+ } else if close {+ self.prompt = None;+ }+ }+}+/// 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 {@@ -2652,6 +3077,24 @@ fn spawn(tx: &Sender<Msg>, ctx: &egui::Context, job: impl FnOnce() -> Msg + Send#[cfg(test)]mod tests {+ #[test]+ fn editors_open_at_a_line_their_own_way() {+ use std::ffi::OsString;+ let p = std::path::Path::new("src/a.rs");+ let args = |e: &str, l| super::editor_args(e, p, l);+ let os = |v: &[&str]| v.iter().map(OsString::from).collect::<Vec<_>>();+ assert_eq!(args("code", Some(12)), os(&["-g", "src/a.rs:12"]));+ assert_eq!(+ args("C:/Tools/Cursor.exe", Some(3)),+ os(&["-g", "src/a.rs:3"])+ );+ assert_eq!(args("subl", Some(4)), os(&["src/a.rs:4"]));+ assert_eq!(args("idea64", Some(5)), os(&["--line", "5", "src/a.rs"]));+ assert_eq!(args("nvim", Some(6)), os(&["+6", "src/a.rs"]));+ assert_eq!(args("notepad++", Some(7)), os(&["src/a.rs"]));+ assert_eq!(args("code", None), os(&["src/a.rs"]));+ }+use super::{DiffKey, DiffView, headline};#[test]diff --git a/src/repo/sidebar.rs b/src/repo/sidebar.rsindex 2392466..a838c14 100644--- a/src/repo/sidebar.rs+++ b/src/repo/sidebar.rs@@ -3,6 +3,7 @@use egui::{Align2, Rect, Response, Sense, Ui, pos2, vec2};+use super::branch_filter::{Change, local_ref, remote_ref};use super::widgets;use super::{Action, Dialog, Refresh, RepoTab, Undo, compare_action, fast_forward_action, merge_action, ops,@@ -44,12 +45,13 @@ impl RepoTab {ui.spacing_mut().item_spacing.y = 0.0;let local: Vec<&Branch> = self.refs.local.iter().filter(matches).collect();+ let count = self.visible_count(local.iter().map(|b| local_ref(&b.name)));let (open, add) = widgets::section_with_button(ui,"local","laptop","LOCAL",- local.len(),+ count,true,Some(("plus", "New branch at HEAD…")),);@@ -159,7 +161,10 @@ impl RepoTab {.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(+ let full = local_ref(&b.name);+ // The checked-out branch is always drawn.+ let eye = (!b.is_head).then(|| self.graph_filter.shows(&full));+ let (r, eye_clicked) = branch_row(ui,&b.name,b.is_head,@@ -168,7 +173,11 @@ impl RepoTab {b.upstream_gone(),elsewhere.is_some(),has_pr,+ eye,);+ if eye_clicked {+ acts.push(Action::BranchFilter(Change::Toggle(full)));+ }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),@@ -195,6 +204,51 @@ impl RepoTab {.show(|ui| self.branch_menu_items(ui, acts, b, idle));}+ /// Hide, show or solo a branch in the graph (`full`: its ref name), at the end of its menus.+ pub(super) fn filter_items(&self, ui: &mut Ui, acts: &mut Vec<Action>, full: &str, head: bool) {+ ui.separator();+ let f = &self.graph_filter;+ if f.shows(full) || head {+ if ui+ .add_enabled(!head, egui::Button::new("Hide in the graph"))+ .on_disabled_hover_text("The checked-out branch is always shown")+ .clicked()+ {+ acts.push(Action::BranchFilter(Change::Toggle(full.to_owned())));+ }+ } else if ui.button("Show in the graph").clicked() {+ acts.push(Action::BranchFilter(Change::Toggle(full.to_owned())));+ }+ if f.soloed(full) {+ if ui.button("Stop soloing").clicked() {+ acts.push(Action::BranchFilter(Change::Unsolo(full.to_owned())));+ }+ } else if ui+ .button("Solo")+ .on_hover_text("Show only this branch in the graph (and any others soloed)")+ .clicked()+ {+ acts.push(Action::BranchFilter(Change::Solo(full.to_owned())));+ }+ if f.is_active() && ui.button("Show all branches").clicked() {+ acts.push(Action::BranchFilter(Change::Clear));+ }+ }++ /// `shown/total` while the graph hides or solos branches, else the total.+ fn visible_count(&self, refs: impl Iterator<Item = String>) -> String {+ let refs: Vec<String> = refs.collect();+ if !self.graph_filter.is_active() {+ return refs.len().to_string();+ }+ let current = self.refs.current.as_deref().map(local_ref);+ let shown = refs+ .iter()+ .filter(|r| self.graph_filter.shows(r) || current.as_ref() == Some(*r))+ .count();+ format!("{shown}/{}", refs.len())+ }+/// The menu of a local branch: in the sidebar and in the graph's commit menu.pub(super) fn branch_menu_items(&self,@@ -354,6 +408,7 @@ impl RepoTab {if ui.button("Copy name").clicked() {ui.ctx().copy_text(b.name.clone());}+ self.filter_items(ui, acts, &local_ref(&b.name), b.is_head);ui.separator();if ui.add_enabled(!b.is_head && idle, egui::Button::new("Delete…"))@@ -481,7 +536,7 @@ impl RepoTab {p.text(pos2(rect.right() - 10.0, y),Align2::RIGHT_CENTER,- branches.len().to_string(),+ self.visible_count(branches.iter().map(|b| remote_ref(&b.name))),theme::medium(11.0),t.text_faint,);@@ -523,8 +578,13 @@ impl RepoTab {.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));+ let full = remote_ref(&b.name);+ let (r, eye_clicked) =+ branch_row_indented(ui, short, has_pr, self.graph_filter.shows(&full));+ if eye_clicked {+ acts.push(Action::BranchFilter(Change::Toggle(full.clone())));+ }+ let r = r.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() {@@ -578,6 +638,7 @@ impl RepoTab {if ui.button("Copy name").clicked() {ui.ctx().copy_text(b.name.clone());}+ self.filter_items(ui, acts, &full, false);ui.separator();if ui.add_enabled(idle, egui::Button::new("Delete from remote…"))@@ -979,7 +1040,8 @@ fn branch_row(gone: bool,in_worktree: bool,has_pr: bool,-) -> Response {+ eye: Option<bool>,+) -> (Response, bool) {let t = Tokens::get(ui.ctx());let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());let painter = ui.painter_at(rect);@@ -990,6 +1052,11 @@ fn branch_row(painter.rect_filled(rect, 0.0, t.hover);}let y = rect.center().y;+ let (mut right, eye_clicked) = match eye {+ Some(shown) => eye_button(ui, &resp, rect, shown),+ None => (rect.right() - 8.0, false),+ };+ let shown = eye.unwrap_or(true);let icon_rect = Rect::from_center_size(pos2(rect.left() + 34.0, y), vec2(16.0, 16.0));if is_head {icons::paint(ui, icon_rect, "check", 14.0, t.accent);@@ -997,7 +1064,6 @@ fn branch_row(icons::paint(ui, icon_rect, "git-branch", 13.0, t.text_faint);}- 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));@@ -1048,19 +1114,42 @@ fn branch_row(Align2::LEFT_CENTER,name,font,- t.text,+ if shown { t.text } else { t.text_faint },);- resp+ (resp, eye_clicked)}-/// A remote's branch, one level in under its remote.-fn branch_row_indented(ui: &mut Ui, name: &str, has_pr: bool) -> Response {+/// The eye at a branch row's right end: on hover, or always while the branch is hidden.+/// Returns where the row's other things end, and whether it was clicked.+fn eye_button(ui: &mut Ui, row: &Response, rect: Rect, shown: bool) -> (f32, bool) {+ let t = Tokens::get(ui.ctx());+ let r = Rect::from_center_size(pos2(rect.right() - 16.0, rect.center().y), vec2(20.0, 20.0));+ let b = ui+ .interact(r, row.id.with("eye"), Sense::click())+ .on_hover_text(if shown {+ "Hide in the graph"+ } else {+ "Show in the graph"+ });+ if row.hovered() || b.hovered() || !shown {+ if b.hovered() {+ ui.painter().rect_filled(r, t.radius_sm, t.pressed);+ }+ let color = if b.hovered() { t.text } else { t.text_faint };+ icons::paint(ui, r, if shown { "eye" } else { "eye-off" }, 13.0, color);+ }+ (r.left() - 4.0, b.clicked())+}++/// A remote's branch, one level in under its remote, with its eye (see [`eye_button`]).+fn branch_row_indented(ui: &mut Ui, name: &str, has_pr: bool, shown: bool) -> (Response, bool) {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;+ let (mut right, eye_clicked) = eye_button(ui, &resp, rect, shown);icons::paint(ui,Rect::from_center_size(pos2(rect.left() + 52.0, y), vec2(16.0, 16.0)),@@ -1068,7 +1157,6 @@ fn branch_row_indented(ui: &mut Ui, name: &str, has_pr: bool) -> Response {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);@@ -1079,9 +1167,9 @@ fn branch_row_indented(ui: &mut Ui, name: &str, has_pr: bool) -> Response {Align2::LEFT_CENTER,name,egui::FontId::proportional(12.5),- t.text,+ if shown { t.text } else { t.text_faint },);- resp+ (resp, eye_clicked)}/// An icon, a name and optional faint text after it.diff --git a/src/repo/widgets.rs b/src/repo/widgets.rsindex 44336fe..3320358 100644--- a/src/repo/widgets.rs+++ b/src/repo/widgets.rs@@ -77,7 +77,7 @@ pub fn section(id: &str,icon: &str,title: &str,- count: usize,+ count: impl std::fmt::Display,default_open: bool,) -> bool {section_with_button(ui, id, icon, title, count, default_open, None).0@@ -90,7 +90,7 @@ pub fn section_with_button(id: &str,icon: &str,title: &str,- count: usize,+ count: impl std::fmt::Display,default_open: bool,button: Option<(&str, &str)>,) -> (bool, bool) {@@ -133,7 +133,7 @@ pub fn section_with_button(theme::semibold(11.5),t.text_dim,);- painter.text(+ let count = painter.text(pos2(rect.right() - 10.0, y),Align2::RIGHT_CENTER,count.to_string(),@@ -142,7 +142,9 @@ pub fn section_with_button();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));+ // Left of the count, however long it reads (`120/870` while branches are hidden).+ let x = (count.left() - 18.0).min(rect.right() - 36.0);+ let r = Rect::from_center_size(pos2(x, y), vec2(20.0, 20.0));let b = ui.interact(r, id.with("button"), Sense::click()).on_hover_text(tooltip);@@ -188,6 +190,21 @@ pub fn file_row(selected: bool,extra: RowExtra<'_>,) -> FileRowResponse {+ file_row_in(ui, code, path, old_path, None, selected, extra)+}++/// [`file_row`] in a tree of folders, `indent` in: just the file's name, its folder being the+/// rows above.+pub fn file_row_in(+ ui: &mut Ui,+ code: char,+ path: &str,+ old_path: Option<&str>,+ indent: Option<f32>,+ selected: bool,+ extra: RowExtra<'_>,+) -> FileRowResponse {+ let shift = indent.unwrap_or(0.0);let t = Tokens::get(ui.ctx());let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), Sense::click());let hovered = ui.rect_contains_pointer(rect);@@ -201,7 +218,7 @@ pub fn file_row(// Status letter in a small rounded square.let color = status_color(&t, code);- let badge = Rect::from_center_size(pos2(rect.left() + 18.0, y), vec2(16.0, 16.0));+ let badge = Rect::from_center_size(pos2(rect.left() + 18.0 + shift, y), vec2(16.0, 16.0));painter.rect_filled(badge, CornerRadius::same(3), color.gamma_multiply(0.22));let letter = if code == '?' { 'A' } else { code };painter.text(@@ -280,7 +297,7 @@ pub fn file_row(None => ("", path),};let text_clip = Rect::from_min_max(- pos2(rect.left() + 32.0, rect.top()),+ pos2(rect.left() + 32.0 + shift, rect.top()),pos2(right, rect.bottom()),);let tp = painter.with_clip_rect(text_clip);@@ -297,7 +314,9 @@ pub fn file_row(faint.push_str(old);faint.push_str(" ");}- faint.push_str(dir);+ if indent.is_none() {+ faint.push_str(dir);+ }if !faint.is_empty() {tp.text(pos2(name_rect.right() + 8.0, y),@@ -565,3 +584,73 @@ fn ignore_patterns(path: &str) -> Vec<(String, String, String)> {}out}++/// How a slider's value reads in the box beside it.+#[derive(Clone, Copy)]+pub enum SliderUnit {+ /// `1.25` reads `125 %`.+ Percent,+ /// The number and a unit after it, like ` px`.+ Suffix(&'static str),+}++/// A slider: a rail filled up to a round knob in the theme's accent, and the value beside it+/// to drag or type. Returns the slider's and the box's response together.+pub fn slider(+ ui: &mut Ui,+ value: &mut f32,+ range: std::ops::RangeInclusive<f32>,+ step: f32,+ unit: SliderUnit,+) -> Response {+ const KNOB: f32 = 7.0;+ let t = Tokens::get(ui.ctx());+ let (min, max) = (*range.start(), *range.end());+ ui.horizontal(|ui| {+ let size = vec2(ui.spacing().slider_width, ui.spacing().interact_size.y);+ let (rect, mut resp) = ui.allocate_exact_size(size, Sense::click_and_drag());+ let resp_hover = resp.clone();+ let track = rect.x_range().shrink(KNOB);+ if let Some(p) = resp.interact_pointer_pos() {+ let f = ((p.x - track.min) / track.span()).clamp(0.0, 1.0);+ let mut v = min + f * (max - min);+ if step > 0.0 {+ v = min + ((v - min) / step).round() * step;+ }+ let v = v.clamp(min, max);+ if (v - *value).abs() > f32::EPSILON {+ *value = v;+ resp.mark_changed();+ }+ }+ let f = if max > min {+ ((*value - min) / (max - min)).clamp(0.0, 1.0)+ } else {+ 0.0+ };+ let y = rect.center().y;+ let x = track.min + f * track.span();+ let p = ui.painter();+ let rail = Rect::from_min_max(pos2(rect.left(), y - 2.0), pos2(rect.right(), y + 2.0));+ p.rect_filled(rail, 2.0, t.field_border);+ p.rect_filled(rail.with_max_x(x), 2.0, t.accent.gamma_multiply(0.6));+ let lifted = resp_hover.hovered() || resp_hover.dragged();+ p.circle_filled(pos2(x, y), if lifted { KNOB + 1.0 } else { KNOB }, t.accent);+ let resp = resp.on_hover_cursor(egui::CursorIcon::Grab);++ let mut drag = egui::DragValue::new(value)+ .range(min..=max)+ .speed(step.max(0.01));+ drag = match unit {+ SliderUnit::Percent => drag+ .custom_formatter(|v, _| format!("{:.0} %", v * 100.0))+ .custom_parser(|s| {+ let n: f64 = s.trim().trim_end_matches('%').trim().parse().ok()?;+ Some(n / 100.0)+ }),+ SliderUnit::Suffix(suffix) => drag.suffix(suffix),+ };+ resp | ui.add(drag)+ })+ .inner+}diff --git a/src/settings.rs b/src/settings.rsindex 6e02033..d576d4f 100644--- a/src/settings.rs+++ b/src/settings.rs@@ -3,7 +3,19 @@use egui::{RichText, Ui};use serde::{Deserialize, Serialize};+use crate::code_theme::SyntaxStyle;+use crate::repo::widgets::{SliderUnit, slider};use crate::theme::{self, Tokens};+use crate::vscode;++/// The code each theme is shown with.+const SAMPLE: &str = "/// Opens the server on `port`.+pub fn listen(port: u16) -> Result<Server> {+ let addr = format!(\"0.0.0.0:{port}\");+ let socket = TcpListener::bind(&addr)?;+ log!(\"listening on {}\", addr); // ok+ Ok(Server { socket, open: true })+}";/// A name and email to commit with, applied per repository.#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]@@ -32,6 +44,8 @@ pub struct Settings {pub diff_split: bool,/// Diffs show the whole file, not just the lines around the changes.pub diff_whole_file: bool,+ /// A commit's files in a tree of their folders rather than a list of paths.+ pub files_as_tree: bool,/// Background fetch interval in minutes; 0 turns it off.pub auto_fetch_minutes: u32,/// Load avatars: GitHub / GitLab accounts on repositories hosted there, Gravatar otherwise.@@ -42,8 +56,10 @@ pub struct Settings {pub notifications: bool,/// Ask GitHub every 12 hours whether a newer release exists.pub check_updates: bool,- /// Colour code in diffs and blame with VS Code's current theme, when it has one.- pub vscode_colors: bool,+ /// The theme code is coloured with in diffs and blame.+ pub theme: CodeTheme,+ /// VS Code colour themes imported into the settings.+ pub imported_themes: Vec<vscode::ThemeInfo>,pub profiles: Vec<Profile>,}@@ -59,17 +75,33 @@ impl Default for Settings {show_hash: false,diff_split: false,diff_whole_file: false,+ files_as_tree: false,auto_fetch_minutes: 10,avatars: true,editor: "code".to_owned(),notifications: true,check_updates: true,- vscode_colors: true,+ theme: CodeTheme::default(),+ imported_themes: Vec::new(),profiles: Vec::new(),}}}+/// The code's theme: one of gitcraft's own, or a VS Code colour theme imported, which also+/// colours the rest of the window.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub enum CodeTheme {+ Builtin(SyntaxStyle),+ VsCode(String),+}++impl Default for CodeTheme {+ fn default() -> Self {+ CodeTheme::Builtin(SyntaxStyle::default())+ }+}+fn id() -> egui::Id {egui::Id::new("gitcraft-settings")}@@ -83,7 +115,14 @@ impl Settings {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));- crate::vscode_theme::set_enabled(self.vscode_colors);+ }++ /// The imported VS Code theme chosen, if one is.+ pub fn vscode_theme(&self) -> Option<&vscode::ThemeInfo> {+ match &self.theme {+ CodeTheme::VsCode(name) => self.imported_themes.iter().find(|t| t.name == *name),+ CodeTheme::Builtin(_) => None,+ }}/// The settings form. Returns true when something changed.@@ -103,10 +142,10 @@ impl Settings {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)));+ self.zoom(ui);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"));+ slider(ui, &mut self.refs_width, 180.0..=480.0, 10.0, SliderUnit::Suffix(" px"));ui.end_row();ui.label("Graph columns");ui.horizontal(|ui| {@@ -119,23 +158,6 @@ impl Settings {ui.checkbox(&mut self.avatars, "Load from GitHub, GitLab or Gravatar").on_hover_text("On a GitHub repository, its commit list says which account each author is; on GitLab, the host is asked by email. Other authors: an MD5 hash of the email goes to gravatar.com. Cached on disk.");ui.end_row();- ui.label("Code colours");- ui.horizontal(|ui| {- ui.checkbox(&mut self.vscode_colors, "Use VS Code's colour theme");- if self.vscode_colors {- let note = match crate::vscode_theme::current() {- Some(found) if found.dark == t.dark() => found.name.clone(),- Some(found) => format!(- "{} is {}: gitcraft's colours meanwhile",- found.name,- if found.dark { "dark" } else { "light" }- ),- None => "No VS Code theme found".to_owned(),- };- ui.label(RichText::new(note).color(t.text_faint).small());- }- });- ui.end_row();ui.label("Notifications");ui.checkbox(&mut self.notifications, "When a long operation ends in the background");ui.end_row();@@ -162,6 +184,9 @@ impl Settings {ui.end_row();});+ section(ui, "THEMES");+ self.themes(ui);+section(ui, "GIT");egui::Grid::new("settings-git").num_columns(2)@@ -209,7 +234,13 @@ impl Settings {});ui.end_row();ui.label("Font size");- ui.add(egui::Slider::new(&mut self.terminal_font, 9.0..=20.0).step_by(0.5));+ slider(+ ui,+ &mut self.terminal_font,+ 9.0..=20.0,+ 0.5,+ SliderUnit::Suffix(" pt"),+ );ui.end_row();});@@ -253,3 +284,248 @@ impl Settings {*self != before}}++impl Settings {+ /// The zoom slider and its Apply button: the zoom changes once applied, not while the+ /// slider moves (the slider would move under the pointer as the window rescales).+ fn zoom(&mut self, ui: &mut Ui) {+ let id = ui.id().with("zoom-draft");+ let mut draft = ui.data(|d| d.get_temp::<f32>(id)).unwrap_or(self.ui_scale);+ ui.horizontal(|ui| {+ slider(ui, &mut draft, 0.7..=2.0, 0.05, SliderUnit::Percent);+ let pending = (draft - self.ui_scale).abs() > 0.001;+ if ui+ .add_enabled(pending, egui::Button::new("Apply"))+ .clicked()+ {+ self.ui_scale = draft;+ }+ if pending && ui.add(egui::Button::new("Cancel").frame(false)).clicked() {+ draft = self.ui_scale;+ }+ });+ ui.data_mut(|d| d.insert_temp(id, draft));+ }++ /// gitcraft's code styles as cards, the VS Code themes imported below them.+ fn themes(&mut self, ui: &mut Ui) {+ let t = Tokens::get(ui.ctx());+ egui::Grid::new("settings-themes")+ .num_columns(2)+ .spacing([12.0, 12.0])+ .show(ui, |ui| {+ for (i, style) in SyntaxStyle::ALL.into_iter().enumerate() {+ let chosen = self.theme == CodeTheme::Builtin(style);+ let card = Card {+ label: style.label(),+ theme: style.theme(t.dark()),+ background: t.dock,+ text: t.text,+ };+ if card.ui(ui, chosen, false).0.clicked() {+ self.theme = CodeTheme::Builtin(style);+ }+ if i % 2 == 1 {+ ui.end_row();+ }+ }+ });+ ui.add_space(12.0);+ self.import_button(ui);++ if self.imported_themes.is_empty() {+ return;+ }+ ui.add_space(14.0);+ ui.label(+ RichText::new("VS CODE THEMES")+ .font(theme::semibold(10.5))+ .color(t.text_faint),+ );+ ui.label(+ RichText::new("A VS Code theme colours the whole window, not just the code.")+ .color(t.text_faint)+ .small(),+ );+ ui.add_space(4.0);+ let mut remove = None;+ egui::Grid::new("settings-vscode-themes")+ .num_columns(2)+ .spacing([12.0, 12.0])+ .show(ui, |ui| {+ for (i, info) in self.imported_themes.iter().enumerate() {+ let name = &info.name;+ let chosen = self.theme == CodeTheme::VsCode(name.clone());+ let (resp, removed) = match vscode::color_theme(info) {+ Some(vs) => Card {+ label: name,+ theme: &vs.syntax,+ background: vs.color("editor.background").unwrap_or(t.dock),+ text: vs.color("editor.foreground").unwrap_or(t.text),+ }+ .ui(ui, chosen, true),+ None => missing_card(ui, name),+ };+ if resp.clicked() {+ self.theme = CodeTheme::VsCode(name.clone());+ }+ if removed {+ remove = Some(i);+ }+ if i % 2 == 1 {+ ui.end_row();+ }+ }+ });+ if let Some(i) = remove {+ let info = self.imported_themes.remove(i);+ if self.theme == CodeTheme::VsCode(info.name) {+ self.theme = CodeTheme::default();+ }+ }+ }++ /// "Import VS Code themes": a list of the colour themes installed in VS Code; picking one+ /// adds it to the VS Code themes.+ fn import_button(&mut self, ui: &mut Ui) {+ let t = Tokens::get(ui.ctx());+ let resp = ui.button("Import VS Code themes…");+ egui::Popup::menu(&resp)+ .style(theme::menu_style)+ .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)+ .show(|ui| {+ let installed = vscode::color_themes();+ if installed.is_empty() {+ egui::Frame::new()+ .inner_margin(egui::Margin::symmetric(16, 4))+ .show(ui, |ui| {+ ui.label(RichText::new("No VS Code themes found").color(t.text_faint));+ });+ return;+ }+ egui::ScrollArea::vertical()+ .max_height(360.0)+ .show(ui, |ui| {+ ui.set_width(280.0);+ for info in installed {+ let imported = self.imported_themes.iter().any(|t| t.name == info.name);+ let kind = if info.dark { "dark" } else { "light" };+ let label = ui.add_enabled(+ !imported,+ egui::Button::new(&info.name)+ .right_text(RichText::new(kind).color(t.text_faint).small())+ .frame(false)+ .min_size(egui::vec2(280.0, 0.0)),+ );+ if label.clicked() {+ self.imported_themes.push(info);+ }+ }+ });+ });+ }+}++/// A theme's preview in the settings: its name over the sample code in its colours.+struct Card<'a> {+ label: &'a str,+ theme: &'a syntect::highlighting::Theme,+ background: egui::Color32,+ text: egui::Color32,+}++const CARD_W: f32 = 312.0;++impl Card<'_> {+ /// Draws it, the chosen one outlined; with `removable`, a button to remove it shows on+ /// hover. Returns its response and whether it was removed.+ fn ui(&self, ui: &mut Ui, chosen: bool, removable: bool) -> (egui::Response, bool) {+ let t = Tokens::get(ui.ctx());+ let font = egui::FontId::monospace(11.0);+ let mut job = egui::text::LayoutJob::default();+ let lines = crate::repo::highlight::highlight_with(+ "sample.rs",+ self.theme,+ SAMPLE.lines(),+ self.text,+ )+ .unwrap_or_default();+ for (n, spans) in lines.iter().enumerate() {+ if n > 0 {+ job.append("\n", 0.0, egui::TextFormat::simple(font.clone(), self.text));+ }+ for (color, text) in spans {+ job.append(text, 0.0, egui::TextFormat::simple(font.clone(), *color));+ }+ }+ let galley = ui.painter().layout_job(job);+ let size = egui::vec2(CARD_W, galley.size().y + 42.0);+ let (rect, resp) = ui.allocate_exact_size(size, egui::Sense::click());+ card_frame(ui, rect, &resp, chosen, self.background);+ let p = ui.painter();+ let label = if chosen {+ self.text+ } else {+ self.text.gamma_multiply(0.75)+ };+ p.with_clip_rect(rect.shrink(2.0)).text(+ rect.left_top() + egui::vec2(12.0, 10.0),+ egui::Align2::LEFT_TOP,+ self.label,+ theme::semibold(12.0),+ label,+ );+ p.with_clip_rect(rect.shrink(2.0)).galley(+ rect.left_top() + egui::vec2(12.0, 32.0),+ galley,+ self.text,+ );+ let mut removed = false;+ if removable && ui.rect_contains_pointer(rect) {+ let close = egui::Rect::from_center_size(+ rect.right_top() + egui::vec2(-16.0, 16.0),+ egui::vec2(20.0, 20.0),+ );+ let x = ui.interact(close, resp.id.with("remove"), egui::Sense::click());+ let color = if x.hovered() { self.text } else { t.text_faint };+ crate::icons::paint(ui, close, "x", 14.0, color);+ removed = x.on_hover_text("Remove").clicked();+ }+ (resp, removed)+ }+}++/// An imported theme VS Code no longer has: a card saying so, to remove it.+fn missing_card(ui: &mut Ui, name: &str) -> (egui::Response, bool) {+ let t = Tokens::get(ui.ctx());+ let (rect, resp) = ui.allocate_exact_size(egui::vec2(CARD_W, 60.0), egui::Sense::hover());+ card_frame(ui, rect, &resp, false, t.dock);+ ui.painter().text(+ rect.left_top() + egui::vec2(12.0, 10.0),+ egui::Align2::LEFT_TOP,+ format!("{name}\nnot found in VS Code"),+ egui::FontId::proportional(12.0),+ t.text_faint,+ );+ let close = egui::Rect::from_center_size(+ rect.right_top() + egui::vec2(-16.0, 16.0),+ egui::vec2(20.0, 20.0),+ );+ let x = ui.interact(close, resp.id.with("remove"), egui::Sense::click());+ crate::icons::paint(ui, close, "x", 14.0, t.text_faint);+ let removed = x.on_hover_text("Remove").clicked();+ (resp, removed)+}++fn card_frame(ui: &Ui, rect: egui::Rect, resp: &egui::Response, chosen: bool, fill: egui::Color32) {+ let t = Tokens::get(ui.ctx());+ let stroke = if chosen {+ egui::Stroke::new(2.0, t.accent)+ } else if resp.hovered() {+ egui::Stroke::new(1.0, t.text_faint)+ } else {+ egui::Stroke::new(1.0, t.field_border)+ };+ ui.painter()+ .rect(rect, t.radius, fill, stroke, egui::StrokeKind::Inside);+}diff --git a/src/theme.rs b/src/theme.rsindex d94f472..cb29955 100644--- a/src/theme.rs+++ b/src/theme.rs@@ -2,6 +2,7 @@//! a blue accent, Inter for the UI and JetBrains Mono for hashes and diffs.//!//! Widgets read [`Tokens::get`] instead of hard-coding colours, so every theme applies everywhere.+//! With a VS Code theme chosen, [`Tokens::with_vscode`] repaints them in its workbench colours.use std::sync::Arc;@@ -11,6 +12,8 @@ use egui::{};use serde::{Deserialize, Serialize};+use crate::vscode::theme::EditorTheme;+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]pub enum ThemeKind {/// Charcoal panels (PhotoCraft's "Pro (Dark)").@@ -147,6 +150,89 @@ impl Tokens {}}+ /// The tokens recoloured with a VS Code theme's workbench colours (as CodeCraft does). The+ /// base is gitcraft's dark or light palette, whichever matches the theme, for anything it+ /// doesn't set.+ pub fn with_vscode(vs: &EditorTheme) -> Self {+ let base = Tokens::for_kind(if vs.dark {+ ThemeKind::Dark+ } else {+ ThemeKind::Light+ });+ let editor = vs+ .color("editor.background")+ .unwrap_or(base.dock)+ .to_opaque();+ // Translucent colours are laid over the editor's background.+ let get = |keys: &[&str]| keys.iter().find_map(|k| vs.color(k));+ let solid =+ |keys: &[&str], fallback: Color32| get(keys).map_or(fallback, |c| over(editor, c));+ let text = solid(&["editor.foreground", "foreground"], base.text);+ let sidebar = solid(&["sideBar.background"], editor);+ // The colour VS Code marks the active tab or view with.+ let accent = solid(+ &[+ "tab.activeBorderTop",+ "tab.activeBorder",+ "activityBar.activeBorder",+ "activityBarBadge.background",+ "focusBorder",+ ],+ base.accent,+ );+ // Dark text on a bright accent, white on a dark one.+ let [r, g, b, _] = accent.to_srgba_unmultiplied();+ let luma = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;+ let accent_text = if luma > 150.0 {+ Color32::from_rgb(30, 30, 30)+ } else {+ Color32::WHITE+ };+ let mix = |a: Color32, b: Color32, t: f32| a.lerp_to_gamma(b, t);+ Tokens {+ chrome: sidebar,+ dock: editor,+ card: sidebar,+ field: solid(&["input.background"], mix(editor, Color32::BLACK, 0.1)),+ field_border: solid(+ &["input.border", "dropdown.border", "widget.border"],+ mix(editor, text, 0.25),+ ),+ hover: solid(&["list.hoverBackground"], mix(sidebar, text, 0.08)),+ pressed: mix(sidebar, text, 0.16),+ text,+ text_dim: solid(&["sideBar.foreground"], mix(text, editor, 0.25)),+ text_faint: solid(&["descriptionForeground"], mix(text, editor, 0.45)),+ icon: solid(&["icon.foreground"], mix(text, editor, 0.15)),+ accent,+ accent_text,+ separator: solid(+ &["sideBar.border", "editorGroup.border", "panel.border"],+ mix(editor, Color32::BLACK, 0.25),+ ),+ tab_strip: solid(&["editorGroupHeader.tabsBackground"], sidebar),+ row_selected: solid(+ &[+ "list.activeSelectionBackground",+ "list.inactiveSelectionBackground",+ ],+ base.row_selected,+ ),+ // Laid over the lines, so they stay translucent.+ diff_add_bg: get(&[+ "diffEditor.insertedLineBackground",+ "diffEditor.insertedTextBackground",+ ])+ .unwrap_or(base.diff_add_bg),+ diff_del_bg: get(&[+ "diffEditor.removedLineBackground",+ "diffEditor.removedTextBackground",+ ])+ .unwrap_or(base.diff_del_bg),+ ..base+ }+ }+pub fn dark(&self) -> bool {self.kind != ThemeKind::Light}@@ -187,6 +273,13 @@ impl Tokens {}}+/// `top` painted over `bottom`, opaque.+fn over(bottom: Color32, top: Color32) -> Color32 {+ let [r, g, b, a] = top.to_srgba_unmultiplied();+ let solid = Color32::from_rgb(r, g, b);+ bottom.lerp_to_gamma(solid, a as f32 / 255.0)+}+fn tokens_id() -> egui::Id {egui::Id::new("gitcraft-theme")}@@ -268,8 +361,8 @@ pub fn menu_style(s: &mut egui::Style) {}}-pub fn apply(ctx: &egui::Context, kind: ThemeKind) {- let t = Tokens::for_kind(kind);+/// Makes `t` the theme of the whole UI.+pub fn apply(ctx: &egui::Context, t: Tokens) {ctx.data_mut(|d| d.insert_temp(tokens_id(), t));let mut v = if t.dark() {Visuals::dark()diff --git a/src/vscode/mod.rs b/src/vscode/mod.rsnew file mode 100644index 0000000..59f5fcd--- /dev/null+++ b/src/vscode/mod.rs@@ -0,0 +1,336 @@+//! VS Code's colour themes ([`theme`]), to import into gitcraft.+//!+//! Listing them means scanning every extension's `package.json` (built-in ones included), so+//! that is only done when the list is asked for, and kept. An imported theme remembers its+//! file, so loading it later reads just that file.++pub mod theme;++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex};++use egui::Color32;+use serde_json::Value;++/// A colour theme installed in VS Code.+#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]+pub struct ThemeInfo {+ pub name: String,+ pub dark: bool,+ /// The theme file.+ pub path: PathBuf,+}++/// What the extensions of every installed VS Code flavour contribute, scanned once.+fn extensions() -> Arc<Extensions> {+ static SCANNED: Mutex<Option<Arc<Extensions>>> = Mutex::new(None);+ let Ok(mut scanned) = SCANNED.lock() else {+ return Arc::default();+ };+ Arc::clone(scanned.get_or_insert_with(|| Arc::new(scan(&extension_dirs()))))+}++/// The colour themes installed in VS Code, by name, each once.+pub fn color_themes() -> Vec<ThemeInfo> {+ color_themes_in(&extensions())+}++fn color_themes_in(extensions: &Extensions) -> Vec<ThemeInfo> {+ let mut out: Vec<ThemeInfo> = Vec::new();+ for c in &extensions.color_themes {+ let Some(name) = c.label.clone().or_else(|| c.id.clone()) else {+ continue;+ };+ if out.iter().all(|t| t.name != name) {+ out.push(ThemeInfo {+ name,+ dark: theme::ui_dark(c.ui_theme.as_deref()),+ path: c.path.clone(),+ });+ }+ }+ out.sort_by_key(|t| t.name.to_lowercase());+ out+}++/// A colour theme read from its file, once and kept.+pub fn color_theme(info: &ThemeInfo) -> Option<Arc<theme::EditorTheme>> {+ type Cache = HashMap<PathBuf, Option<Arc<theme::EditorTheme>>>;+ static CACHE: Mutex<Option<Cache>> = Mutex::new(None);+ if let Ok(cache) = CACHE.lock()+ && let Some(found) = cache.as_ref().and_then(|c| c.get(&info.path))+ {+ return found.clone();+ }+ let found = theme::load_file(&info.name, &info.path, info.dark).map(Arc::new);+ if let Ok(mut cache) = CACHE.lock() {+ cache+ .get_or_insert_with(HashMap::new)+ .insert(info.path.clone(), found.clone());+ }+ found+}++fn home() -> Option<PathBuf> {+ std::env::var_os("HOME")+ .or_else(|| std::env::var_os("USERPROFILE"))+ .map(PathBuf::from)+}++/// Folders a VS Code install keeps its built-in extensions in.+fn builtin_dirs(install: &Path) -> Vec<PathBuf> {+ let mut dirs = vec![+ install.join("extensions"),+ install.join("resources/app/extensions"),+ ];+ // Newer Windows installs put each version in a folder of its own.+ if let Ok(entries) = std::fs::read_dir(install) {+ for e in entries.flatten() {+ dirs.push(e.path().join("resources/app/extensions"));+ }+ }+ dirs.into_iter().filter(|d| d.is_dir()).collect()+}++/// Where VS Code, VS Code Insiders and VSCodium keep their extensions, user and built-in.+fn extension_dirs() -> Vec<PathBuf> {+ let Some(home) = home() else {+ return Vec::new();+ };+ let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from);+ let program_files = std::env::var_os("ProgramFiles").map(PathBuf::from);+ // (user extensions folder, install folder names)+ let flavours: [(&str, &[&str]); 3] = [+ (+ ".vscode",+ &[+ "Microsoft VS Code",+ "Visual Studio Code.app/Contents/Resources/app",+ "code",+ "visual-studio-code",+ ],+ ),+ (+ ".vscode-insiders",+ &[+ "Microsoft VS Code Insiders",+ "Visual Studio Code - Insiders.app/Contents/Resources/app",+ "code-insiders",+ ],+ ),+ (+ ".vscode-oss",+ &[+ "VSCodium",+ "VSCodium.app/Contents/Resources/app",+ "codium",+ "vscodium",+ ],+ ),+ ];+ let mut roots: Vec<PathBuf> = Vec::new();+ if let Some(l) = &local {+ roots.push(l.join("Programs"));+ }+ if let Some(p) = &program_files {+ roots.push(p.clone());+ }+ roots.extend(["/Applications", "/usr/share", "/usr/lib", "/opt"].map(PathBuf::from));++ flavours+ .iter()+ .flat_map(|(extensions, installs)| {+ let mut dirs = vec![home.join(extensions).join("extensions")];+ for root in &roots {+ for name in *installs {+ dirs.extend(builtin_dirs(&root.join(name)));+ }+ }+ dirs+ })+ .collect()+}++/// A colour theme an extension contributes.+pub struct Contribution {+ pub id: Option<String>,+ pub label: Option<String>,+ /// The theme file, absolute.+ pub path: PathBuf,+ /// `uiTheme` (`vs`, `vs-dark`, `hc-black`, `hc-light`).+ pub ui_theme: Option<String>,+}++/// What the installed extensions contribute, user extensions first.+#[derive(Default)]+pub struct Extensions {+ pub color_themes: Vec<Contribution>,+}++fn scan(dirs: &[PathBuf]) -> Extensions {+ let mut out = Extensions::default();+ for dir in dirs {+ let Ok(entries) = std::fs::read_dir(dir) else {+ continue;+ };+ // Newest version first when an extension is installed more than once.+ let mut exts: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();+ exts.sort();+ exts.reverse();+ for ext in exts {+ let Some(pkg) = read_jsonc(&ext.join("package.json")) else {+ continue;+ };+ let Some(contributes) = pkg.get("contributes") else {+ continue;+ };+ let mut nls = None;+ let mut contributions = |key: &str| -> Vec<Contribution> {+ let Some(list) = contributes.get(key).and_then(Value::as_array) else {+ return Vec::new();+ };+ list.iter()+ .filter_map(|t| {+ let mut label = t.get("label").and_then(Value::as_str).map(str::to_owned);+ if let Some(key) = label+ .as_deref()+ .and_then(|l| l.strip_prefix('%'))+ .and_then(|l| l.strip_suffix('%'))+ {+ let nls = nls+ .get_or_insert_with(|| read_jsonc(&ext.join("package.nls.json")));+ label = nls+ .as_ref()+ .and_then(|n| n.get(key))+ .and_then(Value::as_str)+ .map(str::to_owned);+ }+ Some(Contribution {+ id: t.get("id").and_then(Value::as_str).map(str::to_owned),+ label,+ path: ext.join(t.get("path").and_then(Value::as_str)?),+ ui_theme: t.get("uiTheme").and_then(Value::as_str).map(str::to_owned),+ })+ })+ .collect()+ };+ out.color_themes.extend(contributions("themes"));+ }+ }+ out+}++/// `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`, as straight (unmultiplied) RGBA.+pub fn parse_color(s: &str) -> Option<[u8; 4]> {+ let hex = s.trim().strip_prefix('#')?;+ let digit =+ |i: usize, len: usize| u8::from_str_radix(hex.get(i * len..i * len + len)?, 16).ok();+ match hex.len() {+ 3 | 4 => {+ let d = |i| digit(i, 1).map(|v| v * 17);+ Some([+ d(0)?,+ d(1)?,+ d(2)?,+ if hex.len() == 4 { d(3)? } else { 255 },+ ])+ }+ 6 | 8 => Some([+ digit(0, 2)?,+ digit(1, 2)?,+ digit(2, 2)?,+ if hex.len() == 8 { digit(3, 2)? } else { 255 },+ ]),+ _ => None,+ }+}++pub fn parse_color32(s: &str) -> Option<Color32> {+ let [r, g, b, a] = parse_color(s)?;+ Some(Color32::from_rgba_unmultiplied(r, g, b, a))+}++fn read_jsonc(path: &Path) -> Option<Value> {+ let text = std::fs::read_to_string(path).ok()?;+ serde_json::from_str(&strip_jsonc(text.trim_start_matches('\u{feff}'))).ok()+}++/// Removes the comments and trailing commas VS Code allows in its JSON files.+fn strip_jsonc(src: &str) -> String {+ let mut out = String::with_capacity(src.len());+ let mut chars = src.chars().peekable();+ let mut in_string = false;+ while let Some(c) = chars.next() {+ if in_string {+ out.push(c);+ match c {+ '\\' => out.extend(chars.next()),+ '"' => in_string = false,+ _ => {}+ }+ continue;+ }+ match (c, chars.peek()) {+ ('"', _) => {+ in_string = true;+ out.push(c);+ }+ ('/', Some('/')) => {+ for c in chars.by_ref() {+ if c == '\n' {+ out.push('\n');+ break;+ }+ }+ }+ ('/', Some('*')) => {+ chars.next();+ let mut prev = ' ';+ for c in chars.by_ref() {+ if prev == '*' && c == '/' {+ break;+ }+ prev = c;+ }+ out.push(' ');+ }+ (']' | '}', _) => {+ // Drop a comma left right before the closing bracket.+ let kept = out.trim_end().len();+ if out[..kept].ends_with(',') {+ out.truncate(kept - 1);+ }+ out.push(c);+ }+ _ => out.push(c),+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn strips_comments_and_trailing_commas() {+ let src = r#"{+ // a comment+ "a": "http://x", /* block */ "b": [1, 2,],+ "c": "quote \" // not a comment",+ }"#;+ let v: Value = serde_json::from_str(&strip_jsonc(src)).unwrap_or_default();+ assert_eq!(v["a"], "http://x");+ assert_eq!(v["b"], serde_json::json!([1, 2]));+ assert_eq!(v["c"], "quote \" // not a comment");+ }++ #[test]+ fn parses_colours() {+ assert_eq!(parse_color("#fcfcfa"), Some([0xfc, 0xfc, 0xfa, 255]));+ assert_eq!(parse_color("#f0a8"), Some([255, 0, 0xaa, 0x88]));+ assert_eq!(parse_color("#12345"), None);+ assert_eq!(parse_color("red"), None);+ }+}diff --git a/src/vscode/theme.rs b/src/vscode/theme.rsnew file mode 100644index 0000000..19f20c2--- /dev/null+++ b/src/vscode/theme.rs@@ -0,0 +1,189 @@+//! VS Code's colour theme: its token colours as a syntect theme for the editor, and its+//! workbench colours for the rest of the window (see `theme::Tokens::with_vscode`).++use std::path::Path;+use std::str::FromStr;++use egui::Color32;+use serde_json::Value;+use syntect::highlighting::{+ Color, ScopeSelectors, StyleModifier, Theme, ThemeItem, ThemeSettings,+};++use super::{parse_color, parse_color32, read_jsonc};++/// A VS Code colour theme, ready for syntect and the window.+pub struct EditorTheme {+ pub dark: bool,+ pub syntax: Theme,+ /// Workbench colours (`editor.background`, `sideBar.background`, ...).+ colors: serde_json::Map<String, Value>,+}++impl EditorTheme {+ /// A workbench colour, if the theme sets it.+ pub fn color(&self, key: &str) -> Option<Color32> {+ self.colors+ .get(key)+ .and_then(Value::as_str)+ .and_then(parse_color32)+ }+}++/// Whether a theme is dark by its extension's `uiTheme`.+pub fn ui_dark(ui_theme: Option<&str>) -> bool {+ !matches!(ui_theme, Some("vs" | "hc-light"))+}++/// Reads the theme `name` from its file; `ui_dark` is what its extension says it is, in case+/// the file doesn't say.+pub fn load_file(name: &str, path: &Path, ui_dark: bool) -> Option<EditorTheme> {+ let (colors, rules, kind) = read_theme(path, 0)?;+ let dark = match kind.as_deref() {+ Some("light" | "hcLight") => false,+ Some(_) => true,+ None => ui_dark,+ };+ Some(EditorTheme {+ syntax: build(name, &colors, &rules),+ dark,+ colors,+ })+}++/// Workbench colours, token rules and type (`dark`, `light`, ...) of a theme file.+type ThemeFile = (serde_json::Map<String, Value>, Vec<Value>, Option<String>);++/// Reads a theme file, following its `include`s.+fn read_theme(path: &Path, depth: u32) -> Option<ThemeFile> {+ if depth > 8 {+ return None;+ }+ let json = read_jsonc(path)?;+ let (mut colors, mut rules, mut kind) = match json.get("include").and_then(Value::as_str) {+ Some(inc) => read_theme(&path.parent()?.join(inc), depth + 1)?,+ None => Default::default(),+ };+ if let Some(c) = json.get("colors").and_then(Value::as_object) {+ colors.extend(c.clone());+ }+ // A theme may point at a .tmTheme file instead; only inline rules are read.+ if let Some(r) = json.get("tokenColors").and_then(Value::as_array) {+ rules.extend(r.iter().cloned());+ }+ if let Some(t) = json.get("type").and_then(Value::as_str) {+ kind = Some(t.to_owned());+ }+ Some((colors, rules, kind))+}++fn syntect_color(s: &str) -> Option<Color> {+ let [r, g, b, a] = parse_color(s)?;+ Some(Color { r, g, b, a })+}++fn build(name: &str, colors: &serde_json::Map<String, Value>, rules: &[Value]) -> Theme {+ let color = |key: &str| {+ colors+ .get(key)+ .and_then(Value::as_str)+ .and_then(syntect_color)+ };+ let mut settings = ThemeSettings {+ foreground: color("editor.foreground"),+ background: color("editor.background"),+ ..Default::default()+ };+ let mut scopes = Vec::new();+ for rule in rules {+ let Some(s) = rule.get("settings") else {+ continue;+ };+ let foreground = s+ .get("foreground")+ .and_then(Value::as_str)+ .and_then(syntect_color);+ let selector = match rule.get("scope") {+ Some(Value::String(s)) => s.clone(),+ Some(Value::Array(list)) => list+ .iter()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>()+ .join(", "),+ // A rule without a scope sets the defaults.+ _ => {+ if settings.foreground.is_none() {+ settings.foreground = foreground;+ }+ continue;+ }+ };+ let Some(foreground) = foreground else {+ continue;+ };+ let Ok(scope) = ScopeSelectors::from_str(selector.trim()) else {+ continue;+ };+ scopes.push(ThemeItem {+ scope,+ style: StyleModifier {+ foreground: Some(foreground),+ background: None,+ font_style: None,+ },+ });+ }+ Theme {+ name: Some(name.to_owned()),+ author: None,+ settings,+ scopes,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_an_extension_theme_with_include() {+ let dir = std::env::temp_dir().join(format!("gitcraft-vstheme-{}", std::process::id()));+ let ext = dir.join("someone.nice-theme-1.0.0");+ let _ = std::fs::create_dir_all(ext.join("themes"));+ let write = |p: &str, s: &str| {+ let _ = std::fs::write(ext.join(p), s);+ };+ write(+ "package.json",+ r#"{ "contributes": { "themes": [+ { "label": "%label%", "uiTheme": "vs-dark", "path": "./themes/nice.json" } ] } }"#,+ );+ write("package.nls.json", r#"{ "label": "Nice Dark" }"#);+ write(+ "themes/base.json",+ r##"{ "colors": { "editor.foreground": "#aaaaaa", "sideBar.background": "#202020" },+ "tokenColors": [ { "scope": "comment", "settings": { "foreground": "#777777" } } ] }"##,+ );+ write(+ "themes/nice.json",+ r##"{ "include": "./base.json", // comment+ "tokenColors": [ { "scope": ["keyword", "storage"], "settings": { "foreground": "#ff6188" } }, ] }"##,+ );+ let extensions = super::super::scan(std::slice::from_ref(&dir));+ let found = super::super::color_themes_in(&extensions);+ let theme = found+ .first()+ .and_then(|t| load_file(&t.name, &t.path, t.dark));+ assert_eq!(found.first().map(|t| t.name.as_str()), Some("Nice Dark"));+ let _ = std::fs::remove_dir_all(&dir);+ assert!(theme.is_some(), "theme not found");+ let Some(theme) = theme else { return };+ assert!(theme.dark);+ assert_eq!(theme.syntax.scopes.len(), 2);+ assert_eq!(theme.syntax.settings.foreground, syntect_color("#aaaaaa"));+ assert_eq!(+ theme.color("sideBar.background"),+ Some(Color32::from_rgb(0x20, 0x20, 0x20))+ );+ }+}diff --git a/src/vscode_theme.rs b/src/vscode_theme.rsdeleted file mode 100644index 1746aad..0000000--- a/src/vscode_theme.rs+++ /dev/null@@ -1,470 +0,0 @@-//! The colour theme VS Code is using, read from its settings and extensions and turned into a-//! syntect theme, so diffs and blame colour code like the editor does.--use std::path::{Path, PathBuf};-use std::str::FromStr;-use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, Mutex};-use std::time::SystemTime;--use serde_json::Value;-use syntect::highlighting::{- Color, ScopeSelectors, StyleModifier, Theme, ThemeItem, ThemeSettings,-};--/// A VS Code theme ready for syntect.-pub struct EditorTheme {- pub name: String,- pub dark: bool,- pub theme: Theme,-}--static ENABLED: AtomicBool = AtomicBool::new(true);--/// Follow VS Code's theme or not (the "Code colours" setting).-pub fn set_enabled(on: bool) {- ENABLED.store(on, Ordering::Relaxed);-}--pub fn enabled() -> bool {- ENABLED.load(Ordering::Relaxed)-}--/// The theme selected in VS Code; `None` when VS Code isn't installed or its theme can't be-/// found. Reloaded when VS Code's settings file changes.-pub fn current() -> Option<Arc<EditorTheme>> {- type Cache = Option<(PathBuf, Option<SystemTime>, Option<Arc<EditorTheme>>)>;- static CACHE: Mutex<Cache> = Mutex::new(None);-- let editor = installed_editors()- .into_iter()- .find(|e| e.settings.is_file())?;- let modified = std::fs::metadata(&editor.settings)- .and_then(|m| m.modified())- .ok();- let mut cache = CACHE.lock().ok()?;- if let Some((path, when, theme)) = cache.as_ref()- && *path == editor.settings- && *when == modified- {- return theme.clone();- }- let theme = load(&editor).map(Arc::new);- *cache = Some((editor.settings.clone(), modified, theme.clone()));- theme-}--/// One VS Code flavour: its user settings file and where its extensions live.-struct Editor {- settings: PathBuf,- extension_dirs: Vec<PathBuf>,-}--fn home() -> Option<PathBuf> {- std::env::var_os("HOME")- .or_else(|| std::env::var_os("USERPROFILE"))- .map(PathBuf::from)-}--fn config_dir() -> Option<PathBuf> {- if cfg!(windows) {- std::env::var_os("APPDATA").map(PathBuf::from)- } else if cfg!(target_os = "macos") {- home().map(|h| h.join("Library/Application Support"))- } else {- std::env::var_os("XDG_CONFIG_HOME")- .map(PathBuf::from)- .or_else(|| home().map(|h| h.join(".config")))- }-}--/// Folders a VS Code install keeps its built-in extensions in.-fn builtin_dirs(install: &Path) -> Vec<PathBuf> {- let mut dirs = vec![- install.join("extensions"),- install.join("resources/app/extensions"),- ];- // Newer Windows installs put each version in a folder of its own.- if let Ok(entries) = std::fs::read_dir(install) {- for e in entries.flatten() {- dirs.push(e.path().join("resources/app/extensions"));- }- }- dirs.into_iter().filter(|d| d.is_dir()).collect()-}--fn installed_editors() -> Vec<Editor> {- let (Some(config), Some(home)) = (config_dir(), home()) else {- return Vec::new();- };- let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from);- let program_files = std::env::var_os("ProgramFiles").map(PathBuf::from);- // (settings folder, user extensions folder, install folder names)- let flavours: [(&str, &str, &[&str]); 3] = [- (- "Code",- ".vscode",- &[- "Microsoft VS Code",- "Visual Studio Code.app/Contents/Resources/app",- "code",- "visual-studio-code",- ],- ),- (- "Code - Insiders",- ".vscode-insiders",- &[- "Microsoft VS Code Insiders",- "Visual Studio Code - Insiders.app/Contents/Resources/app",- "code-insiders",- ],- ),- (- "VSCodium",- ".vscode-oss",- &[- "VSCodium",- "VSCodium.app/Contents/Resources/app",- "codium",- "vscodium",- ],- ),- ];- let mut roots: Vec<PathBuf> = Vec::new();- if let Some(l) = &local {- roots.push(l.join("Programs"));- }- if let Some(p) = &program_files {- roots.push(p.clone());- }- roots.extend(["/Applications", "/usr/share", "/usr/lib", "/opt"].map(PathBuf::from));-- flavours- .iter()- .map(|(settings, extensions, installs)| {- let mut extension_dirs = vec![home.join(extensions).join("extensions")];- for root in &roots {- for name in *installs {- extension_dirs.extend(builtin_dirs(&root.join(name)));- }- }- Editor {- settings: config.join(settings).join("User/settings.json"),- extension_dirs,- }- })- .collect()-}--fn load(editor: &Editor) -> Option<EditorTheme> {- let settings = read_jsonc(&editor.settings)?;- let name = settings.get("workbench.colorTheme")?.as_str()?.to_owned();- let (path, ui_dark) = find_theme(&editor.extension_dirs, &name)?;- let (colors, rules, kind) = read_theme(&path, 0)?;- let dark = match kind.as_deref() {- Some("light" | "hcLight") => false,- Some(_) => true,- None => ui_dark,- };- Some(EditorTheme {- theme: build(&name, &colors, &rules),- name,- dark,- })-}--/// Finds the theme file contributed under `name` (its label or id), and whether VS Code-/// treats it as dark.-fn find_theme(dirs: &[PathBuf], name: &str) -> Option<(PathBuf, bool)> {- for dir in dirs {- let Ok(entries) = std::fs::read_dir(dir) else {- continue;- };- // Newest version first when an extension is installed more than once.- let mut exts: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();- exts.sort();- exts.reverse();- for ext in exts {- let Some(pkg) = read_jsonc(&ext.join("package.json")) else {- continue;- };- let Some(themes) = pkg.pointer("/contributes/themes").and_then(Value::as_array) else {- continue;- };- let mut nls = None;- for t in themes {- let id = t.get("id").and_then(Value::as_str);- let mut label = t.get("label").and_then(Value::as_str).map(str::to_owned);- if let Some(key) = label- .as_deref()- .and_then(|l| l.strip_prefix('%'))- .and_then(|l| l.strip_suffix('%'))- {- let nls = nls.get_or_insert_with(|| read_jsonc(&ext.join("package.nls.json")));- label = nls- .as_ref()- .and_then(|n| n.get(key))- .and_then(Value::as_str)- .map(str::to_owned);- }- if id != Some(name) && label.as_deref() != Some(name) {- continue;- }- let path = t.get("path").and_then(Value::as_str)?;- let ui = t- .get("uiTheme")- .and_then(Value::as_str)- .unwrap_or("vs-dark");- return Some((ext.join(path), !matches!(ui, "vs" | "hc-light")));- }- }- }- None-}--/// Workbench colours, token rules and type (`dark`, `light`, ...) of a theme file.-type ThemeFile = (serde_json::Map<String, Value>, Vec<Value>, Option<String>);--/// Reads a theme file, following its `include`s.-fn read_theme(path: &Path, depth: u32) -> Option<ThemeFile> {- if depth > 8 {- return None;- }- let json = read_jsonc(path)?;- let (mut colors, mut rules, mut kind) = match json.get("include").and_then(Value::as_str) {- Some(inc) => read_theme(&path.parent()?.join(inc), depth + 1)?,- None => Default::default(),- };- if let Some(c) = json.get("colors").and_then(Value::as_object) {- colors.extend(c.clone());- }- // A theme may point at a .tmTheme file instead; only inline rules are read.- if let Some(r) = json.get("tokenColors").and_then(Value::as_array) {- rules.extend(r.iter().cloned());- }- if let Some(t) = json.get("type").and_then(Value::as_str) {- kind = Some(t.to_owned());- }- Some((colors, rules, kind))-}--fn build(name: &str, colors: &serde_json::Map<String, Value>, rules: &[Value]) -> Theme {- let color = |key: &str| {- colors- .get(key)- .and_then(Value::as_str)- .and_then(parse_color)- };- let mut settings = ThemeSettings {- foreground: color("editor.foreground"),- background: color("editor.background"),- ..Default::default()- };- let mut scopes = Vec::new();- for rule in rules {- let Some(s) = rule.get("settings") else {- continue;- };- let foreground = s- .get("foreground")- .and_then(Value::as_str)- .and_then(parse_color);- let selector = match rule.get("scope") {- Some(Value::String(s)) => s.clone(),- Some(Value::Array(list)) => list- .iter()- .filter_map(Value::as_str)- .collect::<Vec<_>>()- .join(", "),- // A rule without a scope sets the defaults.- _ => {- if settings.foreground.is_none() {- settings.foreground = foreground;- }- continue;- }- };- let Some(foreground) = foreground else {- continue;- };- let Ok(scope) = ScopeSelectors::from_str(selector.trim()) else {- continue;- };- scopes.push(ThemeItem {- scope,- style: StyleModifier {- foreground: Some(foreground),- background: None,- font_style: None,- },- });- }- Theme {- name: Some(name.to_owned()),- author: None,- settings,- scopes,- }-}--/// `#rgb`, `#rgba`, `#rrggbb` or `#rrggbbaa`.-fn parse_color(s: &str) -> Option<Color> {- let hex = s.trim().strip_prefix('#')?;- let digit =- |i: usize, len: usize| u8::from_str_radix(hex.get(i * len..i * len + len)?, 16).ok();- let (r, g, b, a) = match hex.len() {- 3 | 4 => {- let d = |i| digit(i, 1).map(|v| v * 17);- (- d(0)?,- d(1)?,- d(2)?,- if hex.len() == 4 { d(3)? } else { 255 },- )- }- 6 | 8 => (- digit(0, 2)?,- digit(1, 2)?,- digit(2, 2)?,- if hex.len() == 8 { digit(3, 2)? } else { 255 },- ),- _ => return None,- };- Some(Color { r, g, b, a })-}--fn read_jsonc(path: &Path) -> Option<Value> {- let text = std::fs::read_to_string(path).ok()?;- serde_json::from_str(&strip_jsonc(text.trim_start_matches('\u{feff}'))).ok()-}--/// Removes the comments and trailing commas VS Code allows in its JSON files.-fn strip_jsonc(src: &str) -> String {- let mut out = String::with_capacity(src.len());- let mut chars = src.chars().peekable();- let mut in_string = false;- while let Some(c) = chars.next() {- if in_string {- out.push(c);- match c {- '\\' => out.extend(chars.next()),- '"' => in_string = false,- _ => {}- }- continue;- }- match (c, chars.peek()) {- ('"', _) => {- in_string = true;- out.push(c);- }- ('/', Some('/')) => {- for c in chars.by_ref() {- if c == '\n' {- out.push('\n');- break;- }- }- }- ('/', Some('*')) => {- chars.next();- let mut prev = ' ';- for c in chars.by_ref() {- if prev == '*' && c == '/' {- break;- }- prev = c;- }- out.push(' ');- }- (']' | '}', _) => {- // Drop a comma left right before the closing bracket.- let kept = out.trim_end().len();- if out[..kept].ends_with(',') {- out.truncate(kept - 1);- }- out.push(c);- }- _ => out.push(c),- }- }- out-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn strips_comments_and_trailing_commas() {- let src = r#"{- // a comment- "a": "http://x", /* block */ "b": [1, 2,],- "c": "quote \" // not a comment",- }"#;- let v: Value = serde_json::from_str(&strip_jsonc(src)).unwrap_or_default();- assert_eq!(v["a"], "http://x");- assert_eq!(v["b"], serde_json::json!([1, 2]));- assert_eq!(v["c"], "quote \" // not a comment");- }-- #[test]- fn parses_colours() {- assert_eq!(- parse_color("#fcfcfa"),- Some(Color {- r: 0xfc,- g: 0xfc,- b: 0xfa,- a: 255- })- );- assert_eq!(- parse_color("#f0a8"),- Some(Color {- r: 255,- g: 0,- b: 0xaa,- a: 0x88- })- );- assert_eq!(parse_color("#12345"), None);- assert_eq!(parse_color("red"), None);- }-- #[test]- fn reads_an_extension_theme_with_include() {- let dir = std::env::temp_dir().join(format!("gitcraft-vstheme-{}", std::process::id()));- let ext = dir.join("someone.nice-theme-1.0.0");- let _ = std::fs::create_dir_all(ext.join("themes"));- let write = |p: &str, s: &str| {- let _ = std::fs::write(ext.join(p), s);- };- write(- "package.json",- r#"{ "contributes": { "themes": [- { "label": "%label%", "uiTheme": "vs-dark", "path": "./themes/nice.json" } ] } }"#,- );- write("package.nls.json", r#"{ "label": "Nice Dark" }"#);- write(- "themes/base.json",- r##"{ "colors": { "editor.foreground": "#aaaaaa" },- "tokenColors": [ { "scope": "comment", "settings": { "foreground": "#777777" } } ] }"##,- );- write(- "themes/nice.json",- r##"{ "include": "./base.json", // comment- "tokenColors": [ { "scope": ["keyword", "storage"], "settings": { "foreground": "#ff6188" } }, ] }"##,- );- let found = find_theme(std::slice::from_ref(&dir), "Nice Dark");- let read = found.as_ref().and_then(|(path, _)| read_theme(path, 0));- let _ = std::fs::remove_dir_all(&dir);- assert!(found.is_some_and(|(_, dark)| dark));- assert!(read.is_some());- let (colors, rules, _) = read.unwrap_or_default();- let theme = build("Nice Dark", &colors, &rules);- assert_eq!(theme.scopes.len(), 2);- assert_eq!(theme.settings.foreground, parse_color("#aaaaaa"));- }-}