diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b0b56ff..2315d87 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,7 +87,8 @@ Its tests run against real repositories made with `git` in a temporary folder - `start.rs` (open, clone and create), `ui.rs` (tabs and toolbar), `graph.rs`, `sidebar.rs`, `details.rs`, `diff.rs`, `history.rs` (a file's history), `blame.rs` (who last changed each line), `merge.rs` (a conflicted file) and `rebase.rs` (an interactive rebase) draw the views, and - `theme.rs` has the colours. + `theme.rs` has the colours. `syntax.rs` colours code with the grammar of its language, from + the top of the file, so a diff reads both versions of the file in the background to colour it. The app's tests (`crates/app/src/tests.rs`) drive the whole window the way a user does, through the accessibility tree with [egui_kittest](https://crates.io/crates/egui_kittest). That also keeps diff --git a/Cargo.lock b/Cargo.lock index a6df87e..c875f64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -120,7 +120,7 @@ dependencies = [ "objc2-foundation 0.3.2", "parking_lot", "percent-encoding", - "windows-sys 0.52.0", + "windows-sys 0.61.2", "wl-clipboard-rs", "x11rb", ] @@ -158,6 +158,24 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec 0.8.0", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -176,6 +194,12 @@ dependencies = [ "bit-vec 0.10.1", ] +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bit-vec" version = "0.9.1" @@ -957,7 +981,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -975,6 +999,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "fancy-regex" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f" +dependencies = [ + "bit-set 0.8.0", + "regex-automata", + "regex-syntax", +] + [[package]] name = "faster-hex" version = "0.10.1" @@ -1179,6 +1214,7 @@ dependencies = [ "gitcraft-core", "image", "rfd", + "syntect", "tempfile", ] @@ -2982,7 +3018,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3433,7 +3469,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3681,6 +3717,24 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syntect" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925" +dependencies = [ + "bincode", + "fancy-regex", + "flate2", + "fnv", + "once_cell", + "regex-syntax", + "serde", + "serde_derive", + "thiserror 2.0.21", + "walkdir", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -3691,7 +3745,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4326,7 +4380,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 52ccd22..b208474 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ eframe = { version = "0.37", default-features = false, features = ["default_font egui_kittest = "0.37" rfd = "0.18" image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] } +syntect = { version = "5.3", default-features = false, features = ["default-syntaxes", "default-themes", "regex-fancy"] } tempfile = "3" proptest = "1" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support"] } diff --git a/README.md b/README.md index 287e62d..35255a7 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,10 @@ GitCraft is young. This is what it does today; [ROADMAP.md](ROADMAP.md) has what that name comes first, so typing its name takes you there. Large histories are searched as you type, without the window waiting. - **Commits**: message, author, parents and the files they changed, with the diff of each file. -- **Diffs**: in a line that changed, the words that changed stand out, so a renamed variable or a - new argument is easy to spot. "Side by side" puts the old version on the left and the new one on +- **Diffs**: code has the colours of its language, some fifty of them from Rust and C to Python, + JavaScript, PHP and Go, and a line in a comment or string that started above the change is + coloured as one. In a line that changed, the words that changed stand out, so a renamed + variable or a new argument is easy to spot. "Side by side" puts the old version on the left and the new one on the right, each changed line facing the line that replaced it; you stage or discard lines from either side the same way, and the choice stays for the next diff and the next run. A picture (PNG, JPEG, GIF, WebP, BMP or ICO) shows its old and its new version next to each other, with diff --git a/ROADMAP.md b/ROADMAP.md index dea36ff..b1a6d8a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -50,15 +50,15 @@ drive it the way a user does, and keeps every benchmark as fast as before. - [x] Better diffs, part 1: the words that changed within a line stand out - [x] Better diffs, part 2: the old and the new version side by side - [x] Better diffs, part 3: a picture's old and new version next to each other +- [x] Better diffs, part 4: code in the colours of its language ## Next -1. **Better diffs, part 4**: syntax colouring. -2. **Keyboard**: shortcuts for everything, and a command palette. -3. **Settings**: light and dark theme, font size, date format, default pull mode. -4. **Graph polish**: resizable columns, compact lanes, author avatars (optional, never by default +1. **Keyboard**: shortcuts for everything, and a command palette. +2. **Settings**: light and dark theme, font size, date format, default pull mode. +3. **Graph polish**: resizable columns, compact lanes, author avatars (optional, never by default over the network). -5. **Packaging**: installers with the icon for Windows (MSI), macOS (.app in a .dmg) and Linux +4. **Packaging**: installers with the icon for Windows (MSI), macOS (.app in a .dmg) and Linux (AppImage, .deb, Flatpak), signed where the platform expects it. ## After 1.0 diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index 73152d5..edad3f9 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -12,6 +12,7 @@ gitcraft-core.workspace = true eframe.workspace = true rfd.workspace = true image.workspace = true +syntect.workspace = true [dev-dependencies] egui_kittest.workspace = true diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 43a7520..46a97d4 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -21,6 +21,8 @@ use gitcraft_core::undo::{self, Undo}; use gitcraft_core::watch::Watch; use gitcraft_core::{ObjectId, Result}; +use crate::syntax; + /// What the user asked for. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Action { @@ -190,10 +192,22 @@ pub struct OpenFile { pub diff: FileDiff, /// The picked lines, as hunk and line index. pub lines: BTreeSet<(usize, usize)>, - /// The old and the new version, when the file is a picture. - pub pictures: [Version; 2], - /// The pictures being read, if they are. - pub reading: Reading<[Version; 2]>, + /// The old and the new version, once they are read. + pub versions: Versions, + /// The versions being read, if they are. + pub reading: Reading, +} + +/// The old and the new version of a file, to show more of them than the diff does. +#[derive(Debug, Default)] +pub enum Versions { + /// Not read. + #[default] + None, + /// A picture's. + Pictures([Version; 2]), + /// The lines of code, with their colours; none in a language without colours. + Code([Vec; 2]), } /// A version of a picture, or why it does not show; `None` when the version does not have the file. @@ -218,22 +232,31 @@ impl std::fmt::Debug for Picture { impl OpenFile { fn new(ctx: &egui::Context, repo: &Repo, source: Source, diff: FileDiff) -> Self { - let mut file = Self { source, diff, lines: BTreeSet::new(), pictures: [None, None], reading: None }; - file.read_pictures(ctx, repo); + let mut file = Self { source, diff, lines: BTreeSet::new(), versions: Versions::None, reading: None }; + file.read_versions(ctx, repo); file } - /// Reads the old and the new version in the background, when git sees the file as binary - /// and its name says it is a picture. - fn read_pictures(&mut self, ctx: &egui::Context, repo: &Repo) { + /// Reads the old and the new version in the background: of a picture, when git sees the file + /// as binary and its name says it is one, and else of the code, to colour it. + fn read_versions(&mut self, ctx: &egui::Context, repo: &Repo) { let format = image::ImageFormat::from_path(self.source.path()); - if !self.diff.binary || !format.is_ok_and(|format| format.reading_enabled()) { + let binary = self.diff.binary; + // A link or a submodule has no code: its diff is where it points. + let link = self.diff.header.iter().any(|line| line.ends_with(" 120000") || line.ends_with(" 160000")); + if binary && !format.is_ok_and(|format| format.reading_enabled()) || !binary && link { return; } let (repo, source, context) = (repo.clone(), self.source.clone(), ctx.clone()); self.reading = Some(read_in_background(ctx, move || { - let versions = repo.versions(&source)?; - Ok(versions.map(|version| version.map(|bytes| picture(&context, source.path(), &bytes)))) + let (versions, path) = (repo.versions(&source)?, source.path()); + Ok(if binary { + Versions::Pictures(versions.map(|version| version.map(|bytes| picture(&context, path, &bytes)))) + } else { + Versions::Code( + versions.map(|version| version.map_or_else(Vec::new, |code| syntax::colour(path, &code))), + ) + }) })); } } @@ -739,7 +762,7 @@ impl Workspace { self.open(ctx, source); } - /// Takes in the history, the blame or the pictures of the file in the centre once they are + /// Takes in the history, the blame or the versions of the file in the centre once they are /// read. A history shows the diff of its newest commit when none is open; a blame that /// failed, as when the file is gone, closes. fn take_reading(&mut self, ctx: &egui::Context) { @@ -766,7 +789,7 @@ impl Workspace { && let Some(read) = take(&mut file.reading) { match read { - Ok(pictures) => file.pictures = pictures, + Ok(versions) => file.versions = versions, Err(error) => self.error = Some(error), } } @@ -986,7 +1009,7 @@ impl Workspace { Ok(diff) if diff == file.diff => {} Ok(diff) => { (file.diff, file.lines) = (diff, BTreeSet::new()); - file.read_pictures(ctx, &self.repo); + file.read_versions(ctx, &self.repo); } Err(error) => self.error = Some(error.to_string()), } diff --git a/crates/app/src/diff.rs b/crates/app/src/diff.rs index 6555f2c..ae4b269 100644 --- a/crates/app/src/diff.rs +++ b/crates/app/src/diff.rs @@ -1,5 +1,5 @@ -//! The diff of one file, with the words that changed within its lines, and staging and -//! discarding of hunks and single lines; or a picture's old and new version. +//! The diff of one file, with the colours of its code and the words that changed within its +//! lines, and staging and discarding of hunks and single lines; or a picture's old and new version. use std::ops::Range; @@ -9,7 +9,7 @@ use eframe::egui::{self, Align2, Color32, FontId, Key, Rect, RichText, Sense, Ui use gitcraft_core::diff::{self, LineKind, Source}; use gitcraft_core::git::Op; -use crate::app::{Action, Confirm, OpenFile, Picture}; +use crate::app::{Action, Confirm, OpenFile, Picture, Versions}; use crate::theme; const LINE: f32 = 18.0; @@ -47,28 +47,35 @@ impl ComputerMut<[&str; 2], [Vec>; 2]> for Words { } } -/// A line's text after its `marker`, with its `words` that changed on the `background`. +/// A line's text after its `marker`, in its `colours` (where each starts, `None` for `plain`), and +/// with its `words` that changed on the `background`. fn line_text( marker: &str, text: &str, - words: &[Range], - background: Color32, + colours: &[(usize, Option)], + (words, background): (&[Range], Color32), font: &FontId, - color: Color32, + plain: Color32, ) -> LayoutJob { let mut job = LayoutJob::default(); - let mut add = |text: &str, background| { + let mut add = |text: &str, color, background| { job.append(text, 0.0, TextFormat { font_id: font.clone(), color, background, ..TextFormat::default() }); }; - add(marker, Color32::TRANSPARENT); - let mut at = 0; - // A word can end in the carriage return that is not shown. - for word in words.iter().filter(|word| word.start < text.len()) { - add(&text[at..word.start], Color32::TRANSPARENT); - at = word.end.min(text.len()); - add(&text[word.start..at], background); + add(marker, plain, Color32::TRANSPARENT); + // A piece goes up to where the next colour or word starts or a word ends; a word can end in + // the carriage return that is not shown. + let starts = words.iter().flat_map(|word| [word.start, word.end]).chain(colours.iter().map(|&(at, _)| at)); + let mut cuts: Vec = starts.filter(|&at| at < text.len()).chain([0, text.len()]).collect(); + cuts.sort_unstable(); + cuts.dedup(); + let (mut colour, mut next) = (plain, colours.iter().peekable()); + for piece in cuts.windows(2) { + while let Some(&(_, start)) = next.next_if(|&&(at, _)| at <= piece[0]) { + colour = start.unwrap_or(plain); + } + let changed = words.iter().any(|word| word.contains(&piece[0])); + add(&text[piece[0]..piece[1]], colour, if changed { background } else { Color32::TRANSPARENT }); } - add(&text[at..], Color32::TRANSPARENT); job } @@ -178,16 +185,19 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec /// The old and the new version of a picture side by side, each as large as it is or as fits. fn pictures(ui: &mut Ui, file: &OpenFile) { - if file.pictures.iter().all(Option::is_none) { - if file.reading.is_some() { - ui.spinner(); - } else { - ui.weak("Binary file"); + let pictures = match &file.versions { + Versions::Pictures(pictures) if pictures.iter().any(Option::is_some) => pictures, + _ => { + if file.reading.is_some() { + ui.spinner(); + } else { + ui.weak("Binary file"); + } + return; } - return; - } + }; ui.columns(2, |columns| { - for ((ui, version), name) in columns.iter_mut().zip(&file.pictures).zip(["Old", "New"]) { + for ((ui, version), name) in columns.iter_mut().zip(pictures).zip(["Old", "New"]) { ui.weak(match version { None => format!("{name} · none"), Some(Err(error)) => format!("{name} · cannot be shown: {error}"), @@ -243,11 +253,21 @@ fn line( painter.text(at(x - 6.0), Align2::RIGHT_CENTER, n, FONT, Color32::DARK_GRAY); } let color = ui.visuals().text_color(); + // The version the line is in, the old one for a line in both. + let version = usize::from(line.kind == LineKind::Added); let words = hunk.pair(l).map_or_else(Vec::new, |pair| { - let side = usize::from(line.kind == LineKind::Added); - ui.memory_mut(|m| m.caches.cache::>().get(pair)[side].clone()) + ui.memory_mut(|m| m.caches.cache::>().get(pair)[version].clone()) }); - let job = line_text(marker, line.text.trim_end_matches('\r'), &words, word, &FONT, color); + let text = line.text.trim_end_matches('\r'); + // The line's colours, as long as the version read has the same line there. + let colours = match &file.versions { + Versions::Code(code) => [line.old, line.new][version] + .and_then(|n| code[version].get((n as usize).checked_sub(1)?)) + .filter(|coloured| coloured.text == text) + .map(|coloured| &coloured.colours[..]), + _ => None, + }; + let job = line_text(marker, text, colours.unwrap_or_default(), (&words, word), &FONT, color); let galley = painter.layout_job(job); painter.galley(at(x + 6.0) - Vec2::Y * galley.size().y / 2.0, galley, color); let changed = matches!(line.kind, LineKind::Added | LineKind::Removed); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 60fe212..32d0093 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -11,6 +11,7 @@ mod merge; mod rebase; mod sidebar; mod start; +mod syntax; #[cfg(test)] mod tests; mod theme; diff --git a/crates/app/src/syntax.rs b/crates/app/src/syntax.rs new file mode 100644 index 0000000..a04b572 --- /dev/null +++ b/crates/app/src/syntax.rs @@ -0,0 +1,115 @@ +//! Colours for code, from the grammar of its language: syntect's, for some fifty languages. + +use std::ffi::OsStr; +use std::path::Path; +use std::sync::LazyLock; + +use eframe::egui::Color32; +use syntect::easy::HighlightLines; +use syntect::highlighting::{Theme, ThemeSet}; +use syntect::parsing::{SyntaxReference, SyntaxSet}; +use syntect::util::LinesWithEndings; + +use crate::theme; + +/// The grammars, read the first time code is coloured. +static SYNTAXES: LazyLock = LazyLock::new(SyntaxSet::load_defaults_newlines); + +static THEME: LazyLock = + LazyLock::new(|| ThemeSet::load_defaults().themes.remove(theme::CODE).expect("one of syntect's own themes")); + +/// Code larger than this keeps the colour of plain text: colouring takes some 50 µs a line. +const LARGEST: usize = 512 << 10; + +/// A line of code, with its colours. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Line { + /// The text, without the line ending. + pub text: String, + /// Where in the text each colour starts; `None` is the colour of plain text. + pub colours: Vec<(usize, Option)>, +} + +/// The lines of `code`, the whole of a file at `path`, with their colours. A line takes its colour +/// from the lines before it, as one in a comment over several lines does, so this goes through +/// the file from the start. Nothing when the language is not known, or the code is not text or +/// too large. +pub fn colour(path: &str, code: &[u8]) -> Vec { + let code = std::str::from_utf8(code).ok().filter(|code| code.len() <= LARGEST); + let Some((code, syntax)) = code.and_then(|code| Some((code, syntax(path, code)?))) else { return Vec::new() }; + let plain = THEME.settings.foreground; + let mut highlighter = HighlightLines::new(syntax, &THEME); + LinesWithEndings::from(code) + .map_while(|line| { + let pieces = highlighter.highlight_line(line, &SYNTAXES).ok()?; + let text = line.strip_suffix('\n').unwrap_or(line).trim_end_matches('\r'); + let mut colours = Vec::new(); + let mut at = 0; + for (style, piece) in pieces { + let colour = Some(style.foreground).filter(|&colour| Some(colour) != plain); + let colour = colour.map(|colour| Color32::from_rgb(colour.r, colour.g, colour.b)); + if at < text.len() && colours.last().is_none_or(|&(_, last)| last != colour) { + colours.push((at, colour)); + } + at += piece.len(); + } + Some(Line { text: text.to_owned(), colours }) + }) + .collect() +} + +/// The grammar for a file at `path` with `code` in it: by its name, its extension, or a first line +/// like `#!/bin/sh`. +fn syntax(path: &str, code: &str) -> Option<&'static SyntaxReference> { + let path = Path::new(path); + let by = |part: Option<&OsStr>| SYNTAXES.find_syntax_by_extension(part?.to_str()?); + by(path.file_name()) + .or_else(|| by(path.extension())) + .or_else(|| SYNTAXES.find_syntax_by_first_line(code.lines().next()?)) + .filter(|syntax| syntax.name != SYNTAXES.find_syntax_plain_text().name) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The colour `line` has at `text` in it. + fn at(line: &Line, text: &str) -> Option { + let start = line.text.find(text).expect("the text is in the line"); + line.colours.iter().rev().find(|&&(at, _)| at <= start).and_then(|&(_, colour)| colour) + } + + #[test] + fn code_takes_the_colours_of_its_language() { + let lines = colour("src/main.rs", b"fn main() {\n let greeting = \"hello\"; // a comment\n}\n"); + assert_eq!(lines.len(), 3); + assert_eq!(lines[1].text, " let greeting = \"hello\"; // a comment"); + let [keyword, string, comment] = ["let", "hello", "a comment"].map(|text| at(&lines[1], text)); + assert!(keyword.is_some() && string.is_some() && comment.is_some()); + assert!(keyword != string && string != comment && comment != keyword); + assert_eq!(at(&lines[1], "greeting"), None, "a name has the colour of plain text"); + assert_eq!(at(&lines[0], "fn"), keyword); + } + + #[test] + fn a_line_takes_its_colour_from_the_lines_before_it() { + let lines = colour("a.c", b"/* a comment\nover two lines */\nint x;\r\n"); + assert_eq!(at(&lines[1], "over"), at(&lines[0], "a comment")); + assert_ne!(at(&lines[2], "int"), at(&lines[0], "a comment")); + assert_eq!(lines[2].text, "int x;"); + } + + #[test] + fn a_file_without_an_extension_is_known_by_its_name_or_first_line() { + assert_ne!(colour("Makefile", b"all:\n\tcc main.c\n"), []); + assert_ne!(colour("bin/run", b"#!/bin/sh\necho hello\n"), []); + } + + #[test] + fn text_unknown_code_and_large_files_stay_plain() { + assert_eq!(colour("notes.txt", b"fn main() {}\n"), []); + assert_eq!(colour("data.unknown", b"fn main() {}\n"), []); + assert_eq!(colour("main.rs", b"fn main() { \xff }\n"), []); + assert_eq!(colour("main.rs", "fn main() {}\n".repeat(50_000).as_bytes()), []); + } +} diff --git a/crates/app/src/tests.rs b/crates/app/src/tests.rs index 7d49b33..eeeea96 100644 --- a/crates/app/src/tests.rs +++ b/crates/app/src/tests.rs @@ -432,14 +432,14 @@ fn pictures_painted(harness: &Harness<'_, App>) -> Vec { pictures.map(|shape| shape.visual_bounding_rect().size()).collect() } -/// Opens the diff of `path` in the details and waits for its pictures. -fn open_pictures(harness: &mut Harness<'_, App>, path: &str) { +/// Opens the diff of `path` in the details and waits for its old and new version. +fn open_versions(harness: &mut Harness<'_, App>, path: &str) { harness.get_by_label(path).click(); let read = |h: &Harness<'_, App>| { let file = h.state().workspace().unwrap().open_file.as_ref(); file.is_some_and(|file| file.source.path() == path && file.reading.is_none()) }; - wait_until(harness, "the pictures", read); + wait_until(harness, "the versions", read); settle(harness); } @@ -456,7 +456,7 @@ fn a_picture_shows_its_old_and_its_new_version_side_by_side() { harness.get_by_label("Uncommitted changes").click(); settle(&mut harness); - open_pictures(&mut harness, "logo.png"); + open_versions(&mut harness, "logo.png"); harness.get_by_label(&format!("Old · 3 × 2 · {} bytes", old.len())); harness.get_by_label(&format!("New · 40 × 30 · {} bytes", new.len())); let sizes = pictures_painted(&harness); @@ -467,7 +467,7 @@ fn a_picture_shows_its_old_and_its_new_version_side_by_side() { fs::write(git.dir().join("logo.png"), png(5, 5)).unwrap(); wait_until(&mut harness, "the new picture", |h| h.query_by_label_contains("New · 5 × 5").is_some()); - open_pictures(&mut harness, "broken.png"); + open_versions(&mut harness, "broken.png"); harness.get_by_label("Old · none"); harness.get_by_label_contains("New · cannot be shown: "); @@ -476,12 +476,56 @@ fn a_picture_shows_its_old_and_its_new_version_side_by_side() { settle(&mut harness); harness.get_by_role_and_label(Role::Button, "Logo").click(); settle(&mut harness); - open_pictures(&mut harness, "logo.png"); + open_versions(&mut harness, "logo.png"); harness.get_by_label("Old · none"); harness.get_by_label(&format!("New · 3 × 2 · {} bytes", old.len())); assert_eq!(pictures_painted(&harness).len(), 1); } +/// The colours of the text on screen that reads `text`. +fn coloured(harness: &Harness<'_, App>, text: &str) -> Vec { + let jobs = harness.output().shapes.iter().filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some(&text.galley.job), + _ => None, + }); + jobs.flat_map(|job| { + let pieces = job.sections.iter().filter(|s| job.text[s.byte_range.start.0..s.byte_range.end.0] == *text); + pieces.map(|section| section.format.color) + }) + .collect() +} + +#[test] +fn code_in_a_diff_has_the_colours_of_its_language() { + let (_dir, git) = repo(); + let code = "/*\n * one\n * two\n * three\n * four\n */\nfn main() {}\n"; + fs::write(git.dir().join("main.rs"), code).unwrap(); + git.apply(&Op::Stage(vec!["main.rs".into()])).unwrap(); + git.apply(&Op::Commit { message: "Main".into(), amend: false }).unwrap(); + fs::write(git.dir().join("main.rs"), code.replace("{}", "{ greet(); }")).unwrap(); + let mut harness = app(Some(git.dir())); + harness.get_by_label("Uncommitted changes").click(); + settle(&mut harness); + open_versions(&mut harness, "main.rs"); + + // The hunk starts in a comment that starts before it, and it still reads as one. + let plain = harness.ctx.style_of(egui::Theme::Dark).visuals.text_color(); + let [comment] = coloured(&harness, " * three")[..] else { panic!("no line of the comment") }; + let [keyword, again] = coloured(&harness, "fn")[..] else { panic!("no old and new line") }; + assert!(comment != plain && keyword != plain && keyword != comment && again == keyword); + assert!(painted_on(&harness, theme::ADDED_WORD).concat().contains("greet"), "the words still stand out"); + + // A submodule is no code, and its diff shows where it points. + let head = git.run(&["rev-parse", "HEAD"]).unwrap(); + fs::create_dir(git.dir().join("sub")).unwrap(); + git.run(&["update-index", "--add", "--cacheinfo", &format!("160000,{},sub", head.trim())]).unwrap(); + harness.get_by_label("Refresh").click(); + settle(&mut harness); + open_versions(&mut harness, "sub"); + assert_eq!(painted_at(&harness, "Subproject commit").len(), 1); + assert_eq!(harness.state().workspace().unwrap().error, None); +} + #[test] fn sizes_read_the_way_people_say_them() { assert_eq!(crate::diff::bytes(1023), "1023 bytes"); diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rs index 6e6761c..fc6451e 100644 --- a/crates/app/src/theme.rs +++ b/crates/app/src/theme.rs @@ -30,6 +30,8 @@ pub const REMOVED_WORD: Color32 = Color32::from_rgb(0x74, 0x30, 0x39); pub const CONFLICT: Color32 = Color32::from_rgb(0x4a, 0x38, 0x1c); /// The background of a line picked for staging. pub const PICKED: Color32 = Color32::from_rgb(0x2b, 0x4a, 0x7a); +/// The colours of code: one of syntect's own themes, made for a dark background. +pub const CODE: &str = "base16-ocean.dark"; /// Text for errors. pub const ERROR: Color32 = Color32::from_rgb(0xf8, 0x71, 0x71); diff --git a/deny.toml b/deny.toml index fe1342f..fe817be 100644 --- a/deny.toml +++ b/deny.toml @@ -2,6 +2,11 @@ [advisories] yanked = "deny" +ignore = [ + # Informational, no flaw: bincode's authors stopped and call 1.3.3 complete. syntect reads its + # built-in grammars with it. + { id = "RUSTSEC-2025-0141", reason = "bincode 1.3.3 is complete; syntect reads its grammars with it" }, +] [licenses] allow = [