From 0d18510a1f1c9b16dc114e1cd90c388a4069ee1c Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Thu, 19 Nov 2026 21:13:49 -0500 Subject: [PATCH] feat: draw on the terminal's own background --- CHANGELOG.md | 6 +++ docs/embedding.md | 14 +++++ src/app.rs | 27 +++++++++- src/engine.rs | 24 +++++++++ src/lib.rs | 4 +- src/render.rs | 2 + src/render/sidebar.rs | 9 +++- src/render/tests.rs | 123 ++++++++++++++++++++++++++++++++++++++++++ src/theme.rs | 36 +++++++++++++ tests/engine.rs | 42 +++++++++++++++ 10 files changed, 283 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30203e5..e1c5499 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,12 @@ All notable changes to `diffs-rs` are recorded here. The forked crates in has its own column at the right of every row, so rows stay aligned, and a folder shows a badge when every file under it has the same one. Hosts that never call it, and the `diffs` viewer, look as before. +- `Engine::set_terminal_background(true)` draws the diff on the terminal's own background + and text color: empty rows, plain context lines, gaps, file headers and the Files sidebar + get no background, and plain text uses the terminal's default foreground. Added and + deleted lines, changed words and hunk headers keep explicit tints from the palette of + `Options::appearance`, adjusted to read on lighter or bluer dark terminals. Off by + default; the `diffs` viewer does not change. ## 0.2.0 - 2026-11-15 diff --git a/docs/embedding.md b/docs/embedding.md index 497c012..5e71827 100644 --- a/docs/embedding.md +++ b/docs/embedding.md @@ -77,6 +77,20 @@ Read the state the footer would have shown from `status()`: `loading`, `coloring The review label, layout and theme are the host's own inputs and `options()`. `chrome` is fixed for the engine's lifetime, and `replace()` keeps it. +### Terminal background + +By default the engine paints its whole rectangle with the theme's background (#0a0a0a dark, #ffffff light) and its own text color. +A host whose other screens use the terminal's own colors can call `engine.set_terminal_background(true)?`: + +- Empty rows, plain context lines, gaps, metadata and "no newline" rows, file headers, the Files sidebar, and with chrome the label row, footer and help draw with `Color::Reset` as background. +- Plain text, including syntax tokens the theme leaves uncolored, uses the terminal's default foreground. Other syntax colors stay. +- Added and deleted lines, changed words, hunk headers, the empty half of a split row, and the Files keyboard cursor row keep explicit colors. They come from the palette of `Options::appearance`, so set the appearance that matches the terminal: `Dark` for a dark terminal, `Light` for a light one. +- The engine cannot know the terminal's exact background, so those colors are mixed for it: hunk headers are stronger than on the theme's own background, and the dark tints start from a slightly lighter base than #0a0a0a, so they read on black, #1e1e1e or a blue-grey alike. +- Gutter markers, the cursor and selection indicators, and the search match keep their own colors and underlines. + +It is off by default. It can be set before the first file arrives, stays set across `replace()`, and follows the `t` theme toggle. +It is a method rather than an `Options` field so that adding it does not break hosts that build `Options` without `..Options::default()`. + ## Commands and selection `handle_event(event, focused)` applies the viewer's default bindings. diff --git a/src/app.rs b/src/app.rs index 19e5273..5d3589e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -68,6 +68,11 @@ pub struct App { pub(crate) search_match: Option, pub(crate) selection: Option, pub(crate) markers: crate::engine::markers::Markers, + /// Draws the base surfaces and plain text in the terminal's own colors. + pub(crate) terminal_background: bool, + /// The theme's text color, which plain syntax tokens carry; drawn as the terminal's own + /// foreground when `terminal_background` is on. + pub(crate) plain: ratatui::style::Color, reading_anchor: Option, } @@ -80,6 +85,7 @@ impl App { wake: std::sync::mpsc::SyncSender<()>, ) -> anyhow::Result { let colors = theme::load(appearance)?.0; + let plain = colors.fg; let worker = crate::highlight::start(wake); Ok(Self { view: View::default(), @@ -96,6 +102,8 @@ impl App { search_match: None, selection: None, markers: Default::default(), + terminal_background: false, + plain, top: Position::default(), cursor: Position::default(), old_side: false, @@ -503,12 +511,29 @@ impl App { pub fn toggle_theme(&mut self) -> anyhow::Result<()> { self.appearance = self.appearance.toggle(); - self.colors = theme::load(self.appearance)?.0; + self.load_colors()?; self.epoch += 1; self.cache = Cache::default(); Ok(()) } + /// Draws the base surfaces and plain text in the terminal's own colors, or in the theme's. + pub(crate) fn set_terminal_background(&mut self, on: bool) -> Result<()> { + self.terminal_background = on; + self.load_colors() + } + + fn load_colors(&mut self) -> Result<()> { + let theme = theme::load(self.appearance)?.0; + self.plain = theme.fg; + self.colors = if self.terminal_background { + theme::on_terminal(self.appearance)? + } else { + theme + }; + Ok(()) + } + pub fn request_highlights(&self) { let mut ids = Vec::new(); let mut files = Vec::new(); diff --git a/src/engine.rs b/src/engine.rs index 3828e0d..43658c1 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -127,6 +127,8 @@ pub struct Engine { markers: markers::Markers, /// File marks set before the first file arrived, taken like `markers`. file_marks: file_marks::FileMarks, + /// Draw on the terminal's own background and foreground. Kept across `replace()`. + terminal_background: bool, } impl Engine { @@ -171,9 +173,26 @@ impl Engine { area: Rect::default(), markers: markers::Markers::default(), file_marks: file_marks::FileMarks::default(), + terminal_background: false, }) } + /// Draws the base surfaces in the terminal's default colors instead of the theme's: + /// empty rows, plain context lines, gaps, file headers, the Files sidebar, and the label + /// row and footer use `Color::Reset` as background, and plain text uses the terminal's + /// default foreground. Added and deleted lines, changed words, hunk headers and the + /// empty half of a split row keep explicit colors from the palette of + /// `Options::appearance`, so pick the appearance that matches the terminal. Off by + /// default; it stays set across `replace()`. + pub fn set_terminal_background(&mut self, on: bool) -> Result<()> { + self.terminal_background = on; + if let Some(app) = &mut self.app { + app.set_terminal_background(on)?; + } + self.changed(InputEffect::Redraw); + Ok(()) + } + pub fn review_id(&self) -> ReviewId { self.id } @@ -323,6 +342,9 @@ impl Engine { app.chrome = self.options.chrome; app.markers = std::mem::take(&mut self.markers); app.set_file_marks(std::mem::take(&mut self.file_marks)); + if self.terminal_background { + app.set_terminal_background(true)?; + } if self.full_sources { app.sources = Some(Vec::new()); } @@ -596,8 +618,10 @@ impl Engine { /// Close the previous review before creating fresh channels, identity and workers. pub fn replace(&mut self, input: Input) -> Result<()> { let options = self.options(); + let terminal_background = self.terminal_background; self.close()?; *self = Self::open(input, options, self.wake.clone())?; + self.terminal_background = terminal_background; Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index da9d6eb..3a25b7b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,8 +49,8 @@ //! ``` //! //! The [embedding guide](https://github.com/plannotator/diffs-rs/blob/main/docs/embedding.md) -//! covers the host loop, focus, source coordinates, chrome, markers, file marks, reading tools, -//! and shutdown. +//! covers the host loop, focus, source coordinates, chrome, the terminal background, markers, +//! file marks, reading tools, and shutdown. pub mod app; mod cleanup; diff --git a/src/render.rs b/src/render.rs index 5f970ed..7eec6f8 100644 --- a/src/render.rs +++ b/src/render.rs @@ -867,6 +867,8 @@ fn code(buf: &mut Buffer, app: &App, cell: CodeCell) -> anyhow::Result<()> { .filter(|t| t.range.contains(&glyph.byte)) }) .map(|t| t.color) + // Plain text carries the theme's text color; on the terminal's colors it is `c.fg`. + .filter(|color| !(app.terminal_background && *color == app.plain)) .unwrap_or(c.fg); let emphasized = style.is_some_and(|s| { s.changed diff --git a/src/render/sidebar.rs b/src/render/sidebar.rs index b9c1cc1..046745b 100644 --- a/src/render/sidebar.rs +++ b/src/render/sidebar.rs @@ -52,7 +52,14 @@ pub(super) fn draw(buf: &mut Buffer, app: &App) { let node = state.tree.node(row.node); let focused = state.focused() && state.cursor == Some(row.node); let current = node.file().is_some_and(|id| Some(id) == state.current); - let bg = if focused { c.context } else { c.chrome }; + // On the terminal's background the context color is the terminal's own, so the + // keyboard cursor row takes the hunk header band instead. + let highlight = if app.terminal_background { + c.separator + } else { + c.context + }; + let bg = if focused { highlight } else { c.chrome }; let y = area.y + 1 + offset as u16; fill( buf, diff --git a/src/render/tests.rs b/src/render/tests.rs index cf0adf4..bd17005 100644 --- a/src/render/tests.rs +++ b/src/render/tests.rs @@ -581,3 +581,126 @@ fn file_marks_truncate_long_names_but_never_the_badge() { ] ); } + +/// A modified file with context, a replacement, a pure addition and a pure deletion. +const CONTEXT: &str = "diff --git a/src/lib.rs b/src/lib.rs +index 1111111..2222222 100644 +--- a/src/lib.rs ++++ b/src/lib.rs +@@ -1,5 +1,5 @@ + fn first() {} +-fn old() {} ++fn new() {} + fn middle() {} +-fn gone() {} + fn last() {} ++fn added() {} +diff --git a/README.md b/README.md +index 3333333..4444444 100644 +--- a/README.md ++++ b/README.md +@@ -1 +1 @@ +-old ++new +"; + +/// The rows of `buffer` whose text contains `text`. +fn rows_with(buffer: &Buffer, text: &str) -> Vec { + let Rect { width, height, .. } = buffer.area; + (0..height) + .filter(|&y| { + (0..width) + .map(|x| buffer[(x, y)].symbol()) + .collect::() + .contains(text) + }) + .collect() +} + +#[test] +fn terminal_background_leaves_base_surfaces_to_the_terminal_and_keeps_tints() { + for appearance in [Appearance::Dark, Appearance::Light] { + for split in [true, false] { + let mut app = review_in(CONTEXT, "context.patch", appearance); + if !split { + app.layout = Layout::Unified; + } + // Off by default: the theme paints every cell. + let theme = draw_buffer(&mut app, 160, 24, None); + assert!( + theme.content().iter().all(|cell| cell.bg != Color::Reset), + "{appearance:?}" + ); + app.set_terminal_background(true).unwrap(); + let buffer = draw_buffer(&mut app, 160, 24, None); + let c = app.colors.clone(); + let width = buffer.area.width; + let cells = |y: u16| (0..width).map(move |x| (x, y)); + // Plain context rows, empty rows below the diff, the sidebar, the file headers, + // the label row and the footer carry no background, and plain text no foreground. + let mut plain: Vec = rows_with(&buffer, "fn middle() {}"); + plain.extend(rows_with(&buffer, "fn first() {}")); + plain.extend([0, 17, 18, 22, 23]); + for y in plain { + for cell in cells(y) { + assert_eq!( + buffer[cell].bg, + Color::Reset, + "{appearance:?} {split} {cell:?}" + ); + } + } + let row = rows_with(&buffer, "fn middle() {}")[0]; + let text = cells(row) + .find(|&cell| buffer[cell].symbol() == "m") + .unwrap(); + assert_eq!(buffer[text].fg, Color::Reset); + // Changed lines and hunk headers keep their explicit tints. + for (text, bg) in [ + ("fn added() {}", c.add_bg), + ("fn gone() {}", c.del_bg), + ("@@ -1,5 +1,5 @@", c.separator), + ] { + let row = rows_with(&buffer, text)[0]; + assert!( + cells(row).any(|cell| buffer[cell].bg == bg) && bg != Color::Reset, + "{appearance:?} {split} {text}" + ); + } + // The empty half of a split addition keeps its shading. + if split { + let row = rows_with(&buffer, "fn added() {}")[0]; + assert!(cells(row).any(|cell| buffer[cell].bg == c.empty)); + } + // Turning it off restores the theme. + app.set_terminal_background(false).unwrap(); + let again = draw_buffer(&mut app, 160, 24, None); + assert_eq!(again, theme, "{appearance:?} {split}"); + } + } +} + +#[test] +fn terminal_background_highlights_the_files_cursor_and_survives_a_theme_toggle() { + let mut app = review(KINDS, "kinds.patch"); + app.set_terminal_background(true).unwrap(); + draw_buffer(&mut app, 160, 24, None); + app.files_command().unwrap(); + let buffer = draw_buffer(&mut app, 160, 24, None); + let c = app.colors.clone(); + let cursor = styled(&buffer, app.sidebar.area, ">*", "added.rs"); + assert!( + cursor + .iter() + .all(|(_, bg)| *bg == c.separator && *bg != Color::Reset) + ); + let other = styled(&buffer, app.sidebar.area, "modified.rs", "modified.rs"); + assert!( + other + .iter() + .all(|(fg, bg)| (*fg, *bg) == (Color::Reset, Color::Reset)) + ); + app.toggle_theme().unwrap(); + assert_eq!(app.colors.bg, Color::Reset); + assert_ne!(app.colors.add_bg, c.add_bg); +} diff --git a/src/theme.rs b/src/theme.rs index 497a0d3..21b0c81 100644 --- a/src/theme.rs +++ b/src/theme.rs @@ -138,6 +138,42 @@ pub fn load(appearance: Appearance) -> Result<(Colors, Theme)> { Ok((colors, syntax)) } +/// The theme's colors for drawing on the terminal's own background and foreground. +/// +/// The base surfaces (diff, plain context, sidebar, label row, footer) and plain text become +/// `Color::Reset`. The tints keep explicit colors from the `appearance` palette, which should +/// match the terminal: a dark palette on a dark terminal, a light one on a light terminal. +/// The terminal's background is not known and is often lighter or bluer than the theme's, +/// so hunk headers are mixed more strongly, and the +/// dark tints start from a slightly lighter base than #0a0a0a. +pub(crate) fn on_terminal(appearance: Appearance) -> Result { + let colors = load(appearance)?.0; + let dark = appearance == Appearance::Dark; + let fg = colors.fg; + // Dark terminals are rarely as dark as the theme's #0a0a0a, so the dark tints start from + // a slightly lighter base and sit on #1e1e1e or #1e2230 as they do on black. + let base = if dark { + lab_mix(colors.bg, fg, 0.06) + } else { + colors.bg + }; + let add_bg = lab_mix(base, colors.added, if dark { 0.22 } else { 0.12 }); + let del_bg = lab_mix(base, colors.deleted, if dark { 0.22 } else { 0.12 }); + Ok(Colors { + bg: Color::Reset, + fg: Color::Reset, + chrome: Color::Reset, + context: Color::Reset, + separator: lab_mix(base, fg, if dark { 0.16 } else { 0.09 }), + empty: lab_mix(base, fg, if dark { 0.12 } else { 0.10 }), + add_bg, + del_bg, + add_word: alpha_mix(add_bg, colors.added, if dark { 0.20 } else { 0.15 }), + del_word: alpha_mix(del_bg, colors.deleted, if dark { 0.20 } else { 0.15 }), + ..colors + }) +} + fn components(color: Color) -> (u8, u8, u8) { let Color::Rgb(r, g, b) = color else { unreachable!("theme colors are RGB") diff --git a/tests/engine.rs b/tests/engine.rs index 5e05251..ccaa645 100644 --- a/tests/engine.rs +++ b/tests/engine.rs @@ -782,3 +782,45 @@ fn file_marks_badge_and_dim_sidebar_rows_without_moving_the_diff() { host.engine.close().unwrap(); assert!(host.engine.set_file_marks(&[]).is_err()); } + +#[test] +fn terminal_background_draws_plain_text_and_context_in_the_terminal_colors() { + let mut host = Host::new(); + let theme_text = Color::Rgb(0xfa, 0xfa, 0xfa); + let buffer = host.settle(); + let area = host.area; + let cells = |buffer: &Buffer, y: u16| -> Vec<(Color, Color)> { + (area.x..area.right()) + .map(|x| (buffer[(x, y)].fg, buffer[(x, y)].bg)) + .collect() + }; + let row = find(&buffer, area, "fn start() {}"); + assert!(cells(&buffer, row).iter().any(|(fg, _)| *fg == theme_text)); + host.engine.set_terminal_background(true).unwrap(); + assert!(host.engine.needs_draw()); + for replaced in [false, true] { + let buffer = host.settle(); + // A colored context row: no background anywhere, and the theme's text color is gone. + let row = find(&buffer, area, "fn start() {}"); + let row = cells(&buffer, row); + assert!(row.iter().all(|(_, bg)| *bg == Color::Reset), "{replaced}"); + assert!(row.iter().all(|(fg, _)| *fg != theme_text), "{replaced}"); + assert!(row.iter().any(|(fg, _)| *fg == Color::Reset), "{replaced}"); + // Syntax colors stay: some cell carries an explicit foreground. + assert!( + row.iter().any(|(fg, _)| matches!(fg, Color::Rgb(..))), + "{replaced}" + ); + // An added line keeps its tint. + let added = find(&buffer, area, "let extra = true;"); + assert!( + cells(&buffer, added) + .iter() + .any(|(_, bg)| matches!(bg, Color::Rgb(..))), + "{replaced}" + ); + // The setting survives replacement. + let path = host.directory.path().join("review.patch"); + host.engine.replace(Input::Patch(path)).unwrap(); + } +}