use std::fmt::Write as _;
use std::rc::Rc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub(crate) enum Colour {
#[default]
Default,
Basic(u8),
Indexed(u8),
Rgb(u8, u8, u8),
}
pub(crate) mod attr {
pub(crate) const BOLD: u8 = 1;
pub(crate) const FAINT: u8 = 1 << 1;
pub(crate) const ITALIC: u8 = 1 << 2;
pub(crate) const BLINK: u8 = 1 << 3;
pub(crate) const RAPID_BLINK: u8 = 1 << 4;
pub(crate) const REVERSE: u8 = 1 << 5;
pub(crate) const CONCEAL: u8 = 1 << 6;
pub(crate) const STRIKE: u8 = 1 << 7;
}
const ATTRIBUTES: [(u8, u8, u8); 8] = [
(attr::BOLD, 1, 22),
(attr::FAINT, 2, 22),
(attr::ITALIC, 3, 23),
(attr::BLINK, 5, 25),
(attr::RAPID_BLINK, 6, 25),
(attr::REVERSE, 7, 27),
(attr::CONCEAL, 8, 28),
(attr::STRIKE, 9, 29),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub(crate) struct Pen {
pub(crate) fg: Colour,
pub(crate) bg: Colour,
pub(crate) underline_colour: Colour,
pub(crate) attrs: u8,
pub(crate) underline: u8,
}
pub(crate) type Link = Option<Rc<str>>;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Glyph {
Char(char),
Cluster(Box<str>),
Continuation,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct Cell {
pub(crate) glyph: Glyph,
pub(crate) width: u8,
pub(crate) pen: Pen,
pub(crate) link: Link,
}
impl Cell {
pub(crate) const BLANK: Self = Self {
glyph: Glyph::Char(' '),
width: 1,
pen: Pen::DEFAULT,
link: None,
};
pub(crate) fn new(text: &str, width: u8, pen: Pen, link: Link) -> Self {
let mut chars = text.chars();
let glyph = match (chars.next(), chars.next()) {
(Some(c), None) => Glyph::Char(c),
_ => Glyph::Cluster(text.into()),
};
Self {
glyph,
width,
pen,
link,
}
}
pub(crate) fn continuation(pen: Pen, link: Link) -> Self {
Self {
glyph: Glyph::Continuation,
width: 0,
pen,
link,
}
}
pub(crate) fn is_blank(&self) -> bool {
*self == Self::BLANK
}
pub(crate) fn is_continuation(&self) -> bool {
self.glyph == Glyph::Continuation
}
pub(crate) fn push_text(&self, out: &mut String) {
match &self.glyph {
Glyph::Char(c) => out.push(*c),
Glyph::Cluster(s) => out.push_str(s),
Glyph::Continuation => {}
}
}
pub(crate) fn append(&mut self, mark: &str) {
let mut text = String::new();
self.push_text(&mut text);
text.push_str(mark);
self.glyph = Glyph::Cluster(text.into());
}
}
impl Pen {
pub(crate) const DEFAULT: Self = Self {
fg: Colour::Default,
bg: Colour::Default,
underline_colour: Colour::Default,
attrs: 0,
underline: 0,
};
pub(crate) fn apply_sgr(&mut self, params: &str) {
let list: Vec<&str> = params.split(';').collect();
let mut i = 0;
while i < list.len() {
i += self.apply_one(&list, i);
}
}
fn apply_one(&mut self, list: &[&str], i: usize) -> usize {
let mut parts = list[i].split(':');
let code = number(parts.next().unwrap_or(""));
let sub: Vec<&str> = parts.collect();
match code {
38 | 48 | 58 => {
let (colour, used) = read_colour(&sub, &list[i + 1..]);
self.set_colour(code, colour);
1 + used
}
4 => {
self.underline = match sub.first().map(|s| number(s)) {
Some(n @ 0..=5) => u8::try_from(n).unwrap_or(1),
_ => 1,
};
1
}
_ => {
self.apply_code(code);
1
}
}
}
fn set_colour(&mut self, code: u32, colour: Option<Colour>) {
let Some(colour) = colour else { return };
match code {
38 => self.fg = colour,
48 => self.bg = colour,
_ => self.underline_colour = colour,
}
}
fn apply_code(&mut self, code: u32) {
if let Some((bit, _, _)) = ATTRIBUTES.iter().find(|a| u32::from(a.1) == code) {
self.attrs |= bit;
return;
}
if let Some(reset) = ATTRIBUTES
.iter()
.find(|a| u32::from(a.2) == code)
.map(|a| a.2)
{
for (bit, _, off) in ATTRIBUTES {
if off == reset {
self.attrs &= !bit;
}
}
return;
}
self.apply_colour_code(code);
}
fn apply_colour_code(&mut self, code: u32) {
if let Some((colour, background)) = basic_colour(code) {
if background {
self.bg = colour;
} else {
self.fg = colour;
}
return;
}
match code {
0 => *self = Self::DEFAULT,
24 => self.underline = 0,
39 => self.fg = Colour::Default,
49 => self.bg = Colour::Default,
59 => self.underline_colour = Colour::Default,
_ => {}
}
}
pub(crate) fn transition(&self, to: &Self) -> String {
if self == to {
return String::new();
}
if *to == Self::DEFAULT {
return "\x1b[m".to_string();
}
let mut codes = String::new();
let from = if self.must_reset(to) {
codes.push('0');
Self::DEFAULT
} else {
*self
};
from.push_changes(to, &mut codes);
format!("\x1b[{codes}m")
}
fn must_reset(&self, to: &Self) -> bool {
let off = |a: Colour, b: Colour| a != Colour::Default && b == Colour::Default;
self.attrs & !to.attrs != 0
|| (self.underline != 0 && to.underline == 0)
|| off(self.fg, to.fg)
|| off(self.bg, to.bg)
|| off(self.underline_colour, to.underline_colour)
}
fn push_changes(&self, to: &Self, codes: &mut String) {
let mut push = |code: &str| {
if !codes.is_empty() {
codes.push(';');
}
codes.push_str(code);
};
for (bit, on, _) in ATTRIBUTES {
if to.attrs & bit != 0 && self.attrs & bit == 0 {
push(&on.to_string());
}
}
if to.underline != self.underline {
push(&underline_code(to.underline));
}
for (code, a, b) in [
(38, self.fg, to.fg),
(48, self.bg, to.bg),
(58, self.underline_colour, to.underline_colour),
] {
if a != b {
push(&colour_code(code, b));
}
}
}
}
fn basic_colour(code: u32) -> Option<(Colour, bool)> {
let (base, bright, background) = match code {
30..=37 => (30, 0, false),
40..=47 => (40, 0, true),
90..=97 => (90, 8, false),
100..=107 => (100, 8, true),
_ => return None,
};
let n = u8::try_from(code - base).ok()?;
Some((Colour::Basic(n + bright), background))
}
fn underline_code(style: u8) -> String {
if style == 1 {
"4".to_string()
} else {
format!("4:{style}")
}
}
fn colour_code(code: u8, c: Colour) -> String {
let mut out = String::new();
match (code, c) {
(38 | 48, Colour::Basic(n)) => {
let base = if code == 38 { 30 } else { 40 };
let n = u16::from(n);
let value = if n < 8 { base + n } else { base + 60 + n - 8 };
let _ = write!(out, "{value}");
}
(_, Colour::Basic(n) | Colour::Indexed(n)) => {
let _ = write!(out, "{code};5;{n}");
}
(_, Colour::Rgb(r, g, b)) => {
let _ = write!(out, "{code};2;{r};{g};{b}");
}
(_, Colour::Default) => {
let _ = write!(out, "{}", code + 1);
}
}
out
}
fn number(s: &str) -> u32 {
s.parse().unwrap_or(0)
}
fn read_colour(sub: &[&str], rest: &[&str]) -> (Option<Colour>, usize) {
if !sub.is_empty() {
return (colon_colour(sub), 0);
}
let value = |i: usize| rest.get(i).map(|s| number(s));
match value(0) {
Some(5) => (value(1).map(indexed), 2),
Some(2) => match (value(1), value(2), value(3)) {
(Some(r), Some(g), Some(b)) => (Some(rgb(r, g, b)), 4),
_ => (None, rest.len().min(4)),
},
_ => (None, 0),
}
}
fn colon_colour(sub: &[&str]) -> Option<Colour> {
let values: Vec<u32> = sub.iter().map(|s| number(s)).collect();
match values.as_slice() {
[5, n, ..] => Some(indexed(*n)),
[2, _, r, g, b, ..] | [2, r, g, b] => Some(rgb(*r, *g, *b)),
_ => None,
}
}
fn indexed(n: u32) -> Colour {
Colour::Indexed(n.to_le_bytes()[0])
}
fn rgb(r: u32, g: u32, b: u32) -> Colour {
Colour::Rgb(r.to_le_bytes()[0], g.to_le_bytes()[0], b.to_le_bytes()[0])
}
#[cfg(test)]
mod tests;