Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 32 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions crates/app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
84 changes: 76 additions & 8 deletions crates/app/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Result<Picture, String>>;

/// 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<Picture, String> {
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.
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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()),
}
Expand All @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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()),
}
}
Expand Down
43 changes: 40 additions & 3 deletions crates/app/src/diff.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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;
Expand Down Expand Up @@ -108,7 +108,7 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec<Action>
});
ui.separator();
if file.diff.binary {
ui.weak("Binary file");
pictures(ui, file);
return;
}
if file.diff.hunks.is_empty() {
Expand Down Expand Up @@ -176,6 +176,43 @@ pub fn show(ui: &mut Ui, file: &OpenFile, alone: bool, actions: &mut Vec<Action>
});
}

/// 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.
Expand Down
72 changes: 72 additions & 0 deletions crates/app/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8> {
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<egui::Vec2> {
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();
Expand Down
Loading
Loading