From 834f39e8cfd3ac44c0b9f16c35bee99c6a30ce3a Mon Sep 17 00:00:00 2001 From: Lars Jansen Date: Mon, 23 Nov 2026 11:12:24 +0100 Subject: [PATCH] feat: add a light theme beside the dark one, or the one the system uses --- CONTRIBUTING.md | 2 +- README.md | 7 +- ROADMAP.md | 7 +- crates/app/src/app.rs | 18 +++-- crates/app/src/details.rs | 4 +- crates/app/src/diff.rs | 13 ++- crates/app/src/graph.rs | 28 ++++--- crates/app/src/history.rs | 2 +- crates/app/src/merge.rs | 13 +-- crates/app/src/settings.rs | 33 +++++--- crates/app/src/start.rs | 5 +- crates/app/src/syntax.rs | 41 +++++----- crates/app/src/tests.rs | 52 ++++++++++-- crates/app/src/theme.rs | 160 ++++++++++++++++++++++++------------- crates/app/src/ui.rs | 6 +- 15 files changed, 259 insertions(+), 132 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e4359a..2d98ce6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -91,7 +91,7 @@ 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 and how dates read. `settings.rs` has the settings, which egui keeps + `theme.rs` has the colours, for a dark and for a light background, and how dates read. `settings.rs` has the settings, which egui keeps in its memory and eframe saves between runs, and the window to change them in. `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. diff --git a/README.md b/README.md index c4f1731..03fcb40 100644 --- a/README.md +++ b/README.md @@ -106,9 +106,10 @@ GitCraft is young. This is what it does today; [ROADMAP.md](ROADMAP.md) has what Escape goes back to the graph. While you type in a field, the field keeps its keys, apart from Ctrl+Enter. - **Settings**: Settings, at the right of the tabs, or Ctrl+, (Cmd+, on a Mac). Zoom everything - larger or smaller (Ctrl+Plus, Ctrl+Minus and Ctrl+0 do that anywhere), show dates as how long - ago or as the date and the time, and have Pull rebase rather than merge. They hold for every - repository and stay for the next run. + larger or smaller (Ctrl+Plus, Ctrl+Minus and Ctrl+0 do that anywhere), pick the dark or the + light theme or the one your system uses, show dates as how long ago or as the date and the time, + and have Pull rebase rather than merge. They hold for every repository and stay for the next + run. - **Safe by default**: a hard reset, deleting a branch with commits no other branch or tag has, a force push, dropping a stash and removing a remote all ask first, saying what will be lost. diff --git a/ROADMAP.md b/ROADMAP.md index d60c5e8..c10427f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -58,13 +58,14 @@ drive it the way a user does, and keeps every benchmark as fast as before. create in the palette - [x] Settings, part 1: a settings window (also Ctrl+,) to zoom, to pick how dates read, and whether Pull merges or rebases; they last between runs +- [x] Settings, part 2: a light theme beside the dark one, or the one the system uses; the + graph, diffs, code and conflicts take colours made for it ## Next -1. **Settings, part 2**: a light theme beside the dark one, or the one the system uses. -2. **Graph polish**: resizable columns, compact lanes, author avatars (optional, never by default +1. **Graph polish**: resizable columns, compact lanes, author avatars (optional, never by default over the network). -3. **Packaging**: installers with the icon for Windows (MSI), macOS (.app in a .dmg) and Linux +2. **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/src/app.rs b/crates/app/src/app.rs index 3b08665..3a14dcc 100644 --- a/crates/app/src/app.rs +++ b/crates/app/src/app.rs @@ -217,8 +217,8 @@ pub enum Versions { None, /// A picture's. Pictures([Version; 2]), - /// The lines of code, with their colours; none in a language without colours. - Code([Vec; 2]), + /// The lines of code, with their colours in a theme; none in a language without colours. + Code(egui::Theme, [Vec; 2]), } /// A version of a picture, or why it does not show; `None` when the version does not have the file. @@ -258,15 +258,14 @@ impl OpenFile { if binary && !format.is_ok_and(|format| format.reading_enabled()) || !binary && link { return; } - let (repo, source, context) = (repo.clone(), self.source.clone(), ctx.clone()); + let (repo, source, context, theme) = (repo.clone(), self.source.clone(), ctx.clone(), ctx.theme()); self.reading = Some(read_in_background(ctx, move || { 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))), - ) + let colour = |code: Vec| syntax::colour(path, &code, theme); + Versions::Code(theme, versions.map(|version| version.map_or_else(Vec::new, colour))) }) })); } @@ -979,6 +978,13 @@ impl Workspace { /// Takes in the result of the background job, once it is there, and starts the next. pub fn poll(&mut self, ctx: &egui::Context) { self.take_reading(ctx); + // Code is coloured for one theme: in another, it is coloured again. + if let Some(file) = &mut self.open_file + && file.reading.is_none() + && matches!(file.versions, Versions::Code(theme, _) if theme != ctx.theme()) + { + file.read_versions(ctx, &self.repo); + } let Some(job) = &self.job else { return }; let (failed, snapshot, watch) = match job.outcome.try_recv() { Err(TryRecvError::Empty) => return, diff --git a/crates/app/src/details.rs b/crates/app/src/details.rs index 6242026..99c89c3 100644 --- a/crates/app/src/details.rs +++ b/crates/app/src/details.rs @@ -24,7 +24,7 @@ pub fn show(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { /// One changed file: its kind of change, its path, and `buttons` on the right, right to left. /// Returns the path. fn file(ui: &mut Ui, change: Change, path: &str, open: bool, buttons: impl FnOnce(&mut Ui)) -> Response { - let (letter, colour) = theme::change(change); + let (letter, colour) = theme::colours(ui.ctx().theme()).change(change); ui.horizontal(|ui| { ui.with_layout(Layout::right_to_left(egui::Align::Center), |ui| { buttons(ui); @@ -193,7 +193,7 @@ fn commit(ui: &mut Ui, ws: &mut Workspace, id: ObjectId, actions: &mut Vec commit.clone(), Err(error) => { - ui.colored_label(theme::ERROR, error.to_string()); + ui.colored_label(ui.visuals().error_fg_color, error.to_string()); return; } }; diff --git a/crates/app/src/diff.rs b/crates/app/src/diff.rs index 31b408e..3e021fb 100644 --- a/crates/app/src/diff.rs +++ b/crates/app/src/diff.rs @@ -257,13 +257,18 @@ fn line( let line = &hunk.lines[l]; let numbers = [line.old, line.new]; let numbers = side.map_or(&numbers[..], |side| &numbers[side..=side]); + let palette = theme::colours(ui.ctx().theme()); let (background, word, marker) = match line.kind { - LineKind::Added => (theme::ADDED, theme::ADDED_WORD, "+ "), - LineKind::Removed => (theme::REMOVED, theme::REMOVED_WORD, "- "), + LineKind::Added => (palette.added, palette.added_word, "+ "), + LineKind::Removed => (palette.removed, palette.removed_word, "- "), LineKind::Context | LineKind::NoNewline => (Color32::TRANSPARENT, Color32::TRANSPARENT, " "), }; let painter = ui.painter_at(rect); - painter.rect_filled(rect, 0.0, if file.lines.contains(&(h, l)) { theme::PICKED } else { background }); + painter.rect_filled( + rect, + 0.0, + if file.lines.contains(&(h, l)) { ui.visuals().selection.bg_fill } else { background }, + ); let at = |x: f32| rect.left_center() + Vec2::X * x; let mut x = 0.0; for n in numbers { @@ -280,7 +285,7 @@ fn line( 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] + 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[..]), diff --git a/crates/app/src/graph.rs b/crates/app/src/graph.rs index b5fca44..f48a18a 100644 --- a/crates/app/src/graph.rs +++ b/crates/app/src/graph.rs @@ -92,7 +92,7 @@ pub fn show(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { let head = history.head == Some(index); let merge = history.graph.parents(index).len() > 1; paint_row(&painter.with_clip_rect(graph), row, lane_x, merge, (head, head && wip == 1 && index == 0)); - let colour = theme::lane(row.lane); + let colour = theme::colours(ui.ctx().theme()).lane(row.lane); paint_labels(&painter, rect.with_max_x(rect.left() + labels_width), labels, colour, current.as_deref()); match ws.commits.get(&ws.repo, id) { Ok(commit) => { @@ -111,7 +111,7 @@ pub fn show(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { let date = Rect::from_x_y_ranges(rect.right() - date_width..=rect.right() - 8.0, rect.y_range()); put(ui, date, egui::RichText::new(dates.when(commit.time)).weak()); } - Err(error) => put(ui, text, egui::RichText::new(error.to_string()).color(theme::ERROR)), + Err(error) => put(ui, text, egui::RichText::new(error.to_string()).color(ui.visuals().error_fg_color)), } if response.clicked() { actions.push(Action::Select(Selection::Commit(id))); @@ -220,10 +220,11 @@ fn paint_row( ) { let rect = painter.clip_rect(); let (top, mid, bottom) = (rect.top(), rect.center().y, rect.bottom()); + let colours = theme::colours(painter.ctx().theme()); for edge in &row.edges { let (y0, y1, colour) = match edge.half { - Half::Top => (top, mid, theme::lane(edge.from)), - Half::Bottom => (mid, bottom, theme::lane(edge.to)), + Half::Top => (top, mid, colours.lane(edge.from)), + Half::Bottom => (mid, bottom, colours.lane(edge.to)), }; let (a, b) = (Pos2::new(lane_x(edge.from), y0), Pos2::new(lane_x(edge.to), y1)); let stroke = Stroke::new(2.0, colour); @@ -235,9 +236,9 @@ fn paint_row( } } let node = Pos2::new(lane_x(row.lane), mid); - painter.circle_filled(node, if merge { 4.0 } else { 6.0 }, theme::lane(row.lane)); + painter.circle_filled(node, if merge { 4.0 } else { 6.0 }, colours.lane(row.lane)); if head { - painter.circle_stroke(node, 9.0, Stroke::new(1.5, Color32::WHITE)); + painter.circle_stroke(node, 9.0, Stroke::new(1.5, strong(painter))); } if wip_above { dashed(painter, Pos2::new(node.x, top), node - Vec2::Y * 9.0); @@ -248,22 +249,27 @@ fn paint_row( fn paint_labels(painter: &Painter, rect: Rect, labels: &[Ref], colour: Color32, current: Option<&str>) { let Some(first) = labels.iter().find(|l| Some(l.name.as_str()) == current).or(labels.first()) else { return }; let more = if labels.len() > 1 { format!(" +{}", labels.len() - 1) } else { String::new() }; - let font = FontId::proportional(12.0); - let galley = painter.layout_no_wrap(format!("{}{more}", first.name), font, Color32::WHITE); + let (font, text) = (FontId::proportional(12.0), strong(painter)); + let galley = painter.layout_no_wrap(format!("{}{more}", first.name), font, text); let size = galley.size() + Vec2::new(14.0, 6.0); let pill = Rect::from_min_size(Pos2::new(rect.left() + 6.0, rect.center().y - size.y / 2.0), size); let pill = pill.intersect(rect.shrink2(Vec2::new(4.0, 0.0))); match first.kind { RefKind::Local => painter.rect_filled(pill, 4.0, colour.gamma_multiply(0.55)), RefKind::Remote => painter.rect_stroke(pill, 4.0, Stroke::new(1.0, colour), egui::StrokeKind::Inside), - RefKind::Tag => painter.rect_filled(pill, 0.0, Color32::from_gray(70)), + RefKind::Tag => painter.rect_filled(pill, 0.0, theme::colours(painter.ctx().theme()).tag), }; if Some(first.name.as_str()) == current { - painter.rect_stroke(pill, 4.0, Stroke::new(1.5, Color32::WHITE), egui::StrokeKind::Outside); + painter.rect_stroke(pill, 4.0, Stroke::new(1.5, text), egui::StrokeKind::Outside); } let line = Pos2::new(pill.right(), rect.center().y); painter.line_segment([line, Pos2::new(rect.right(), line.y)], Stroke::new(1.0, colour.gamma_multiply(0.6))); - painter.with_clip_rect(pill).galley(pill.min + Vec2::new(7.0, 3.0), galley, Color32::WHITE); + painter.with_clip_rect(pill).galley(pill.min + Vec2::new(7.0, 3.0), galley, text); +} + +/// The colour of what stands out most, as the commit checked out: white on dark, black on light. +fn strong(painter: &Painter) -> Color32 { + painter.ctx().global_style().visuals.strong_text_color() } /// The right-click menu of a commit: what can be done with each branch and tag on it, then with diff --git a/crates/app/src/history.rs b/crates/app/src/history.rs index b56f5ab..c289386 100644 --- a/crates/app/src/history.rs +++ b/crates/app/src/history.rs @@ -48,7 +48,7 @@ pub fn show(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { let commit = match commits.get(repo, *id) { Ok(commit) => commit, Err(error) => { - put(ui, column(80.0, 8.0), RichText::new(error.to_string()).color(theme::ERROR)); + put(ui, column(80.0, 8.0), RichText::new(error.to_string()).color(ui.visuals().error_fg_color)); continue; } }; diff --git a/crates/app/src/merge.rs b/crates/app/src/merge.rs index 10dc6d0..622fdd7 100644 --- a/crates/app/src/merge.rs +++ b/crates/app/src/merge.rs @@ -132,8 +132,9 @@ pub fn show(ui: &mut Ui, merge: &mut Merge, actions: &mut Vec) { columns[1].strong(format!("Theirs: {theirs}")); }); let to = std::mem::take(&mut merge.scroll).then_some(at); - let visuals = ui.visuals(); + let (visuals, colours) = (ui.visuals(), theme::colours(ui.ctx().theme())); let (text, current, other) = (visuals.text_color(), visuals.selection.bg_fill, visuals.extreme_bg_color); + let error = visuals.error_fg_color; ui.spacing_mut().item_spacing.y = 0.0; let half = (ui.available_height() - 2.0 * LINE) / 2.0; list(ui, "sides", &rows(merge, false), half, to, |ui, rect, response, row| { @@ -157,9 +158,9 @@ pub fn show(ui: &mut Ui, merge: &mut Merge, actions: &mut Vec) { Row::Lines(n, lines) => { for (side, (cell, line)) in cells.into_iter().zip(lines).enumerate() { let background = match merge.picks[n] { - None => theme::CONFLICT, - Some(pick) if pick.sides().contains(&side) => theme::ADDED, - Some(_) => theme::REMOVED, + None => colours.conflict, + Some(pick) if pick.sides().contains(&side) => colours.added, + Some(_) => colours.removed, }; if let Some(line) = line { paint(ui, cell, line, text, background); @@ -173,9 +174,9 @@ pub fn show(ui: &mut Ui, merge: &mut Merge, actions: &mut Vec) { ui.add_space(4.0); list(ui, "result", &rows(merge, true), f32::INFINITY, to, |ui, rect, response, row| match row { Row::Same(line) => paint(ui, rect, line, text, Color32::TRANSPARENT), - Row::Lines(_, [line, _]) => paint(ui, rect, line.unwrap_or_default(), text, theme::ADDED), + Row::Lines(_, [line, _]) => paint(ui, rect, line.unwrap_or_default(), text, colours.added), Row::Conflict(n) => { - paint(ui, rect, &format!("Conflict {}: pick a side", n + 1), theme::ERROR, theme::CONFLICT); + paint(ui, rect, &format!("Conflict {}: pick a side", n + 1), error, colours.conflict); if response.clicked() { actions.push(Action::GoTo(n)); } diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index ff79aa9..5c2a797 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -7,7 +7,7 @@ use eframe::egui::gui_zoom::{ self, kb_shortcuts::{ZOOM_IN, ZOOM_OUT, ZOOM_RESET}, }; -use eframe::egui::{self, Button, Id, KeyboardShortcut, Ui}; +use eframe::egui::{self, Button, Id, KeyboardShortcut, ThemePreference, Ui}; /// A setting that is on or off. #[derive(Debug, Clone, Copy)] @@ -33,15 +33,9 @@ impl Switch { /// A choice between what it does off and on. fn choice(self, ui: &mut Ui, what: &str, [off, on]: [&str; 2]) { - ui.horizontal(|ui| { - label(ui, what); - let mut value = self.on(ui.ctx()); - let changed = - ui.radio_value(&mut value, false, off).changed() | ui.radio_value(&mut value, true, on).changed(); - if changed { - self.set(ui.ctx(), value); - } - }); + if let Some(value) = choice(ui, what, self.on(ui.ctx()), &[(false, off), (true, on)]) { + self.set(ui.ctx(), value); + } } } @@ -57,6 +51,11 @@ pub fn show(ctx: &egui::Context) -> bool { zoom(ui, "+", "Zoom in", ZOOM_IN, gui_zoom::zoom_in); zoom(ui, "Reset", "Reset the zoom", ZOOM_RESET, |ctx| ctx.set_zoom_factor(1.0)); }); + let themes = + [(ThemePreference::Dark, "Dark"), (ThemePreference::Light, "Light"), (ThemePreference::System, "System")]; + if let Some(theme) = choice(ui, "Theme", ctx.options(|o| o.theme_preference), &themes) { + ctx.set_theme(theme); + } FULL_DATES.choice(ui, "Dates", ["How long ago", "Date and time"]); REBASE.choice(ui, "Pull", ["Merge", "Rebase"]); close = ui.button("Close").clicked(); @@ -64,6 +63,20 @@ pub fn show(ctx: &egui::Context) -> bool { !(close || response.should_close()) } +/// A row to pick one of `picks` for what it is about, with `value` picked; the new pick, once the +/// user makes one. +fn choice(ui: &mut Ui, what: &str, mut value: T, picks: &[(T, &str)]) -> Option { + ui.horizontal(|ui| { + label(ui, what); + let mut changed = false; + for &(pick, name) in picks { + changed |= ui.radio_value(&mut value, pick, name).changed(); + } + changed.then_some(value) + }) + .inner +} + /// What a row of the settings is about, in a column of its own. fn label(ui: &mut Ui, text: &str) { let width = ui.label(text).rect.width(); diff --git a/crates/app/src/start.rs b/crates/app/src/start.rs index d3b8e8b..16189ce 100644 --- a/crates/app/src/start.rs +++ b/crates/app/src/start.rs @@ -7,7 +7,6 @@ use eframe::egui::{self, Button, Key, ProgressBar, RichText, TextEdit, Ui}; use gitcraft_core::git::{self, Git}; use crate::app::Action; -use crate::theme; use crate::ui::pick_folder; /// The width of the dialog's fields. @@ -67,7 +66,7 @@ impl Start { } } if let Some(error) = &self.error { - ui.colored_label(theme::ERROR, error); + ui.colored_label(ui.visuals().error_fg_color, error); } if !recent.is_empty() { ui.add_space(24.0); @@ -210,7 +209,7 @@ impl Dialog { (None, None) => {} } if let Some(error) = &self.error { - ui.colored_label(theme::ERROR, error); + ui.colored_label(ui.visuals().error_fg_color, error); } let idle = !self.busy(); let enter = ui.input(|i| i.key_pressed(Key::Enter)); diff --git a/crates/app/src/syntax.rs b/crates/app/src/syntax.rs index a04b572..c69d55b 100644 --- a/crates/app/src/syntax.rs +++ b/crates/app/src/syntax.rs @@ -4,9 +4,9 @@ use std::ffi::OsStr; use std::path::Path; use std::sync::LazyLock; -use eframe::egui::Color32; +use eframe::egui::{Color32, Theme}; use syntect::easy::HighlightLines; -use syntect::highlighting::{Theme, ThemeSet}; +use syntect::highlighting::ThemeSet; use syntect::parsing::{SyntaxReference, SyntaxSet}; use syntect::util::LinesWithEndings; @@ -15,8 +15,8 @@ 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")); +/// syntect's own colours for code, for a dark and for a light background among them. +static THEMES: LazyLock = LazyLock::new(ThemeSet::load_defaults); /// Code larger than this keeps the colour of plain text: colouring takes some 50 µs a line. const LARGEST: usize = 512 << 10; @@ -30,15 +30,16 @@ pub struct Line { 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 { +/// The lines of `code`, the whole of a file at `path`, with their colours in `theme`. 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], theme: Theme) -> 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); + let theme = &THEMES.themes[theme::colours(theme).code]; + 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()?; @@ -81,7 +82,7 @@ mod tests { #[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"); + let lines = colour("src/main.rs", b"fn main() {\n let greeting = \"hello\"; // a comment\n}\n", Theme::Dark); 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)); @@ -89,11 +90,13 @@ mod tests { 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); + let light = colour("src/main.rs", b"fn main() {}\n", Theme::Light); + assert!(at(&light[0], "fn").is_some_and(|light| Some(light) != keyword), "other colours on light"); } #[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"); + let lines = colour("a.c", b"/* a comment\nover two lines */\nint x;\r\n", Theme::Dark); 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;"); @@ -101,15 +104,15 @@ mod tests { #[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"), []); + assert_ne!(colour("Makefile", b"all:\n\tcc main.c\n", Theme::Dark), []); + assert_ne!(colour("bin/run", b"#!/bin/sh\necho hello\n", Theme::Dark), []); } #[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()), []); + assert_eq!(colour("notes.txt", b"fn main() {}\n", Theme::Dark), []); + assert_eq!(colour("data.unknown", b"fn main() {}\n", Theme::Dark), []); + assert_eq!(colour("main.rs", b"fn main() { \xff }\n", Theme::Dark), []); + assert_eq!(colour("main.rs", "fn main() {}\n".repeat(50_000).as_bytes(), Theme::Dark), []); } } diff --git a/crates/app/src/tests.rs b/crates/app/src/tests.rs index 1085ddb..360c791 100644 --- a/crates/app/src/tests.rs +++ b/crates/app/src/tests.rs @@ -13,7 +13,7 @@ use gitcraft_core::diff::Source; use gitcraft_core::git::{Git, Op}; use tempfile::TempDir; -use crate::app::{Action, Selection}; +use crate::app::{Action, Selection, Versions}; use crate::commands; use crate::start::percent; use crate::theme; @@ -345,8 +345,8 @@ fn a_changed_line_marks_the_words_that_changed() { settle(&mut harness); // Only the word that changed stands out; a line rewritten as a whole has nothing to point at. - assert_eq!(painted_on(&harness, theme::REMOVED_WORD), ["count"]); - assert_eq!(painted_on(&harness, theme::ADDED_WORD), ["amount"]); + assert_eq!(painted_on(&harness, theme::DARK.removed_word), ["count"]); + assert_eq!(painted_on(&harness, theme::DARK.added_word), ["amount"]); } /// Where the lines on screen that hold `text` are painted, top to bottom. @@ -397,8 +397,8 @@ fn a_diff_side_by_side_puts_old_and_new_next_to_each_other_to_stage_from() { assert!(same(extra.x, new.x) && extra.y > new.y, "a line that pairs with none is on its own side"); let [left, right] = painted_at(&harness, " keep")[..] else { panic!("not on both sides") }; assert!(same(left.y, right.y) && same(left.x, old.x) && same(right.x, new.x)); - assert_eq!(painted_on(&harness, theme::REMOVED_WORD), ["count"]); - assert_eq!(painted_on(&harness, theme::ADDED_WORD), ["amount"]); + assert_eq!(painted_on(&harness, theme::DARK.removed_word), ["count"]); + assert_eq!(painted_on(&harness, theme::DARK.added_word), ["amount"]); // Either side's line can be picked. click_at(&mut harness, old); @@ -515,7 +515,7 @@ fn code_in_a_diff_has_the_colours_of_its_language() { 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"); + assert!(painted_on(&harness, theme::DARK.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(); @@ -1787,3 +1787,43 @@ fn the_settings_change_how_dates_read_what_pull_does_and_the_zoom() { let pull = commands::all(&harness.ctx, harness.state()).into_iter().find(|c| c.name == "Pull").unwrap(); assert_eq!(pull.action, Some(Action::Run(Op::Pull { rebase: false }))); } + +#[test] +fn a_light_theme_colours_diffs_and_code_for_a_light_background() { + let (_dir, git) = repo(); + fs::write(git.dir().join("main.rs"), "fn main() {}\n").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"), "fn main() { greet(); }\n").unwrap(); + let mut harness = app(Some(git.dir())); + harness.get_by_label("Uncommitted changes").click(); + settle(&mut harness); + open_versions(&mut harness, "main.rs"); + let dark = coloured(&harness, "fn"); + assert!(painted_on(&harness, theme::DARK.added_word).concat().contains("greet")); + + // In the light theme the diff and its code take the colours for a light background. + harness.get_by_label("Settings").click(); + settle(&mut harness); + harness.get_by_label("Light").click(); + harness.key_press(Key::Escape); + let coloured_again = |h: &Harness<'_, App>| { + let file = h.state().workspace().unwrap().open_file.as_ref().unwrap(); + file.reading.is_none() && matches!(file.versions, Versions::Code(egui::Theme::Light, _)) + }; + wait_until(&mut harness, "the code in light colours", coloured_again); + settle(&mut harness); + assert_eq!(harness.ctx.theme(), egui::Theme::Light); + let light = coloured(&harness, "fn"); + assert!(dark.len() == 2 && light.len() == 2 && light[0] != dark[0], "{dark:?} and {light:?}"); + assert!(painted_on(&harness, theme::LIGHT.added_word).concat().contains("greet")); + assert_eq!(painted_on(&harness, theme::DARK.added_word), Vec::::new()); + + // Or the one the system uses. + harness.get_by_label("Settings").click(); + settle(&mut harness); + harness.get_by_label("System").click(); + harness.key_press(Key::Escape); + settle(&mut harness); + assert_eq!(harness.ctx.options(|o| o.theme_preference), egui::ThemePreference::System); +} diff --git a/crates/app/src/theme.rs b/crates/app/src/theme.rs index 59e5034..d924c62 100644 --- a/crates/app/src/theme.rs +++ b/crates/app/src/theme.rs @@ -1,69 +1,120 @@ //! Colours, the look of the app, and how times read. -use eframe::egui::{self, Color32}; +use eframe::egui::{self, Color32, Theme}; use gitcraft_core::date; use gitcraft_core::status::Change; use crate::settings; -/// One colour per graph lane, repeating. -const LANES: [Color32; 10] = [ - Color32::from_rgb(0x38, 0xbd, 0xf8), - Color32::from_rgb(0xa7, 0x8b, 0xfa), - Color32::from_rgb(0xf4, 0x72, 0xb6), - Color32::from_rgb(0xfb, 0xbf, 0x24), - Color32::from_rgb(0x34, 0xd3, 0x99), - Color32::from_rgb(0xf8, 0x71, 0x71), - Color32::from_rgb(0x81, 0x8c, 0xf8), - Color32::from_rgb(0xa3, 0xe6, 0x35), - Color32::from_rgb(0x22, 0xd3, 0xee), - Color32::from_rgb(0xfb, 0x92, 0x3c), -]; - -/// The background of an added line. -pub const ADDED: Color32 = Color32::from_rgb(0x1d, 0x3b, 0x2c); -/// The background of a removed line. -pub const REMOVED: Color32 = Color32::from_rgb(0x45, 0x22, 0x27); -/// The background of the words that changed in an added line. -pub const ADDED_WORD: Color32 = Color32::from_rgb(0x2c, 0x63, 0x45); -/// The background of the words that changed in a removed line. -pub const REMOVED_WORD: Color32 = Color32::from_rgb(0x74, 0x30, 0x39); -/// The background of a conflict without a pick. -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); - -/// The colour of a lane. -pub fn lane(i: usize) -> Color32 { - LANES[i % LANES.len()] +/// The colours the app adds to egui's own, for a dark or a light background. +#[derive(Debug)] +pub struct Colours { + /// One per graph lane, repeating. + lanes: [Color32; 10], + /// The background of an added line. + pub added: Color32, + /// The background of a removed line. + pub removed: Color32, + /// The background of the words that changed in an added line. + pub added_word: Color32, + /// The background of the words that changed in a removed line. + pub removed_word: Color32, + /// The background of a conflict without a pick. + pub conflict: Color32, + /// The background of a tag in the graph. + pub tag: Color32, + /// The colours of code: one of syntect's own themes. + pub code: &'static str, } -/// The letter and colour that mark a kind of change. -pub fn change(change: Change) -> (&'static str, Color32) { - match change { - Change::Added => ("A", LANES[4]), - Change::Modified => ("M", LANES[3]), - Change::Deleted => ("D", LANES[5]), - Change::Renamed | Change::Copied => ("R", LANES[0]), - Change::TypeChanged => ("T", LANES[1]), - Change::Untracked => ("U", LANES[7]), - Change::Conflicted { .. } => ("C", LANES[9]), +/// The colours on a dark background. +pub const DARK: Colours = Colours { + lanes: [ + Color32::from_rgb(0x38, 0xbd, 0xf8), + Color32::from_rgb(0xa7, 0x8b, 0xfa), + Color32::from_rgb(0xf4, 0x72, 0xb6), + Color32::from_rgb(0xfb, 0xbf, 0x24), + Color32::from_rgb(0x34, 0xd3, 0x99), + Color32::from_rgb(0xf8, 0x71, 0x71), + Color32::from_rgb(0x81, 0x8c, 0xf8), + Color32::from_rgb(0xa3, 0xe6, 0x35), + Color32::from_rgb(0x22, 0xd3, 0xee), + Color32::from_rgb(0xfb, 0x92, 0x3c), + ], + added: Color32::from_rgb(0x1d, 0x3b, 0x2c), + removed: Color32::from_rgb(0x45, 0x22, 0x27), + added_word: Color32::from_rgb(0x2c, 0x63, 0x45), + removed_word: Color32::from_rgb(0x74, 0x30, 0x39), + conflict: Color32::from_rgb(0x4a, 0x38, 0x1c), + tag: Color32::from_gray(70), + code: "base16-ocean.dark", +}; + +/// The colours on a light background: the same, a shade darker for lines and text, and lighter +/// behind text. +pub const LIGHT: Colours = Colours { + lanes: [ + Color32::from_rgb(0x02, 0x84, 0xc7), + Color32::from_rgb(0x7c, 0x3a, 0xed), + Color32::from_rgb(0xdb, 0x27, 0x77), + Color32::from_rgb(0xd9, 0x77, 0x06), + Color32::from_rgb(0x05, 0x96, 0x69), + Color32::from_rgb(0xdc, 0x26, 0x26), + Color32::from_rgb(0x4f, 0x46, 0xe5), + Color32::from_rgb(0x65, 0xa3, 0x0d), + Color32::from_rgb(0x08, 0x91, 0xb2), + Color32::from_rgb(0xea, 0x58, 0x0c), + ], + added: Color32::from_rgb(0xdc, 0xfc, 0xe7), + removed: Color32::from_rgb(0xfe, 0xe2, 0xe2), + added_word: Color32::from_rgb(0x86, 0xef, 0xac), + removed_word: Color32::from_rgb(0xfc, 0xa5, 0xa5), + conflict: Color32::from_rgb(0xfe, 0xf3, 0xc7), + tag: Color32::from_gray(215), + code: "InspiredGitHub", +}; + +/// The colours for `theme`. +pub fn colours(theme: Theme) -> &'static Colours { + match theme { + Theme::Dark => &DARK, + Theme::Light => &LIGHT, } } -/// Sets up the dark look. +impl Colours { + /// The colour of a lane. + pub fn lane(&self, i: usize) -> Color32 { + self.lanes[i % self.lanes.len()] + } + + /// The letter and colour that mark a kind of change. + pub fn change(&self, change: Change) -> (&'static str, Color32) { + let (letter, lane) = match change { + Change::Added => ("A", 4), + Change::Modified => ("M", 3), + Change::Deleted => ("D", 5), + Change::Renamed | Change::Copied => ("R", 0), + Change::TypeChanged => ("T", 1), + Change::Untracked => ("U", 7), + Change::Conflicted { .. } => ("C", 9), + }; + (letter, self.lanes[lane]) + } +} + +/// Sets up the look, dark and light. Which one shows is egui's theme preference, which eframe saves +/// between runs: dark, light, or the one the system uses. pub fn apply(ctx: &egui::Context) { - ctx.set_theme(egui::Theme::Dark); - ctx.all_styles_mut(|style| { - style.visuals.panel_fill = Color32::from_rgb(0x1f, 0x22, 0x28); - style.visuals.extreme_bg_color = Color32::from_rgb(0x17, 0x19, 0x1e); - style.visuals.selection.bg_fill = Color32::from_rgb(0x2b, 0x4a, 0x7a); - style.spacing.button_padding = egui::vec2(8.0, 3.0); + ctx.all_styles_mut(|style| style.spacing.button_padding = egui::vec2(8.0, 3.0)); + ctx.style_mut_of(Theme::Dark, |style| { + let visuals = &mut style.visuals; + visuals.panel_fill = Color32::from_rgb(0x1f, 0x22, 0x28); + visuals.extreme_bg_color = Color32::from_rgb(0x17, 0x19, 0x1e); + visuals.selection.bg_fill = Color32::from_rgb(0x2b, 0x4a, 0x7a); + visuals.error_fg_color = Color32::from_rgb(0xf8, 0x71, 0x71); }); + ctx.style_mut_of(Theme::Light, |style| style.visuals.error_fg_color = Color32::from_rgb(0xdc, 0x26, 0x26)); } /// How the dates of commits read: how long ago, or the date and the time. @@ -150,7 +201,8 @@ mod tests { #[test] fn lanes_repeat_their_colours() { - assert_eq!(lane(1), lane(11)); - assert_ne!(lane(1), lane(2)); + assert_eq!(DARK.lane(1), DARK.lane(11)); + assert_ne!(DARK.lane(1), DARK.lane(2)); + assert_ne!(DARK.lane(1), LIGHT.lane(1)); } } diff --git a/crates/app/src/ui.rs b/crates/app/src/ui.rs index ccfa2ad..bdf0bdd 100644 --- a/crates/app/src/ui.rs +++ b/crates/app/src/ui.rs @@ -225,7 +225,7 @@ fn workspace(ui: &mut Ui, ws: &mut Workspace, actions: &mut Vec) { if ui.small_button("Dismiss").clicked() { ws.error = None; } - ui.colored_label(theme::ERROR, error); + ui.colored_label(ui.visuals().error_fg_color, error); }); }); } @@ -290,7 +290,7 @@ fn underway(ui: &mut Ui, ws: &Workspace, actions: &mut Vec) { ui.strong(format!("{} in progress", theme::capital(command))); ui.weak(&underway.message); if conflicts > 0 { - ui.colored_label(theme::ERROR, theme::count(conflicts, "conflicted file")); + ui.colored_label(ui.visuals().error_fg_color, theme::count(conflicts, "conflicted file")); } let go_on = ui.add_enabled(idle && conflicts == 0, Button::new("Continue")); if go_on.on_disabled_hover_text("Resolve every conflict first").clicked() { @@ -376,7 +376,7 @@ fn confirm(ctx: &egui::Context, ws: &mut Workspace, actions: &mut Vec) { ui.strong(&confirm.question); ui.label("This cannot be undone."); ui.horizontal(|ui| { - if ui.button(egui::RichText::new(confirm.verb).color(theme::ERROR)).clicked() { + if ui.button(egui::RichText::new(confirm.verb).color(ui.visuals().error_fg_color)).clicked() { actions.push(Action::Run(confirm.op.clone())); done = true; }