Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent-tui): color-depth-aware diff and accent fallback

Akarshan Biswasebdb87ebf356
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 4fe657119..53fa249b4 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -7947,7 +7947,8 @@ fn user_bubble_bg_for(light: bool) -> Color {
}
fn user_bubble_bg() -> Color {
- user_bubble_bg_for(theme::is_light())
+ let t = theme::Theme::current();
+ t.fit(user_bubble_bg_for(t.light))
}
/// User-turn text: the inverse of the bubble background so the message keeps
@@ -7965,7 +7966,8 @@ fn user_bubble_fg_for(light: bool) -> Color {
}
fn user_bubble_fg() -> Color {
- user_bubble_fg_for(theme::is_light())
+ let t = theme::Theme::current();
+ t.fit(user_bubble_fg_for(t.light))
}
/// Tint a run of gutter rows as one filled bubble: every span carries the
@@ -7989,12 +7991,11 @@ fn band_rows(lines: Vec<Line<'static>>, bg: Color) -> Vec<Line<'static>> {
.collect()
}
-fn diff_add_bg() -> Color {
- diff_bg(true, theme::is_light())
-}
-
-fn diff_del_bg() -> Color {
- diff_bg(false, theme::is_light())
+/// The band behind a changed diff row at the theme's depth, or `None` on a
+/// 16-colour terminal, where the row is told apart by a red/green foreground
+/// instead (see `Theme::subtle`).
+fn diff_band(added: bool, t: theme::Theme) -> Option<Color> {
+ t.subtle(diff_bg(added, t.light))
}
/// Selection style shared by every arrow-navigable list (ask, permission, slash
@@ -8025,6 +8026,19 @@ fn diff_lines(
max_rows: usize,
gutter: &'static str,
lang: Option<&str>,
+) -> Vec<Line<'static>> {
+ diff_lines_in(theme::Theme::current(), diff, width, max_rows, gutter, lang)
+}
+
+/// `diff_lines` for an explicit theme, so each colour depth is tested without
+/// the process-wide state.
+fn diff_lines_in(
+ t: theme::Theme,
+ diff: &str,
+ width: usize,
+ max_rows: usize,
+ gutter: &'static str,
+ lang: Option<&str>,
) -> Vec<Line<'static>> {
let max = panel_inner(width, gutter);
let all: Vec<&str> = diff.lines().collect();
@@ -8050,11 +8064,12 @@ fn diff_lines(
rows.push(Line::styled(line.clone(), Style::new().cyan().dim()));
continue;
}
- let bg = match marker.as_bytes().first() {
- Some(b'-') => Some(diff_del_bg()),
- Some(b'+') => Some(diff_add_bg()),
+ let change = match marker.as_bytes().first() {
+ Some(b'-') => Some(Color::Red),
+ Some(b'+') => Some(Color::Green),
_ => None,
};
+ let bg = change.and_then(|c| diff_band(c == Color::Green, t));
let mut spans = Vec::with_capacity(2);
if !marker.is_empty() {
// On a tinted row the marker takes the strong colour and the code
@@ -8066,11 +8081,16 @@ fn diff_lines(
};
spans.push(Span::styled(marker.to_string(), marker_style));
}
- match &highlighted {
- Some(h) => spans.extend(h[i].iter().cloned()),
+ match (&highlighted, change) {
+ // Without a band the foreground is all that says what changed, so
+ // it wins over the syntax colours.
+ (_, Some(fg)) if bg.is_none() => {
+ spans.push(Span::styled(body.to_string(), Style::new().fg(fg)))
+ }
+ (Some(h), _) => spans.extend(h[i].iter().cloned()),
// Dimming an unhighlighted body would fight the tint behind it.
- None if bg.is_some() => spans.push(Span::raw(body.to_string())),
- None => spans.push(Span::styled(body.to_string(), Style::new().dim())),
+ (None, _) if bg.is_some() => spans.push(Span::raw(body.to_string())),
+ (None, _) => spans.push(Span::styled(body.to_string(), Style::new().dim())),
}
// The tint rides on the line so `boxed_panel` can carry it across the
// padding too, making the band reach the right border.
@@ -30012,6 +30032,74 @@ mod tests {
}
}
+ /// The diff bands follow the colour depth: RGB on truecolor, the nearest
+ /// palette index on 256 colours, and no band at all on 16.
+ #[test]
+ fn diff_bands_fit_each_colour_depth() {
+ use super::diff_band;
+ use super::theme::{ColorDepth, Theme};
+ use ratatui::style::Color;
+ let at = |light, depth| Theme { light, depth };
+ for light in [false, true] {
+ for added in [false, true] {
+ let tc = diff_band(added, at(light, ColorDepth::Truecolor));
+ assert!(matches!(tc, Some(Color::Rgb(..))), "{tc:?}");
+ let idx = diff_band(added, at(light, ColorDepth::Ansi256));
+ assert!(matches!(idx, Some(Color::Indexed(16..=255))), "{idx:?}");
+ assert_eq!(diff_band(added, at(light, ColorDepth::Ansi16)), None);
+ }
+ assert_ne!(
+ diff_band(true, at(light, ColorDepth::Ansi256)),
+ diff_band(false, at(light, ColorDepth::Ansi256)),
+ "add and remove must differ on 256 colours (light={light})"
+ );
+ }
+ }
+
+ /// A 16-colour diff drops the band and says what changed with a plain
+ /// red/green foreground, over the syntax colours, so nothing on the row is
+ /// a colour code the terminal cannot show.
+ #[test]
+ fn sixteen_colour_diff_rows_are_foreground_only() {
+ use super::diff_lines_in;
+ use super::theme::{ColorDepth, Theme};
+ use ratatui::style::Color;
+ let diff = " 1 | fn main() {\n- 2 | let x = 1;\n+ 2 | let y = 2;";
+ let t = Theme { light: false, depth: ColorDepth::Ansi16 };
+ let out = diff_lines_in(t, diff, 80, DIFF_MAX_ROWS, "", Some("src/main.rs"));
+ for (needle, fg) in [("let x = 1;", Color::Red), ("let y = 2;", Color::Green)] {
+ let row = diff_row(&out, needle);
+ assert_eq!(row.style.bg, None, "16-colour row was banded: {row:?}");
+ assert!(row.spans.iter().all(|s| s.style.bg.is_none()));
+ let body = row
+ .spans
+ .iter()
+ .find(|s| s.content.contains(needle))
+ .unwrap_or_else(|| panic!("no body span in {row:?}"));
+ assert_eq!(body.style.fg, Some(fg), "{needle:?}");
+ }
+ // Context rows take their token colours from `highlight`, which reads
+ // the process-wide theme; the changed rows and every band are this
+ // function's own.
+ let no_codes = ["let x = 1;", "let y = 2;"]
+ .iter()
+ .flat_map(|n| diff_row(&out, n).spans)
+ .flat_map(|s| [s.style.fg, s.style.bg])
+ .chain(out.iter().flat_map(|l| l.spans.iter().map(|s| s.style.bg)))
+ .all(|c| !matches!(c, Some(Color::Rgb(..) | Color::Indexed(..))));
+ assert!(no_codes, "a 16-colour diff emitted an RGB or indexed colour");
+
+ // On 256 colours the band is an index and the code keeps its tokens.
+ let t = Theme { light: false, depth: ColorDepth::Ansi256 };
+ let out = diff_lines_in(t, diff, 80, DIFF_MAX_ROWS, "", Some("src/main.rs"));
+ assert!(
+ row_backgrounds(&out, "let y = 2;")
+ .iter()
+ .all(|bg| matches!(bg, Some(Color::Indexed(_)))),
+ "256-colour row not banded by an index"
+ );
+ }
+
/// The user bubble flips with the terminal theme like the diff bands do.
#[test]
fn user_bubble_picks_a_variant_per_theme() {
diff --git a/src-tauri/src/core/cli/tui/highlight.rs b/src-tauri/src/core/cli/tui/highlight.rs
index 5506df9f0..9a7f58af7 100644
--- a/src-tauri/src/core/cli/tui/highlight.rs
+++ b/src-tauri/src/core/cli/tui/highlight.rs
@@ -152,7 +152,17 @@ fn highlight_uncached(body: &[&str], token: &str) -> Rows {
/// syntect style -> ratatui style, dropping the background (see module docs).
fn convert(s: SynStyle) -> Style {
- let mut out = Style::new().fg(Color::Rgb(s.foreground.r, s.foreground.g, s.foreground.b));
+ convert_in(s, super::theme::Theme::current())
+}
+
+/// `convert` at an explicit theme. The token colour is fitted to the colour
+/// depth and dropped on 16 colours, leaving only the font style there.
+fn convert_in(s: SynStyle, t: super::theme::Theme) -> Style {
+ let fg = Color::Rgb(s.foreground.r, s.foreground.g, s.foreground.b);
+ let mut out = match t.subtle(fg) {
+ Some(fg) => Style::new().fg(fg),
+ None => Style::new(),
+ };
if s.font_style.contains(FontStyle::BOLD) {
out = out.bold();
}
@@ -221,6 +231,26 @@ mod tests {
assert_eq!(text(&rows[0]), "plain text");
}
+ #[test]
+ fn token_colours_follow_the_colour_depth() {
+ use super::super::theme::{ColorDepth, Theme};
+ use super::{convert_in, FontStyle, SynStyle};
+ use ratatui::style::{Color, Modifier};
+ use syntect::highlighting::Color as SynColor;
+ let s = SynStyle {
+ foreground: SynColor { r: 191, g: 97, b: 106, a: 0xff },
+ background: SynColor::BLACK,
+ font_style: FontStyle::BOLD,
+ };
+ let at = |depth| convert_in(s, Theme { light: false, depth });
+ assert_eq!(at(ColorDepth::Truecolor).fg, Some(Color::Rgb(191, 97, 106)));
+ assert!(matches!(at(ColorDepth::Ansi256).fg, Some(Color::Indexed(_))));
+ // 16 colours keep the font style but leave the token in the default fg.
+ let plain = at(ColorDepth::Ansi16);
+ assert_eq!(plain.fg, None);
+ assert!(plain.add_modifier.contains(Modifier::BOLD));
+ }
+
#[test]
fn no_background_is_ever_emitted() {
// A theme background would show as a colour block inside the panel.
diff --git a/src-tauri/src/core/cli/tui/theme.rs b/src-tauri/src/core/cli/tui/theme.rs
index 77bf24b6c..f5c5e5452 100644
--- a/src-tauri/src/core/cli/tui/theme.rs
+++ b/src-tauri/src/core/cli/tui/theme.rs
@@ -1,17 +1,102 @@
-//! Terminal light/dark theme resolution.
+//! Terminal theme resolution: light/dark background and colour depth.
//!
//! Resolved once at startup and read live everywhere a colour depends on the
-//! terminal background (the syntect theme in `highlight`, the diff `+`/`-`
-//! bands). The state is a process-wide flag, mirroring `set_think_tags_parsed`:
-//! the colour helpers are reached from free render functions with no session in
-//! hand. `false` (dark) is the default so tests and any pre-resolution render
+//! terminal (the syntect theme in `highlight`, the diff `+`/`-` bands, the
+//! accent). The state is process-wide, mirroring `set_think_tags_parsed`: the
+//! colour helpers are reached from free render functions with no session in
+//! hand. Dark truecolor is the default so tests and any pre-resolution render
//! match today's behaviour.
+//!
+//! Callers that need more than one colour take a resolved [`Theme`] (from
+//! [`Theme::current`]) and pass every truecolor value through [`Theme::fit`] or
+//! [`Theme::subtle`], so a 256- or 16-colour terminal never receives RGB codes it
+//! would downsample on its own.
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use ratatui::style::Color;
static IS_LIGHT: AtomicBool = AtomicBool::new(false);
+static DEPTH: AtomicU8 = AtomicU8::new(ColorDepth::Truecolor as u8);
+
+/// How many colours the terminal can show. Ordered richest first.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) enum ColorDepth {
+ /// 24-bit RGB: every colour is emitted as-is.
+ Truecolor = 0,
+ /// The xterm 256-colour palette: RGB maps to the nearest `Color::Indexed`.
+ Ansi256 = 1,
+ /// The 16 named ANSI colours, whose actual values the user's palette picks.
+ Ansi16 = 2,
+}
+
+impl ColorDepth {
+ fn from_u8(v: u8) -> Self {
+ match v {
+ 1 => Self::Ansi256,
+ 2 => Self::Ansi16,
+ _ => Self::Truecolor,
+ }
+ }
+}
+
+/// The resolved terminal theme: everything a colour choice depends on.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(super) struct Theme {
+ /// The terminal background is light.
+ pub(super) light: bool,
+ /// The colour depth colours are fitted to.
+ pub(super) depth: ColorDepth,
+}
+
+/// The accent on a 16-colour terminal. There is no orange in the ANSI set;
+/// yellow is the nearest hue, and since the user's palette already tunes it for
+/// their background, one value serves both themes.
+const STRONG_ACCENT_ANSI16: Color = Color::Yellow;
+
+impl Theme {
+ /// The theme resolved at startup (dark truecolor before resolution).
+ pub(super) fn current() -> Self {
+ Self {
+ light: is_light(),
+ depth: ColorDepth::from_u8(DEPTH.load(Ordering::Relaxed)),
+ }
+ }
+
+ /// Fit a colour to the depth: RGB passes through on truecolor, maps to the
+ /// nearest xterm index on 256 colours and to the nearest named colour on 16.
+ /// Non-RGB colours already speak the terminal's palette and pass through.
+ pub(super) fn fit(self, color: Color) -> Color {
+ let Color::Rgb(r, g, b) = color else {
+ return color;
+ };
+ match self.depth {
+ ColorDepth::Truecolor => color,
+ ColorDepth::Ansi256 => Color::Indexed(rgb_to_xterm256(r, g, b)),
+ ColorDepth::Ansi16 => rgb_to_ansi16(r, g, b),
+ }
+ }
+
+ /// Fit a subtle colour whose meaning lives in shades the 16 ANSI colours
+ /// cannot express: a background tint under text the caller does not control,
+ /// or a syntax token colour. `None` on 16 colours, where the nearest named
+ /// colour is wrong (a saturated red band under code is unreadable; pastel
+ /// tokens collapse to grey), so the caller drops it and falls back.
+ pub(super) fn subtle(self, color: Color) -> Option<Color> {
+ match self.depth {
+ ColorDepth::Ansi16 => None,
+ _ => Some(self.fit(color)),
+ }
+ }
+
+ /// The orange accent for this theme and depth.
+ pub(super) fn strong_accent(self) -> Color {
+ match self.depth {
+ ColorDepth::Ansi16 => STRONG_ACCENT_ANSI16,
+ _ => self.fit(strong_accent_for(self.light)),
+ }
+ }
+}
/// Whether the resolved terminal theme is light. Dark until `resolve_and_apply`
/// says otherwise.
@@ -37,7 +122,7 @@ fn strong_accent_for(light: bool) -> Color {
/// Theme-aware orange accent. Reads the resolved theme live, like the diff bands.
pub(super) fn strong_accent() -> Color {
- strong_accent_for(is_light())
+ Theme::current().strong_accent()
}
fn set_is_light(value: bool) {
@@ -45,11 +130,146 @@ fn set_is_light(value: bool) {
}
/// Resolve the theme from the `theme` config value and, when it is auto/unset,
-/// the terminal itself, and apply it process-wide. Called once at startup, after
-/// raw mode is on (so the OSC query can read its reply) and before the first
-/// highlight warms its theme.
+/// the terminal itself, and apply it process-wide together with the colour
+/// depth. Called once at startup, after raw mode is on (so the OSC query can
+/// read its reply) and before the first highlight warms its theme.
pub(crate) fn resolve_and_apply(config: Option<String>) {
set_is_light(classify(config.as_deref(), detect_is_light));
+ DEPTH.store(detect_depth() as u8, Ordering::Relaxed);
+}
+
+/// Colour depth from the environment.
+fn detect_depth() -> ColorDepth {
+ classify_depth(|name| std::env::var(name).ok())
+}
+
+/// `TERM` values that name a terminal limited to the 16 ANSI colours.
+const ANSI16_TERMS: &[&str] = &[
+ "linux", "vt100", "vt102", "vt220", "ansi", "xterm", "xterm-color", "screen", "tmux",
+ "rxvt", "cygwin",
+];
+
+/// Decide the colour depth from the environment `var` reads, in precedence
+/// order (the order the `supports-color` crate uses, plus a Windows Terminal
+/// promotion):
+///
+/// 1. `FORCE_COLOR` -- the user's explicit level: `3` truecolor, `2` 256,
+/// anything else that is set 16 (there is no colourless mode to fall to).
+/// 2. `WT_SESSION` -- Windows Terminal renders truecolor but sets neither
+/// `COLORTERM` nor a telling `TERM`, and under WSL inherits a stale one.
+/// 3. `TERM=dumb` -- no colour to speak of, so the most conservative depth.
+/// 4. `COLORTERM` of `truecolor`/`24bit`.
+/// 5. `TERM`: `-direct`/truecolor names, then `256color`, then a known
+/// 16-colour name.
+///
+/// Anything else is inconclusive and keeps truecolor, today's behaviour. Pure
+/// -- `var` is passed in -- so the precedence is tested without the process env.
+fn classify_depth(var: impl Fn(&str) -> Option<String>) -> ColorDepth {
+ let read = |name| var(name).map(|v| v.trim().to_ascii_lowercase());
+ if let Some(force) = read("FORCE_COLOR") {
+ return match force.as_str() {
+ "3" => ColorDepth::Truecolor,
+ "2" => ColorDepth::Ansi256,
+ _ => ColorDepth::Ansi16,
+ };
+ }
+ if read("WT_SESSION").is_some_and(|v| !v.is_empty()) {
+ return ColorDepth::Truecolor;
+ }
+ let term = read("TERM").unwrap_or_default();
+ if term == "dumb" {
+ return ColorDepth::Ansi16;
+ }
+ let colorterm = read("COLORTERM").unwrap_or_default();
+ if colorterm == "truecolor" || colorterm == "24bit" {
+ return ColorDepth::Truecolor;
+ }
+ if term.ends_with("-direct") || term.contains("truecolor") || term.contains("24bit") {
+ ColorDepth::Truecolor
+ } else if term.contains("256col") {
+ ColorDepth::Ansi256
+ } else if term.ends_with("-16color") || ANSI16_TERMS.contains(&term.as_str()) {
+ ColorDepth::Ansi16
+ } else {
+ ColorDepth::Truecolor
+ }
+}
+
+/// Channel values of the xterm 6x6x6 colour cube (indices 16-231).
+const CUBE_LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255];
+
+/// Channel spread (max - min) at or above which a colour counts as tinted.
+const TINT_SPREAD: u8 = 24;
+
+fn dist2(a: (u8, u8, u8), b: (u8, u8, u8)) -> u32 {
+ let d = |x: u8, y: u8| (x as i32 - y as i32).pow(2) as u32;
+ d(a.0, b.0) + d(a.1, b.1) + d(a.2, b.2)
+}
+
+/// Nearest xterm-256 index for an RGB colour, from the cube (16-231) or the grey
+/// ramp (232-255); never 0-15, whose values the user's palette redefines.
+///
+/// A tinted colour stays in the cube even when a grey is closer by distance:
+/// the diff bands are dark, desaturated tints whose whole job is their hue, and
+/// plain nearest-distance would turn both the add and the remove band into the
+/// same grey.
+fn rgb_to_xterm256(r: u8, g: u8, b: u8) -> u8 {
+ let level = |v: u8| -> usize {
+ // Midpoints between the uneven cube levels: 0|95 at 48, then every 40.
+ match v {
+ 0..=47 => 0,
+ 48..=114 => 1,
+ _ => ((v - 35) / 40) as usize,
+ }
+ };
+ let (ri, gi, bi) = (level(r), level(g), level(b));
+ let cube = (CUBE_LEVELS[ri], CUBE_LEVELS[gi], CUBE_LEVELS[bi]);
+ let cube_index = 16 + 36 * ri as u8 + 6 * gi as u8 + bi as u8;
+
+ let spread = r.max(g).max(b) - r.min(g).min(b);
+ if spread >= TINT_SPREAD {
+ return cube_index;
+ }
+ // Grey ramp step i is 8 + 10i for i in 0..24.
+ let avg = (r as u32 + g as u32 + b as u32) / 3;
+ let step = (avg.saturating_sub(3) / 10).min(23) as u8;
+ let grey = 8 + 10 * step;
+ if dist2((r, g, b), (grey, grey, grey)) < dist2((r, g, b), cube) {
+ 232 + step
+ } else {
+ cube_index
+ }
+}
+
+/// The 16 named colours with xterm's default values, for nearest matching.
+const ANSI16: [(Color, (u8, u8, u8)); 16] = [
+ (Color::Black, (0, 0, 0)),
+ (Color::Red, (205, 0, 0)),
+ (Color::Green, (0, 205, 0)),
+ (Color::Yellow, (205, 205, 0)),
+ (Color::Blue, (0, 0, 238)),
+ (Color::Magenta, (205, 0, 205)),
+ (Color::Cyan, (0, 205, 205)),
+ (Color::Gray, (229, 229, 229)),
+ (Color::DarkGray, (127, 127, 127)),
+ (Color::LightRed, (255, 0, 0)),
+ (Color::LightGreen, (0, 255, 0)),
+ (Color::LightYellow, (255, 255, 0)),
+ (Color::LightBlue, (92, 92, 255)),
+ (Color::LightMagenta, (255, 0, 255)),
+ (Color::LightCyan, (0, 255, 255)),
+ (Color::White, (255, 255, 255)),
+];
+
+/// Nearest named ANSI colour, measured against xterm's defaults. The user's
+/// palette decides the real values, which is the point: the colour then follows
+/// their theme instead of being an RGB code the terminal cannot show.
+fn rgb_to_ansi16(r: u8, g: u8, b: u8) -> Color {
+ ANSI16
+ .iter()
+ .min_by_key(|(_, rgb)| dist2((r, g, b), *rgb))
+ .map(|(c, _)| *c)
+ .unwrap_or(Color::Reset)
}
/// Decide light vs dark from the config value, deferring to `detect` only when
@@ -229,6 +449,163 @@ mod tests {
);
}
+ fn theme(light: bool, depth: ColorDepth) -> Theme {
+ Theme { light, depth }
+ }
+
+ /// `classify_depth` over a fixed environment.
+ fn depth(env: &[(&str, &str)]) -> ColorDepth {
+ classify_depth(|name| {
+ env.iter()
+ .find(|(k, _)| *k == name)
+ .map(|(_, v)| v.to_string())
+ })
+ }
+
+ #[test]
+ fn depth_defaults_to_truecolor_when_inconclusive() {
+ assert_eq!(depth(&[]), ColorDepth::Truecolor);
+ assert_eq!(depth(&[("COLORTERM", ""), ("TERM", "")]), ColorDepth::Truecolor);
+ assert_eq!(
+ depth(&[("COLORTERM", "yes"), ("TERM", "xterm-kitty")]),
+ ColorDepth::Truecolor
+ );
+ assert_eq!(depth(&[("TERM", "alacritty")]), ColorDepth::Truecolor);
+ }
+
+ #[test]
+ fn depth_reads_colorterm_then_term() {
+ assert_eq!(depth(&[("COLORTERM", "truecolor")]), ColorDepth::Truecolor);
+ assert_eq!(depth(&[("COLORTERM", " 24BIT ")]), ColorDepth::Truecolor);
+ // COLORTERM outranks a TERM that undersells the terminal.
+ assert_eq!(
+ depth(&[("COLORTERM", "truecolor"), ("TERM", "xterm-256color")]),
+ ColorDepth::Truecolor
+ );
+ assert_eq!(
+ depth(&[("COLORTERM", "truecolor"), ("TERM", "xterm")]),
+ ColorDepth::Truecolor
+ );
+ assert_eq!(depth(&[("TERM", "xterm-direct")]), ColorDepth::Truecolor);
+ assert_eq!(depth(&[("TERM", "xterm-256color")]), ColorDepth::Ansi256);
+ assert_eq!(depth(&[("TERM", "tmux-256color")]), ColorDepth::Ansi256);
+ assert_eq!(depth(&[("TERM", "screen.xterm-256color")]), ColorDepth::Ansi256);
+ for term in ["linux", "vt100", "xterm", "xterm-color", "screen", "xterm-16color"] {
+ assert_eq!(depth(&[("TERM", term)]), ColorDepth::Ansi16, "{term}");
+ }
+ }
+
+ #[test]
+ fn dumb_term_outranks_colorterm() {
+ assert_eq!(
+ depth(&[("COLORTERM", "truecolor"), ("TERM", "dumb")]),
+ ColorDepth::Ansi16
+ );
+ }
+
+ #[test]
+ fn windows_terminal_is_truecolor_whatever_term_says() {
+ assert_eq!(depth(&[("WT_SESSION", "abc")]), ColorDepth::Truecolor);
+ assert_eq!(
+ depth(&[("WT_SESSION", "abc"), ("TERM", "xterm")]),
+ ColorDepth::Truecolor
+ );
+ assert_eq!(
+ depth(&[("WT_SESSION", "abc"), ("TERM", "dumb")]),
+ ColorDepth::Truecolor
+ );
+ assert_eq!(
+ depth(&[("WT_SESSION", ""), ("TERM", "xterm")]),
+ ColorDepth::Ansi16,
+ "an empty WT_SESSION says nothing"
+ );
+ }
+
+ #[test]
+ fn force_color_outranks_everything() {
+ let wt = ("WT_SESSION", "abc");
+ let tc = ("COLORTERM", "truecolor");
+ assert_eq!(depth(&[("FORCE_COLOR", "3"), ("TERM", "dumb")]), ColorDepth::Truecolor);
+ assert_eq!(depth(&[("FORCE_COLOR", "2"), wt, tc]), ColorDepth::Ansi256);
+ assert_eq!(depth(&[("FORCE_COLOR", "1"), wt, tc]), ColorDepth::Ansi16);
+ assert_eq!(depth(&[("FORCE_COLOR", "0"), wt]), ColorDepth::Ansi16);
+ assert_eq!(depth(&[("FORCE_COLOR", ""), tc]), ColorDepth::Ansi16);
+ }
+
+ #[test]
+ fn xterm256_maps_cube_and_grey_ramp() {
+ assert_eq!(rgb_to_xterm256(0, 0, 0), 16);
+ assert_eq!(rgb_to_xterm256(255, 255, 255), 231);
+ assert_eq!(rgb_to_xterm256(95, 135, 175), 67);
+ assert_eq!(rgb_to_xterm256(255, 0, 0), 196);
+ assert_eq!(rgb_to_xterm256(128, 128, 128), 244, "exact grey step");
+ assert_eq!(rgb_to_xterm256(238, 238, 238), 255, "top of the ramp");
+ assert_eq!(rgb_to_xterm256(40, 44, 58), 236, "a slate is near-grey");
+ assert_eq!(rgb_to_xterm256(255, 165, 0), 214);
+ assert_eq!(rgb_to_xterm256(180, 83, 9), 130);
+ }
+
+ #[test]
+ fn xterm256_keeps_the_hue_of_a_dark_tint() {
+ // Plain nearest-distance would grey both diff bands out; they stay green
+ // and red.
+ assert_eq!(rgb_to_xterm256(22, 52, 32), 22);
+ assert_eq!(rgb_to_xterm256(66, 26, 30), 52);
+ assert_eq!(rgb_to_xterm256(198, 239, 206), 194);
+ assert_eq!(rgb_to_xterm256(255, 205, 210), 224);
+ }
+
+ #[test]
+ fn ansi16_picks_the_nearest_named_colour() {
+ assert_eq!(rgb_to_ansi16(0, 0, 0), Color::Black);
+ assert_eq!(rgb_to_ansi16(250, 250, 250), Color::White);
+ assert_eq!(rgb_to_ansi16(200, 10, 10), Color::Red);
+ assert_eq!(rgb_to_ansi16(10, 250, 10), Color::LightGreen);
+ assert_eq!(rgb_to_ansi16(40, 44, 58), Color::Black);
+ assert_eq!(rgb_to_ansi16(226, 232, 240), Color::Gray);
+ }
+
+ #[test]
+ fn fit_emits_the_variant_for_each_depth() {
+ let rgb = Color::Rgb(22, 52, 32);
+ assert_eq!(theme(false, ColorDepth::Truecolor).fit(rgb), rgb);
+ assert_eq!(theme(false, ColorDepth::Ansi256).fit(rgb), Color::Indexed(22));
+ assert!(!matches!(
+ theme(false, ColorDepth::Ansi16).fit(rgb),
+ Color::Rgb(..) | Color::Indexed(..)
+ ));
+ // Palette colours are already safe at any depth.
+ for depth in [ColorDepth::Truecolor, ColorDepth::Ansi256, ColorDepth::Ansi16] {
+ assert_eq!(theme(true, depth).fit(Color::Cyan), Color::Cyan);
+ }
+ }
+
+ #[test]
+ fn subtle_colours_are_dropped_on_sixteen_colours() {
+ let rgb = Color::Rgb(66, 26, 30);
+ assert_eq!(theme(false, ColorDepth::Truecolor).subtle(rgb), Some(rgb));
+ assert_eq!(theme(false, ColorDepth::Ansi256).subtle(rgb), Some(Color::Indexed(52)));
+ assert_eq!(theme(false, ColorDepth::Ansi16).subtle(rgb), None);
+ }
+
+ #[test]
+ fn strong_accent_has_a_fallback_per_depth() {
+ let t = |light, depth| theme(light, depth).strong_accent();
+ assert_eq!(t(false, ColorDepth::Truecolor), STRONG_ACCENT_DARK);
+ assert_eq!(t(true, ColorDepth::Truecolor), STRONG_ACCENT_LIGHT);
+ assert_eq!(t(false, ColorDepth::Ansi256), Color::Indexed(214));
+ assert_eq!(t(true, ColorDepth::Ansi256), Color::Indexed(130));
+ assert_eq!(t(false, ColorDepth::Ansi16), Color::Yellow);
+ assert_eq!(t(true, ColorDepth::Ansi16), Color::Yellow);
+ }
+
+ #[test]
+ fn the_unresolved_theme_is_dark_truecolor() {
+ // Nothing in the test binary resolves the theme, so this is the default.
+ assert_eq!(Theme::current(), theme(false, ColorDepth::Truecolor));
+ assert_eq!(strong_accent(), STRONG_ACCENT_DARK);
+ }
+
#[test]
fn classify_prefers_an_explicit_choice_over_detection() {
// An explicit choice wins and never runs detection.