use crate::cp437;
use crate::palette::ANSI_TO_VGA;
use crate::screen::{Cell, Color, DEFAULT_BG, DEFAULT_FG, flags};
pub fn text(lines: &[&[Cell]]) -> String {
let mut out: Vec<String> =
lines.iter().map(|row| row.iter().map(|c| glyph(c.ch)).collect::<String>().trim_end().to_string()).collect();
while out.last().is_some_and(String::is_empty) {
out.pop();
}
let mut s = out.join("\n");
if !s.is_empty() {
s.push('\n');
}
s
}
#[derive(Clone, Copy, Debug, Default)]
pub struct AnsiOptions {
pub ice: bool,
pub unicode: bool,
}
pub fn ansi(lines: &[&[Cell]], opts: AnsiOptions) -> Vec<u8> {
let mut out = Vec::new();
if opts.ice {
out.extend_from_slice(b"\x1b[?33h");
}
out.extend_from_slice(b"\x1b[0m");
let last = lines.iter().rposition(|row| row.iter().any(|c| !blank(c))).map_or(0, |i| i + 1);
let default = Cell::default();
for row in &lines[..last] {
let end = row.iter().rposition(|c| !blank(c)).map_or(0, |i| i + 1);
let mut pen = default;
for c in &row[..end] {
if !same_attrs(c, &pen) {
sgr(c, &mut out);
pen = *c;
}
if opts.unicode {
let mut buf = [0; 4];
out.extend_from_slice(glyph(c.ch).encode_utf8(&mut buf).as_bytes());
} else {
out.push(safe_byte(c.ch));
}
}
if !same_attrs(&pen, &default) {
out.extend_from_slice(b"\x1b[0m");
}
out.extend_from_slice(b"\r\n");
}
out
}
fn glyph(ch: u8) -> char {
if ch == 0 { ' ' } else { cp437::to_unicode(ch) }
}
fn safe_byte(ch: u8) -> u8 {
match ch {
0 | 7 | 8 | 9 | 10 | 12 | 13 | 26 | 27 => b' ',
c => c,
}
}
fn blank(c: &Cell) -> bool {
c.is_blank() && c.flags & (flags::UNDERLINE | flags::BLINK) == 0
}
fn same_attrs(a: &Cell, b: &Cell) -> bool {
a.fg == b.fg && a.bg == b.bg && a.flags == b.flags
}
fn sgr(c: &Cell, out: &mut Vec<u8>) {
let mut p: Vec<String> = vec!["0".into()];
let f = c.flags;
let bright_fg = matches!(c.fg, Color::Pc(i) if i >= 8);
for (bit, code) in
[(flags::BOLD, "1"), (flags::FAINT, "2"), (flags::UNDERLINE, "4"), (flags::BLINK, "5"), (flags::REVERSE, "7")]
{
if f & bit != 0 || bit == flags::BOLD && bright_fg {
p.push(code.into());
}
}
if f & flags::CONCEAL != 0 {
p.push("8".into());
}
match c.fg {
DEFAULT_FG => {}
Color::Pc(i) => p.push(format!("{}", 30 + vga_to_ansi(i & 7))),
Color::Xterm(i) => p.push(format!("38;5;{i}")),
Color::Rgb(rgb) => p.push(format!("38;2;{};{};{}", rgb >> 16 & 0xFF, rgb >> 8 & 0xFF, rgb & 0xFF)),
}
match c.bg {
DEFAULT_BG => {}
Color::Pc(i) if i >= 8 => p.push(format!("{}", 100 + vga_to_ansi(i & 7))),
Color::Pc(i) => p.push(format!("{}", 40 + vga_to_ansi(i))),
Color::Xterm(i) => p.push(format!("48;5;{i}")),
Color::Rgb(rgb) => p.push(format!("48;2;{};{};{}", rgb >> 16 & 0xFF, rgb >> 8 & 0xFF, rgb & 0xFF)),
}
out.extend_from_slice(format!("\x1b[{}m", p.join(";")).as_bytes());
}
fn vga_to_ansi(i: u8) -> u8 {
ANSI_TO_VGA[i as usize & 7]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ansi::Terminal;
fn rows(t: &Terminal) -> Vec<&[Cell]> {
(0..t.screen.rows()).map(|y| t.screen.row(y)).collect()
}
#[test]
fn plain_text() {
let mut t = Terminal::new(20, 5, 0);
t.feed(b"\x1b[1;31mHello\x1b[0m \r\n\r\n\xc9\xcd\xbb\r\n");
assert_eq!(text(&rows(&t)), "Hello\n\n\u{2554}\u{2550}\u{2557}\n");
}
#[test]
fn ansi_round_trips_through_the_terminal() {
let mut t = Terminal::new(40, 6, 0);
t.feed(b"\x1b[1;33;44mBold yellow on blue\x1b[0m plain\r\n");
t.feed(b"\x1b[5;31;47mblink\x1b[0m \x1b[38;5;196mxterm\x1b[38;2;1;2;3m rgb\x1b[0m\r\n");
t.feed(b"\x1b[92mbright\x1b[0m \x1b[104mbg\x1b[0m \x1b[4munder\x1b[7mrev\x1b[0m\r\n");
t.feed(b"\x1b[41m \x1b[0m\x1b[30C\xdb\x1b[K");
let data = ansi(&rows(&t), AnsiOptions::default());
let mut back = Terminal::new(40, 6, 0);
back.feed(&data);
for y in 0..6 {
for x in 0..40 {
let (a, b) = (t.screen.row(y)[x], back.screen.row(y)[x]);
assert_eq!(a.ch, b.ch, "glyph at {x},{y}");
assert_eq!(a.resolve(false), b.resolve(false), "colors at {x},{y}");
}
}
}
#[test]
fn options_and_safety() {
let mut t = Terminal::new(10, 2, 0);
t.screen.put(0x1B);
t.screen.put(0x01);
let raw = ansi(&rows(&t), AnsiOptions { ice: true, unicode: false });
assert_eq!(raw, b"\x1b[?33h\x1b[0m \x01\r\n");
let uni = ansi(&rows(&t), AnsiOptions { ice: false, unicode: true });
assert_eq!(String::from_utf8(uni).unwrap(), "\x1b[0m\u{2190}\u{263A}\r\n");
assert_eq!(ansi(&rows(&Terminal::new(10, 2, 0)), AnsiOptions::default()), b"\x1b[0m");
}
}