diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1815f60..b0b56ff 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,7 +50,7 @@ There are two crates. - `repo.rs` reads the history, refs and commits with gitoxide, in-process, because the graph needs millions of lookups, and what is under way: a merge, rebase, cherry-pick or revert that stopped. It also searches the history, a range of rows at a time, so the app can search a little each - frame. + frame, and reads the old and the new version of a file a diff is about, to show a picture. - `graph.rs` orders commits (`git log --date-order`) and lays out the lanes. It keeps a snapshot of the lanes every 256 rows, so it only ever builds the rows on screen. - `git.rs` runs the user's own `git` for everything else. Every change to a repository is one diff --git a/Cargo.lock b/Cargo.lock index 0e17e37..41770fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -468,6 +468,12 @@ dependencies = [ "bytemuck", ] +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "combine" version = "4.6.9" @@ -1154,6 +1160,16 @@ dependencies = [ "rand_core", ] +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + [[package]] name = "gitcraft" version = "0.20.0" @@ -1161,6 +1177,7 @@ dependencies = [ "eframe", "egui_kittest", "gitcraft-core", + "image", "rfd", "tempfile", ] @@ -2090,10 +2107,25 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "gif", + "image-webp", "moxcms", "num-traits", "png", "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error 2.0.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 6aef6ae..879f7aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ thiserror = "2" eframe = { version = "0.37", default-features = false, features = ["default_fonts", "glow", "wayland", "x11", "persistence"] } egui_kittest = "0.37" rfd = "0.18" +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "ico"] } tempfile = "3" proptest = "1" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support"] } diff --git a/README.md b/README.md index 27b9156..287e62d 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,9 @@ GitCraft is young. This is what it does today; [ROADMAP.md](ROADMAP.md) has what - **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 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. + 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 + their size in pixels and bytes. - **File history**: right-click a file, in a commit or in your changes, for every commit that changed it, newest first, also from before it was renamed. Pick one to see its diff of the file, with the commit beside it. Following a file through a large history happens in the background. diff --git a/ROADMAP.md b/ROADMAP.md index d5b741f..dea36ff 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -49,10 +49,11 @@ drive it the way a user does, and keeps every benchmark as fast as before. - [x] Blame: who last changed each line of a file, and in which commit - [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 ## Next -1. **Better diffs, part 3**: syntax colouring, images. +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 diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml index e38d37d..73152d5 100644 --- a/crates/app/Cargo.toml +++ b/crates/app/Cargo.toml @@ -11,6 +11,7 @@ repository.workspace = true gitcraft-core.workspace = true eframe.workspace = true rfd.workspace = true +image.workspace = true [dev-dependencies] egui_kittest.workspace = true diff --git a/crates/app/src/app.rs b/crates/app/src/app.rs index 7062593..43a7520 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -190,6 +190,63 @@ 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]>, +} + +/// A version of a picture, or why it does not show; `None` when the version does not have the file. +pub type Version = Option>; + +/// A version of a picture, ready to show. +pub struct Picture { + /// What it shows, made smaller when it is too large for one texture. + pub texture: egui::TextureHandle, + /// Its width and height in pixels. + pub size: [u32; 2], + /// How many bytes it takes. + pub bytes: usize, +} + +impl std::fmt::Debug for Picture { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let Self { texture, size, bytes } = self; + f.debug_struct("Picture").field("texture", &texture.id()).field("size", size).field("bytes", bytes).finish() + } +} + +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); + 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) { + let format = image::ImageFormat::from_path(self.source.path()); + if !self.diff.binary || !format.is_ok_and(|format| format.reading_enabled()) { + 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)))) + })); + } +} + +/// Decodes a version of a picture into a texture. +fn picture(ctx: &egui::Context, name: &str, bytes: &[u8]) -> Result { + let image = image::load_from_memory(bytes).map_err(|error| error.to_string())?; + let size = [image.width(), image.height()]; + let largest = u32::try_from(ctx.input(|i| i.max_texture_side)).unwrap_or(u32::MAX); + let image = if size[0].max(size[1]) > largest { image.thumbnail(largest, largest) } else { image }; + let pixels = image.into_rgba8(); + let image = egui::ColorImage::from_rgba_unmultiplied([pixels.width() as usize, pixels.height() as usize], &pixels); + Ok(Picture { texture: ctx.load_texture(name, image, egui::TextureOptions::LINEAR), size, bytes: bytes.len() }) } /// A conflicted file being resolved in the centre, conflict by conflict. @@ -570,7 +627,7 @@ impl Workspace { Action::Next(down) => self.reveal_row(ctx, self.search.next(self.selected_commit(), down)), Action::Open(source) => { (self.history, self.blame) = (None, None); - self.open(source); + self.open(ctx, source); } Action::History { at, path } => { self.close_centre(); @@ -663,11 +720,11 @@ impl Workspace { } /// Shows the diff of a file in the centre. - fn open(&mut self, source: Source) { + fn open(&mut self, ctx: &egui::Context, source: Source) { match diff::read(&self.repo.git, &source) { Ok(diff) => { (self.merge, self.plan) = (None, None); - self.open_file = Some(OpenFile { source, diff, lines: BTreeSet::new() }); + self.open_file = Some(OpenFile::new(ctx, &self.repo, source, diff)); } Err(error) => self.error = Some(error.to_string()), } @@ -679,12 +736,12 @@ impl Workspace { let Some(history) = &self.history else { return }; let (id, source) = (history.commits[row].0, history.source(row)); self.apply(ctx, Action::Reveal(Selection::Commit(id))); - self.open(source); + self.open(ctx, source); } - /// Takes in the history or the blame of the file in the centre once it is 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. + /// Takes in the history, the blame or the pictures 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) { if let Some(history) = &mut self.history && let Some(read) = take(&mut history.reading) @@ -705,6 +762,14 @@ impl Workspace { Err(error) => (self.blame, self.error) = (None, Some(error)), } } + if let Some(file) = &mut self.open_file + && let Some(read) = take(&mut file.reading) + { + match read { + Ok(pictures) => file.pictures = pictures, + Err(error) => self.error = Some(error), + } + } } /// Puts together an interactive rebase onto `onto`, in the centre. @@ -919,7 +984,10 @@ impl Workspace { // The picked lines stay picked as long as the diff stays the same. match diff::read(&self.repo.git, &file.source) { Ok(diff) if diff == file.diff => {} - Ok(diff) => (file.diff, file.lines) = (diff, BTreeSet::new()), + Ok(diff) => { + (file.diff, file.lines) = (diff, BTreeSet::new()); + file.read_pictures(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 02c4370..6555f2c 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. +//! 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}; +use crate::app::{Action, Confirm, OpenFile, Picture}; use crate::theme; const LINE: f32 = 18.0; @@ -108,7 +108,7 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec }); ui.separator(); if file.diff.binary { - ui.weak("Binary file"); + pictures(ui, file); return; } if file.diff.hunks.is_empty() { @@ -176,6 +176,43 @@ 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"); + } + return; + } + ui.columns(2, |columns| { + for ((ui, version), name) in columns.iter_mut().zip(&file.pictures).zip(["Old", "New"]) { + ui.weak(match version { + None => format!("{name} · none"), + Some(Err(error)) => format!("{name} · cannot be shown: {error}"), + Some(Ok(Picture { size: [width, height], bytes: n, .. })) => { + format!("{name} · {width} × {height} · {}", bytes(*n)) + } + }); + if let Some(Ok(picture)) = version { + let image = egui::Image::new(&picture.texture).fit_to_original_size(1.0); + egui::Frame::canvas(ui.style()).show(ui, |ui| ui.add(image.max_size(ui.available_size()))); + } + } + }); +} + +/// A number of bytes, as people read it. +pub fn bytes(n: usize) -> String { + let tenths = |unit: usize| format!("{}.{}", n / unit, n % unit * 10 / unit); + match n { + ..1024 => format!("{n} bytes"), + 1024..1_048_576 => format!("{} KB", tenths(1024)), + _ => format!("{} MB", tenths(1_048_576)), + } +} + /// Draws line `l` of hunk `h` in `rect`, after its numbers in the old and the new version, or /// side by side only the one of its `side` (0 is old, 1 is new). A click picks or unpicks a /// changed line for staging. diff --git a/crates/app/src/tests.rs b/crates/app/src/tests.rs index fe0912a..7d49b33 100644 --- a/crates/app/src/tests.rs +++ b/crates/app/src/tests.rs @@ -417,6 +417,78 @@ fn a_diff_side_by_side_puts_old_and_new_next_to_each_other_to_stage_from() { assert_eq!(painted_at(&harness, " keep").len(), 1); } +/// A PNG of `width` by `height` pixels. +fn png(width: u32, height: u32) -> Vec { + let mut png = std::io::Cursor::new(Vec::new()); + let image = image::RgbaImage::from_pixel(width, height, image::Rgba([200, 40, 40, 255])); + image.write_to(&mut png, image::ImageFormat::Png).unwrap(); + png.into_inner() +} + +/// The sizes of the pictures on screen, left to right. +fn pictures_painted(harness: &Harness<'_, App>) -> Vec { + let shapes = harness.output().shapes.iter().map(|clipped| &clipped.shape); + let pictures = shapes.filter(|shape| shape.texture_id() != egui::TextureId::default()); + 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) { + 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); + settle(harness); +} + +#[test] +fn a_picture_shows_its_old_and_its_new_version_side_by_side() { + let (_dir, git) = repo(); + let (old, new) = (png(3, 2), png(40, 30)); + fs::write(git.dir().join("logo.png"), &old).unwrap(); + git.apply(&Op::Stage(vec!["logo.png".into()])).unwrap(); + git.apply(&Op::Commit { message: "Logo".into(), amend: false }).unwrap(); + fs::write(git.dir().join("logo.png"), &new).unwrap(); + fs::write(git.dir().join("broken.png"), [0, 1, 2]).unwrap(); + let mut harness = app(Some(git.dir())); + harness.get_by_label("Uncommitted changes").click(); + settle(&mut harness); + + open_pictures(&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); + assert_eq!(sizes.len(), 2, "{sizes:?}"); + assert!(same(sizes[0].x, 3.0) && same(sizes[0].y, 2.0) && same(sizes[1].x, 40.0) && same(sizes[1].y, 30.0)); + + // A change outside shows at once. + 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"); + harness.get_by_label("Old · none"); + harness.get_by_label_contains("New · cannot be shown: "); + + // A commit that added it has nothing before. + harness.get_by_label("Close").click(); + settle(&mut harness); + harness.get_by_role_and_label(Role::Button, "Logo").click(); + settle(&mut harness); + open_pictures(&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); +} + +#[test] +fn sizes_read_the_way_people_say_them() { + assert_eq!(crate::diff::bytes(1023), "1023 bytes"); + assert_eq!(crate::diff::bytes(1536), "1.5 KB"); + assert_eq!(crate::diff::bytes(3 << 20), "3.0 MB"); +} + #[test] fn discard_single_lines_and_hunks() { let (_dir, git) = repo(); diff --git a/crates/core/src/repo.rs b/crates/core/src/repo.rs index 94e8b84..50397f5 100644 --- a/crates/core/src/repo.rs +++ b/crates/core/src/repo.rs @@ -9,6 +9,7 @@ use gix::refs::Category; use gix::revision::walk::Sorting; use gix::traverse::commit::simple::CommitTimeOrder; +use crate::diff::Source; use crate::git::Git; use crate::graph::{Graph, Parents, date_order}; use crate::{Error, Result}; @@ -217,6 +218,48 @@ impl Repo { Ok(found) } + /// The old and the new version of the file a diff is about, as stored, or `None` for a version + /// without it. The old version of a commit's file is the one in its first parent. + pub fn versions(&self, source: &Source) -> Result<[Option>; 2]> { + let worktree = |path: &str| match std::fs::read(self.git.dir().join(path)) { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + read => read.map(Some).map_err(|source| Error::File { path: path.to_owned(), source }), + }; + Ok(match source { + Source::Unstaged(path) => [self.indexed(path)?, worktree(path)?], + Source::Staged(path) => { + let head = self.gix.head().map_err(Error::repository)?.try_peel_to_id().map_err(Error::repository)?; + [self.stored(head.map(gix::Id::detach), path)?, self.indexed(path)?] + } + Source::Untracked(path) => [None, worktree(path)?], + Source::Commit { commit, path, from } => { + let commit = ObjectId::from_hex(commit.as_bytes()).map_err(Error::repository)?; + let parent = self.gix.find_commit(commit).map_err(Error::repository)?.parent_ids().next(); + [ + self.stored(parent.map(gix::Id::detach), from.as_deref().unwrap_or(path))?, + self.stored(Some(commit), path)?, + ] + } + }) + } + + /// The file at `path` in `commit`, if there is a commit and it has the file. + fn stored(&self, commit: Option, path: &str) -> Result>> { + let Some(commit) = commit else { return Ok(None) }; + let tree = self.gix.find_commit(commit).map_err(Error::repository)?.tree().map_err(Error::repository)?; + self.blob(tree.lookup_entry_by_path(path).map_err(Error::repository)?.map(|entry| entry.object_id())) + } + + /// The file at `path` in the index, if it has it. + fn indexed(&self, path: &str) -> Result>> { + let index = self.gix.index_or_empty().map_err(Error::repository)?; + self.blob(index.entry_by_path(path.into()).map(|entry| entry.id)) + } + + fn blob(&self, id: Option) -> Result>> { + id.map(|id| self.gix.find_blob(id).map(|mut blob| blob.take_data()).map_err(Error::repository)).transpose() + } + /// Reads one commit. pub fn commit(&self, id: ObjectId) -> Result { let commit = self.gix.find_commit(id).map_err(Error::repository)?; diff --git a/crates/core/tests/repo.rs b/crates/core/tests/repo.rs index 3fa2960..6dffb33 100644 --- a/crates/core/tests/repo.rs +++ b/crates/core/tests/repo.rs @@ -279,6 +279,38 @@ fn the_diff_of_a_file_a_commit_renamed_shows_only_what_changed() { assert_eq!(changed, ["6"]); } +#[test] +fn each_diff_has_the_old_and_the_new_version_of_its_file() { + let (_dir, git) = repo(); + let repo = Repo::open(git.dir()).unwrap(); + let versions = |source| repo.versions(&source).unwrap().map(|v| v.map(|bytes| String::from_utf8(bytes).unwrap())); + write(&git, "a.png", "one"); + git.apply(&Op::Stage(vec!["a.png".into()])).unwrap(); + assert_eq!(versions(Source::Staged("a.png".into())), [None, Some("one".into())]); + let first = commit(&git, "a.png", "one", "One"); + git.run(&["mv", "a.png", "b.png"]).unwrap(); + let renamed = commit(&git, "b.png", "two", "Two"); + commit(&git, "c.png", "c", "Another"); + write(&git, "b.png", "three"); + git.apply(&Op::Stage(vec!["b.png".into()])).unwrap(); + write(&git, "b.png", "four"); + write(&git, "new.png", "new"); + fs::remove_file(git.dir().join("c.png")).unwrap(); + + let at = |commit: &str, path: &str, from: Option<&str>| Source::Commit { + commit: commit.into(), + path: path.into(), + from: from.map(Into::into), + }; + assert_eq!(versions(at(&first, "a.png", None)), [None, Some("one".into())]); + assert_eq!(versions(at(&renamed, "b.png", Some("a.png"))), [Some("one".into()), Some("two".into())]); + assert_eq!(versions(at(&renamed, "a.png", None)), [Some("one".into()), None]); + assert_eq!(versions(Source::Staged("b.png".into())), [Some("two".into()), Some("three".into())]); + assert_eq!(versions(Source::Unstaged("b.png".into())), [Some("three".into()), Some("four".into())]); + assert_eq!(versions(Source::Unstaged("c.png".into())), [Some("c".into()), None]); + assert_eq!(versions(Source::Untracked("new.png".into())), [None, Some("new".into())]); +} + #[test] fn the_history_of_a_file_follows_it_through_renames() { let (_dir, git) = repo();