use ratatui::buffer::Buffer;
use ratatui::style::Color;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorDepth {
TrueColor,
Ansi256,
Ansi16,
}
impl ColorDepth {
pub fn from_setting(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"truecolor" | "24bit" => Some(Self::TrueColor),
"256" => Some(Self::Ansi256),
"16" => Some(Self::Ansi16),
_ => None,
}
}
pub fn detect(env: impl Fn(&str) -> Option<String>) -> Self {
let var = |name: &str| env(name).unwrap_or_default().to_ascii_lowercase();
let colorterm = var("COLORTERM");
if colorterm == "truecolor" || colorterm == "24bit" {
return Self::TrueColor;
}
const TRUECOLOR_PROGRAMS: &[&str] = &[
"iterm.app",
"wezterm",
"ghostty",
"vscode",
"tmux",
"hyper",
"tabby",
"warpterminal",
"rio",
];
if TRUECOLOR_PROGRAMS.contains(&var("TERM_PROGRAM").as_str()) {
return Self::TrueColor;
}
if env("WT_SESSION").is_some_and(|s| !s.is_empty()) {
return Self::TrueColor;
}
let term = var("TERM");
const TRUECOLOR_TERMS: &[&str] = &[
"kitty",
"ghostty",
"alacritty",
"wezterm",
"foot",
"contour",
"rio",
"direct",
"truecolor",
"24bit",
];
if TRUECOLOR_TERMS.iter().any(|t| term.contains(t)) {
return Self::TrueColor;
}
if term.contains("256color") {
return Self::Ansi256;
}
Self::Ansi16
}
pub fn fit(self, color: Color) -> Color {
match (self, color) {
(Self::TrueColor, c) => c,
(Self::Ansi256, Color::Rgb(r, g, b)) => Color::Indexed(nearest_256(r, g, b)),
(Self::Ansi16, Color::Rgb(r, g, b)) => nearest_16(r, g, b),
(Self::Ansi16, Color::Indexed(i)) if i >= 16 => {
let (r, g, b) = palette_256(i);
nearest_16(r, g, b)
}
(_, c) => c,
}
}
pub fn fit_buffer(self, buffer: &mut Buffer) {
if self == Self::TrueColor {
return;
}
for cell in &mut buffer.content {
cell.fg = self.fit(cell.fg);
cell.bg = self.fit(cell.bg);
cell.underline_color = self.fit(cell.underline_color);
}
}
}
pub const UNDERLINE_COLORS_ENV: &str = "CROFT_UNDERLINE_COLORS";
pub fn underline_colors_supported(env: impl Fn(&str) -> Option<String>) -> bool {
match env(UNDERLINE_COLORS_ENV).as_deref().map(str::trim) {
Some("1") => return true,
Some("0") => return false,
_ => {}
}
let var = |name: &str| env(name).unwrap_or_default().to_ascii_lowercase();
const PROGRAMS: &[&str] = &[
"iterm.app",
"wezterm",
"ghostty",
"vscode",
"tmux",
"rio",
"croft",
];
if PROGRAMS.contains(&var("TERM_PROGRAM").as_str()) {
return true;
}
const TERMS: &[&str] = &[
"kitty",
"ghostty",
"alacritty",
"wezterm",
"foot",
"contour",
"rio",
"tmux",
];
let term = var("TERM");
if TERMS.iter().any(|t| term.contains(t)) {
return true;
}
var("VTE_VERSION").parse::<u32>().is_ok_and(|v| v >= 5200)
}
pub fn drop_underline_colors(buffer: &mut Buffer) {
for cell in &mut buffer.content {
cell.underline_color = Color::Reset;
}
}
#[derive(Default)]
pub struct UnderlineColorFilter {
pending: Vec<u8>,
}
impl UnderlineColorFilter {
const LONGEST: usize = 256;
pub fn feed(&mut self, input: &[u8], out: &mut Vec<u8>) {
let joined;
let data: &[u8] = if self.pending.is_empty() {
input
} else {
self.pending.extend_from_slice(input);
joined = std::mem::take(&mut self.pending);
&joined
};
let mut at = 0;
while let Some(found) = memchr::memchr(0x1b, &data[at..]) {
let esc = at + found;
out.extend_from_slice(&data[at..esc]);
if esc + 1 == data.len() {
self.pending.extend_from_slice(&data[esc..]);
return;
}
if data[esc + 1] != b'[' {
out.push(0x1b);
at = esc + 1;
continue;
}
let body = esc + 2;
let Some(end) = data[body..].iter().position(|b| (0x40..=0x7e).contains(b)) else {
if data.len() - esc > Self::LONGEST {
out.extend_from_slice(&data[esc..]);
} else {
self.pending.extend_from_slice(&data[esc..]);
}
return;
};
let fin = body + end;
let params = &data[body..fin];
match (data[fin], without_underline_color(params)) {
(b'm', Some(kept)) if kept.is_empty() => {}
(b'm', Some(kept)) => {
out.extend_from_slice(b"\x1b[");
out.extend_from_slice(&kept);
out.push(b'm');
}
_ => out.extend_from_slice(&data[esc..=fin]),
}
at = fin + 1;
}
out.extend_from_slice(&data[at..]);
}
}
fn without_underline_color(params: &[u8]) -> Option<Vec<u8>> {
if !params
.iter()
.all(|b| b.is_ascii_digit() || *b == b';' || *b == b':')
{
return None;
}
let fields: Vec<&[u8]> = params.split(|b| *b == b';').collect();
let mut kept: Vec<&[u8]> = Vec::with_capacity(fields.len());
let mut changed = false;
let mut i = 0;
while i < fields.len() {
let field = fields[i];
let head = field.split(|b| *b == b':').next().unwrap_or_default();
let span = if field.contains(&b':') {
1
} else {
match (head, fields.get(i + 1).copied()) {
(b"38" | b"48" | b"58", Some(b"5")) => 3,
(b"38" | b"48" | b"58", Some(b"2")) => 5,
_ => 1,
}
};
let group = &fields[i..(i + span).min(fields.len())];
if head == b"58" {
changed = true;
} else {
kept.extend_from_slice(group);
}
i += span;
}
changed.then(|| kept.join(&b';'))
}
const CUBE: [u8; 6] = [0, 95, 135, 175, 215, 255];
fn distance(a: (u8, u8, u8), b: (u8, u8, u8)) -> u32 {
let d = |x: u8, y: u8| (i32::from(x) - i32::from(y)).pow(2) as u32;
d(a.0, b.0) + d(a.1, b.1) + d(a.2, b.2)
}
fn nearest_256(r: u8, g: u8, b: u8) -> u8 {
let level = |v: u8| {
(0..6)
.min_by_key(|&i| (i32::from(CUBE[i]) - i32::from(v)).abs())
.unwrap_or(0)
};
let (ri, gi, bi) = (level(r), level(g), level(b));
let cube_index = 16 + 36 * ri + 6 * gi + bi;
let cube = (CUBE[ri], CUBE[gi], CUBE[bi]);
let avg = (u32::from(r) + u32::from(g) + u32::from(b)) / 3;
let grey_step = ((avg.saturating_sub(8) + 5) / 10).min(23) as u8;
let grey_level = 8 + 10 * grey_step;
let grey = (grey_level, grey_level, grey_level);
if distance((r, g, b), grey) < distance((r, g, b), cube) {
232 + grey_step
} else {
cube_index as u8
}
}
fn palette_256(i: u8) -> (u8, u8, u8) {
if i >= 232 {
let v = 8 + 10 * (i - 232);
return (v, v, v);
}
let i = i.saturating_sub(16) as usize;
(CUBE[i / 36], CUBE[(i / 6) % 6], CUBE[i % 6])
}
fn nearest_16(r: u8, g: u8, b: u8) -> Color {
const ANSI: [(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)),
];
ANSI.iter()
.min_by_key(|(_, rgb)| distance((r, g, b), *rgb))
.map_or(Color::Reset, |(c, _)| *c)
}
#[cfg(test)]
mod tests {
use super::ColorDepth;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::Color;
fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
move |name| {
vars.iter()
.find(|(k, _)| *k == name)
.map(|(_, v)| v.to_string())
}
}
#[test]
fn colorterm_truecolor_is_truecolor() {
for value in ["truecolor", "24bit", "TrueColor"] {
assert_eq!(
ColorDepth::detect(env(&[("COLORTERM", value), ("TERM", "xterm-256color")])),
ColorDepth::TrueColor,
"{value}"
);
}
}
#[test]
fn a_256color_term_without_colorterm_is_256() {
assert_eq!(
ColorDepth::detect(env(&[("TERM", "xterm-256color")])),
ColorDepth::Ansi256
);
assert_eq!(
ColorDepth::detect(env(&[
("TERM", "xterm-256color"),
("TERM_PROGRAM", "Apple_Terminal")
])),
ColorDepth::Ansi256
);
assert_eq!(
ColorDepth::detect(env(&[("TERM", "screen-256color")])),
ColorDepth::Ansi256
);
}
#[test]
fn the_linux_console_and_unknown_terms_are_16() {
assert_eq!(
ColorDepth::detect(env(&[("TERM", "linux")])),
ColorDepth::Ansi16
);
assert_eq!(ColorDepth::detect(env(&[])), ColorDepth::Ansi16);
}
#[test]
fn known_truecolor_terminals_keep_truecolor_without_colorterm() {
for vars in [
[("TERM", "xterm-ghostty"), ("TERM_PROGRAM", "")],
[("TERM", "xterm-kitty"), ("TERM_PROGRAM", "")],
[("TERM", "alacritty"), ("TERM_PROGRAM", "")],
[("TERM", "xterm-256color"), ("TERM_PROGRAM", "iTerm.app")],
[("TERM", "xterm-256color"), ("TERM_PROGRAM", "WezTerm")],
[("TERM", "xterm-256color"), ("TERM_PROGRAM", "vscode")],
[("TERM", "tmux-256color"), ("TERM_PROGRAM", "tmux")],
[("TERM", "xterm-256color"), ("WT_SESSION", "abc")],
] {
assert_eq!(
ColorDepth::detect(env(&vars)),
ColorDepth::TrueColor,
"{vars:?}"
);
}
}
#[test]
fn the_setting_names_a_depth() {
assert_eq!(
ColorDepth::from_setting("truecolor"),
Some(ColorDepth::TrueColor)
);
assert_eq!(ColorDepth::from_setting("256"), Some(ColorDepth::Ansi256));
assert_eq!(ColorDepth::from_setting("16"), Some(ColorDepth::Ansi16));
assert_eq!(ColorDepth::from_setting("auto"), None);
assert_eq!(ColorDepth::from_setting("88"), None);
}
#[test]
fn at_256_colours_rgb_maps_to_the_nearest_palette_index() {
let d = ColorDepth::Ansi256;
assert_eq!(d.fit(Color::Rgb(0x1e, 0x1e, 0x1e)), Color::Indexed(234));
assert_eq!(d.fit(Color::Rgb(0, 0, 0)), Color::Indexed(16));
assert_eq!(d.fit(Color::Rgb(255, 255, 255)), Color::Indexed(231));
assert_eq!(d.fit(Color::Rgb(255, 0, 0)), Color::Indexed(196));
assert_eq!(d.fit(Color::Rgb(0x56, 0x9c, 0xd6)), Color::Indexed(74));
}
#[test]
fn at_16_colours_rgb_and_high_indexes_map_to_ansi_names() {
let d = ColorDepth::Ansi16;
assert_eq!(d.fit(Color::Rgb(0x1e, 0x1e, 0x1e)), Color::Black);
assert_eq!(d.fit(Color::Rgb(250, 10, 10)), Color::LightRed);
assert_eq!(d.fit(Color::Indexed(231)), Color::White);
assert_eq!(d.fit(Color::Indexed(1)), Color::Indexed(1));
}
#[test]
fn named_and_reset_colours_pass_through() {
for d in [ColorDepth::Ansi256, ColorDepth::Ansi16] {
for c in [Color::Reset, Color::Red, Color::Indexed(7)] {
assert_eq!(d.fit(c), c, "{d:?} {c:?}");
}
}
assert_eq!(
ColorDepth::Ansi256.fit(Color::Indexed(200)),
Color::Indexed(200)
);
}
#[test]
fn a_frame_below_truecolor_holds_no_rgb() {
let mut buf = Buffer::empty(Rect::new(0, 0, 3, 1));
for cell in &mut buf.content {
cell.fg = Color::Rgb(0x1e, 0x1e, 0x1e);
cell.bg = Color::Rgb(0, 0, 0);
cell.underline_color = Color::Rgb(255, 0, 0);
}
ColorDepth::Ansi256.fit_buffer(&mut buf);
for cell in &buf.content {
assert_eq!(cell.fg, Color::Indexed(234));
assert_eq!(cell.bg, Color::Indexed(16));
assert_eq!(cell.underline_color, Color::Indexed(196));
}
}
#[test]
fn underline_colours_go_only_to_terminals_that_read_them() {
use super::underline_colors_supported as reads;
assert!(!reads(env(&[("TERM", "xterm")])));
assert!(!reads(env(&[
("TERM", "xterm-256color"),
("COLORTERM", "truecolor")
])));
assert!(!reads(env(&[("TERM", "linux")])));
assert!(!reads(env(&[("TERM", "screen-256color")])));
assert!(!reads(env(&[
("TERM_PROGRAM", "Apple_Terminal"),
("TERM", "xterm-256color")
])));
assert!(!reads(env(&[])));
for (k, v) in [
("TERM_PROGRAM", "iTerm.app"),
("TERM_PROGRAM", "WezTerm"),
("TERM_PROGRAM", "ghostty"),
("TERM_PROGRAM", "vscode"),
("TERM_PROGRAM", "tmux"),
("TERM_PROGRAM", "croft"),
("TERM", "xterm-kitty"),
("TERM", "alacritty"),
("TERM", "foot"),
("TERM", "tmux-256color"),
] {
assert!(reads(env(&[(k, v)])), "{k}={v}");
}
assert!(reads(env(&[
("TERM", "xterm-256color"),
("VTE_VERSION", "7600")
])));
assert!(!reads(env(&[
("TERM", "xterm-256color"),
("VTE_VERSION", "5000")
])));
}
#[test]
fn the_carried_answer_wins() {
use super::{UNDERLINE_COLORS_ENV, underline_colors_supported as reads};
assert!(reads(env(&[
("TERM", "xterm"),
(UNDERLINE_COLORS_ENV, "1")
])));
assert!(!reads(env(&[
("TERM_PROGRAM", "ghostty"),
(UNDERLINE_COLORS_ENV, "0")
])));
assert!(reads(env(&[
("TERM_PROGRAM", "ghostty"),
(UNDERLINE_COLORS_ENV, "maybe")
])));
}
#[test]
fn dropping_underline_colours_keeps_the_underline() {
use ratatui::style::Modifier;
let mut buf = Buffer::empty(Rect::new(0, 0, 2, 1));
buf.content[0].underline_color = Color::Rgb(0x4f, 0xb1, 0xa6);
buf.content[0].modifier = Modifier::UNDERLINED;
buf.content[0].fg = Color::Rgb(1, 2, 3);
super::drop_underline_colors(&mut buf);
assert_eq!(buf.content[0].underline_color, Color::Reset);
assert_eq!(buf.content[0].modifier, Modifier::UNDERLINED);
assert_eq!(buf.content[0].fg, Color::Rgb(1, 2, 3));
}
fn filtered(chunks: &[&[u8]]) -> Vec<u8> {
let mut filter = super::UnderlineColorFilter::default();
let mut out = Vec::new();
for chunk in chunks {
filter.feed(chunk, &mut out);
}
out
}
#[test]
fn the_filter_removes_underline_colours_and_nothing_else() {
let cases: &[(&[u8], &[u8])] = &[
(b"a\x1b[58;5;8mb", b"ab"),
(b"a\x1b[58;2;1;2;3mb", b"ab"),
(b"a\x1b[58:2::1:2:3mb", b"ab"),
(b"\x1b[4;58;5;8mx", b"\x1b[4mx"),
(b"\x1b[1;58;2;9;9;9;3mx", b"\x1b[1;3mx"),
(b"\x1b[38;5;58mx", b"\x1b[38;5;58mx"),
(b"\x1b[48;2;58;58;58mx", b"\x1b[48;2;58;58;58mx"),
(b"\x1b[59m\x1b[m\x1b[0m", b"\x1b[59m\x1b[m\x1b[0m"),
(b"\x1b[58;5H\x1b[?2026h", b"\x1b[58;5H\x1b[?2026h"),
(
b"\x1bP0;1;0q#58;2;1;2;3~\x1b\\",
b"\x1bP0;1;0q#58;2;1;2;3~\x1b\\",
),
(
b"\x1b]1337;File=inline=1:AAAA\x07",
b"\x1b]1337;File=inline=1:AAAA\x07",
),
(
"caf\u{e9} \u{2014}".as_bytes(),
"caf\u{e9} \u{2014}".as_bytes(),
),
];
for (input, want) in cases {
assert_eq!(
filtered(&[input]),
want.to_vec(),
"{}",
String::from_utf8_lossy(input)
);
}
}
#[test]
fn the_filter_gives_the_same_bytes_however_the_stream_is_cut() {
let stream: &[u8] =
b"tab \x1b[3m\x1b[4m\x1b[58;5;8mname\x1b[24m\x1b[59m rest\x1b[38;5;58m!\x1b[0m\x1b";
let whole = filtered(&[stream]);
assert!(
!String::from_utf8_lossy(&whole).contains("[58;"),
"{whole:?}"
);
for cut in 0..=stream.len() {
let (a, b) = stream.split_at(cut);
assert_eq!(filtered(&[a, b]), whole, "cut at {cut}");
}
let bytes: Vec<&[u8]> = stream.chunks(1).collect();
assert_eq!(filtered(&bytes), whole, "one byte at a time");
}
#[test]
fn a_truecolor_frame_is_unchanged() {
let mut buf = Buffer::empty(Rect::new(0, 0, 2, 1));
buf.content[0].fg = Color::Rgb(1, 2, 3);
let before = buf.clone();
ColorDepth::TrueColor.fit_buffer(&mut buf);
assert_eq!(buf, before);
}
}