#[cfg(test)]
use crate::theme::quantize_ansi256;
use crate::{AnsiColor, Color, ColorDepth, ResolvedColor, Stream, Theme, TokenId, TokenStyle};
const ESC: &[u8] = b"\x1b[";
const RESET: &[u8] = b"\x1b[0m";
#[derive(Clone, Copy, Eq, PartialEq)]
pub(crate) struct StyleEncoding {
prefix: [u8; 64],
prefix_len: u8,
reset_count: u8,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct AnsiStyle {
foreground: Option<Color>,
background: Option<Color>,
bold: bool,
dim: bool,
underline: bool,
}
impl AnsiStyle {
pub(crate) const fn from_style(style: &TokenStyle) -> Self {
Self {
foreground: style.foreground,
background: style.background,
bold: style.bold,
dim: style.dim,
underline: style.underline,
}
}
}
impl StyleEncoding {
pub(crate) fn prefix(&self) -> &[u8] {
&self.prefix[..usize::from(self.prefix_len)]
}
pub(crate) const fn reset_count(&self) -> u8 {
self.reset_count
}
pub(crate) const fn suffix_len(&self) -> usize {
RESET.len() * self.reset_count as usize
}
}
pub(crate) fn render_text(
theme: &Theme,
token: &TokenId,
text: &str,
depth: ColorDepth,
color_enabled: bool,
stream: Stream,
) -> String {
if !color_enabled || text.is_empty() {
return text.to_owned();
}
let encoding = style_encoding(theme, token, depth, color_enabled, stream);
if encoding.prefix_len == 0 {
return text.to_owned();
}
let mut output =
Vec::with_capacity(encoding.prefix().len() + text.len() + encoding.suffix_len());
output.extend_from_slice(encoding.prefix());
output.extend_from_slice(text.as_bytes());
for _ in 0..encoding.reset_count() {
output.extend_from_slice(RESET);
}
String::from_utf8(output).expect("ANSI rendering preserves UTF-8")
}
pub(crate) fn style_encoding(
theme: &Theme,
token: &TokenId,
depth: ColorDepth,
color_enabled: bool,
_stream: Stream,
) -> StyleEncoding {
let style = theme.resolve(token);
style_encoding_for_style(&style, depth, color_enabled, _stream)
}
pub(crate) fn style_encoding_for_style(
style: &TokenStyle,
depth: ColorDepth,
color_enabled: bool,
_stream: Stream,
) -> StyleEncoding {
let style = AnsiStyle::from_style(style);
if !color_enabled || style == AnsiStyle::default() {
return StyleEncoding {
prefix: [0; 64],
prefix_len: 0,
reset_count: 0,
};
}
let mut encoding = StyleEncoding {
prefix: [0; 64],
prefix_len: 0,
reset_count: 1,
};
if let Some(foreground) = style.foreground {
push_color(&mut encoding, foreground, depth, ColorRole::Foreground);
}
if let Some(background) = style.background {
push_color(&mut encoding, background, depth, ColorRole::Background);
}
if style.bold {
push_sequence(&mut encoding, 1);
}
if style.dim {
push_sequence(&mut encoding, 2);
}
if style.underline {
push_sequence(&mut encoding, 4);
}
encoding
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum ColorRole {
Foreground,
Background,
}
impl ColorRole {
const fn ansi_offset(self) -> u8 {
match self {
Self::Foreground => 0,
Self::Background => 10,
}
}
const fn selector(self) -> u8 {
match self {
Self::Foreground => 38,
Self::Background => 48,
}
}
}
fn push_color(encoding: &mut StyleEncoding, color: Color, depth: ColorDepth, role: ColorRole) {
match color.resolve(depth) {
ResolvedColor::Ansi(color) => push_ansi_color(encoding, color, role),
ResolvedColor::Indexed(index) => {
push_color_values(encoding, &[role.selector(), 5, index]);
}
ResolvedColor::Rgb { red, green, blue } => {
push_color_values(encoding, &[role.selector(), 2, red, green, blue]);
}
}
}
fn push_ansi_color(encoding: &mut StyleEncoding, color: AnsiColor, role: ColorRole) {
let (normal, bright) = match color {
AnsiColor::Black => (30, None),
AnsiColor::Red => (31, None),
AnsiColor::Green => (32, None),
AnsiColor::Yellow => (33, None),
AnsiColor::Blue => (34, None),
AnsiColor::Magenta => (35, None),
AnsiColor::Cyan => (36, None),
AnsiColor::White => (37, None),
AnsiColor::BrightBlack => (30, Some(90)),
AnsiColor::BrightRed => (31, Some(91)),
AnsiColor::BrightGreen => (32, Some(92)),
AnsiColor::BrightYellow => (33, Some(93)),
AnsiColor::BrightBlue => (34, Some(94)),
AnsiColor::BrightMagenta => (35, Some(95)),
AnsiColor::BrightCyan => (36, Some(96)),
AnsiColor::BrightWhite => (37, Some(97)),
};
let offset = role.ansi_offset();
if let Some(bright) = bright {
push_sequence(encoding, normal + offset);
push_sequence(encoding, bright + offset);
encoding.reset_count = 2;
} else {
push_sequence(encoding, normal + offset);
}
}
fn push_color_values(encoding: &mut StyleEncoding, values: &[u8]) {
push_bytes(encoding, ESC);
for (index, value) in values.iter().copied().enumerate() {
if index != 0 {
push_bytes(encoding, b";");
}
push_decimal(encoding, value);
}
push_bytes(encoding, b"m");
}
fn push_sequence(encoding: &mut StyleEncoding, value: u8) {
push_bytes(encoding, ESC);
push_decimal(encoding, value);
push_bytes(encoding, b"m");
}
fn push_decimal(encoding: &mut StyleEncoding, value: u8) {
let hundreds = value / 100;
let tens = (value / 10) % 10;
let ones = value % 10;
if hundreds != 0 {
push_bytes(encoding, &[b'0' + hundreds]);
push_bytes(encoding, &[b'0' + tens]);
} else if tens != 0 {
push_bytes(encoding, &[b'0' + tens]);
}
push_bytes(encoding, &[b'0' + ones]);
}
fn push_bytes(encoding: &mut StyleEncoding, bytes: &[u8]) {
let start = usize::from(encoding.prefix_len);
let end = start + bytes.len();
encoding.prefix[start..end].copy_from_slice(bytes);
encoding.prefix_len = u8::try_from(end).expect("style prefix fits fixed encoder");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rgb_quantization_matches_independent_reference_boundaries() {
let fixture = include_str!("../tests/fixtures/console-color-quantization.toml");
let mut red = None;
let mut green = None;
let mut blue = None;
let mut cases = Vec::new();
for line in fixture.lines() {
let Some((key, value)) = line.split_once(" = ") else {
continue;
};
let parsed = value.parse::<u8>();
match (key, parsed) {
("red", Ok(value)) => red = Some(value),
("green", Ok(value)) => green = Some(value),
("blue", Ok(value)) => blue = Some(value),
("expected_index", Ok(expected)) => {
if let (Some(red), Some(green), Some(blue)) = (red, green, blue) {
cases.push((red, green, blue, expected));
}
red = None;
green = None;
blue = None;
}
_ => {}
}
}
assert_eq!(cases.len(), 9, "fixture case count changed");
for (red, green, blue, expected) in cases {
assert_eq!(
quantize_ansi256(red, green, blue),
expected,
"vector ({red}, {green}, {blue})"
);
assert_eq!(expected, reference_quantize(red, green, blue));
}
}
#[test]
fn pinned_rgb_index_and_direct_ansi_color_are_depth_invariant() {
assert_eq!(quantize_ansi256(255, 85, 85), 203);
let token = TokenId::from_static("status.error.test");
let theme = Theme::inheriting("ansi-depth-test", &crate::themes::default())
.rule(
token.clone(),
TokenStyle::bold(Color::Ansi(AnsiColor::BrightCyan)),
)
.and_then(crate::ThemeBuilder::build)
.expect("valid test theme");
let rendered = [
ColorDepth::Ansi16,
ColorDepth::Ansi256,
ColorDepth::TrueColor,
]
.map(|depth| render_text(&theme, &token, "value", depth, true, Stream::Stdout));
assert_eq!(rendered[0], rendered[1]);
assert_eq!(rendered[1], rendered[2]);
assert!(!rendered[0].contains("38;5;") && !rendered[0].contains("38;2;"));
}
fn reference_quantize(red: u8, green: u8, blue: u8) -> u8 {
let cube = [0u8, 95, 135, 175, 215, 255];
let mut candidates = Vec::new();
for (r, &candidate_red) in cube.iter().enumerate() {
for (g, &candidate_green) in cube.iter().enumerate() {
for (b, &candidate_blue) in cube.iter().enumerate() {
candidates.push((
16 + 36 * r as u8 + 6 * g as u8 + b as u8,
candidate_red,
candidate_green,
candidate_blue,
));
}
}
}
candidates.extend((0u8..=23).map(|index| {
let value = 8 + 10 * index;
(232 + index, value, value, value)
}));
candidates
.into_iter()
.map(|(index, candidate_red, candidate_green, candidate_blue)| {
let red_mean = (u64::from(red) + u64::from(candidate_red)) / 2;
let dr = (i64::from(red) - i64::from(candidate_red)).unsigned_abs();
let dg = (i64::from(green) - i64::from(candidate_green)).unsigned_abs();
let db = (i64::from(blue) - i64::from(candidate_blue)).unsigned_abs();
let distance = (((512 + red_mean) * dr * dr) >> 8)
+ 4 * dg * dg
+ (((767 - red_mean) * db * db) >> 8);
(distance, index)
})
.min()
.map_or(16, |(_, index)| index)
}
fn encode(style: TokenStyle, depth: ColorDepth) -> String {
let encoding = style_encoding_for_style(&style, depth, true, Stream::Stdout);
String::from_utf8(encoding.prefix().to_vec()).expect("ANSI prefix is UTF-8")
}
const SLATE: Color = Color::Rgb {
red: 47,
green: 53,
blue: 73,
fallback: AnsiColor::Blue,
};
#[test]
fn background_uses_the_48_selector_at_every_depth() {
assert_eq!(
encode(TokenStyle::background(SLATE), ColorDepth::TrueColor),
"\u{1b}[48;2;47;53;73m"
);
assert_eq!(
encode(TokenStyle::background(SLATE), ColorDepth::Ansi256),
format!("\u{1b}[48;5;{}m", quantize_ansi256(47, 53, 73))
);
assert_eq!(
encode(TokenStyle::background(SLATE), ColorDepth::Ansi16),
"\u{1b}[44m",
"Ansi16 falls back to the color's declared ANSI background"
);
}
#[test]
fn foreground_and_background_encode_independently() {
let style = TokenStyle::on(Color::Ansi(AnsiColor::White), SLATE);
assert_eq!(
encode(style, ColorDepth::TrueColor),
"\u{1b}[37m\u{1b}[48;2;47;53;73m"
);
}
#[test]
fn a_style_with_both_colors_and_every_attribute_fits_the_fixed_prefix() {
let style = TokenStyle {
foreground: Some(SLATE),
background: Some(SLATE),
bold: true,
dim: true,
underline: true,
..TokenStyle::default()
};
let encoding =
style_encoding_for_style(&style, ColorDepth::TrueColor, true, Stream::Stdout);
assert!(
usize::from(encoding.prefix_len) <= 64,
"the widest style must fit the fixed encoder buffer, got {}",
encoding.prefix_len
);
}
#[test]
fn attributes_alone_produce_no_escape_bytes() {
let style = TokenStyle::default().with_attr(
crate::StyleAttr::from_static("grid.fill"),
crate::AttrValue::Number(1),
);
assert_eq!(
encode(style, ColorDepth::TrueColor),
"",
"Termosaic's writers never interpret backend-owned attributes"
);
}
#[test]
fn bright_ansi_colors_win_over_their_normal_fallback() {
assert_eq!(
encode(
TokenStyle::foreground(Color::Ansi(AnsiColor::BrightBlue)),
ColorDepth::Ansi16
),
"\u{1b}[34m\u{1b}[94m"
);
assert_eq!(
encode(
TokenStyle::background(Color::Ansi(AnsiColor::BrightBlue)),
ColorDepth::Ansi16
),
"\u{1b}[44m\u{1b}[104m"
);
}
#[test]
fn non_bright_ansi_colors_emit_a_single_sequence() {
assert_eq!(
encode(
TokenStyle::foreground(Color::Ansi(AnsiColor::Blue)),
ColorDepth::Ansi16
),
"\u{1b}[34m"
);
assert_eq!(
encode(
TokenStyle::background(Color::Ansi(AnsiColor::Blue)),
ColorDepth::Ansi16
),
"\u{1b}[44m"
);
}
#[test]
fn every_bright_value_pairs_with_its_own_normal_code() {
for (bright, normal) in [
(AnsiColor::BrightBlack, AnsiColor::Black),
(AnsiColor::BrightRed, AnsiColor::Red),
(AnsiColor::BrightGreen, AnsiColor::Green),
(AnsiColor::BrightYellow, AnsiColor::Yellow),
(AnsiColor::BrightBlue, AnsiColor::Blue),
(AnsiColor::BrightMagenta, AnsiColor::Magenta),
(AnsiColor::BrightCyan, AnsiColor::Cyan),
(AnsiColor::BrightWhite, AnsiColor::White),
] {
let bright_encoding = encode(
TokenStyle::foreground(Color::Ansi(bright)),
ColorDepth::Ansi16,
);
let normal_encoding = encode(
TokenStyle::foreground(Color::Ansi(normal)),
ColorDepth::Ansi16,
);
assert!(
bright_encoding.starts_with(&normal_encoding),
"{bright:?} must lead with the {normal:?} fallback, got {bright_encoding:?}"
);
assert!(
bright_encoding.len() > normal_encoding.len(),
"{bright:?} must add the aixterm code after its fallback"
);
}
}
}