use std::io::{stdout, BufWriter, Write};
use crossterm::{
cursor::{Hide, MoveTo, Show},
queue,
style::{
Attribute, Color, Print, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor,
},
terminal::{BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate},
};
use crate::highlight::TokenKind;
use crate::theme::{Look, Theme};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Style {
Plain,
Dim,
Bold,
Error,
Warning,
Colored(Color),
Menu,
Bar,
BarBold,
BarWarn,
BarError,
BarDim,
Title,
Selected,
TabActive,
Tab,
Input,
LineNumber(bool),
Border,
Accent,
Field,
FieldNote,
Code(Decoration),
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Decoration {
pub kind: Option<TokenKind>,
pub underlined: bool,
pub faded: bool,
pub struck: bool,
pub marked: bool,
pub current: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Zone {
#[default]
Text,
Side,
Panel,
Popup,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Span {
pub style: Style,
pub text: String,
pub zone: Zone,
}
impl Span {
pub fn new(style: Style, text: impl Into<String>) -> Self {
Self {
style,
text: text.into(),
zone: Zone::Text,
}
}
}
pub fn place(rows: &mut [Row], zone: Zone) {
for span in rows.iter_mut().flatten() {
span.zone = zone;
}
}
pub type Row = Vec<Span>;
pub const TAB_STOP: usize = 4;
pub const WIDE_PAD: char = '\0';
pub fn cells(text: &str) -> Vec<(usize, char)> {
use unicode_width::UnicodeWidthChar;
let mut cells = Vec::with_capacity(text.len());
for (index, c) in text.chars().enumerate() {
match c {
'\t' => {
let spaces = TAB_STOP - cells.len() % TAB_STOP;
cells.extend(std::iter::repeat_n((index, ' '), spaces));
}
c => match c.width() {
Some(2) => cells.extend([(index, c), (index, WIDE_PAD)]),
Some(0) | None => {}
Some(_) => cells.push((index, c)),
},
}
}
cells
}
pub fn widen(text: &str) -> String {
if text.bytes().all(|byte| (b' '..0x7f).contains(&byte)) {
return text.to_string();
}
cells(text).into_iter().map(|(_, c)| c).collect()
}
pub fn fit(text: &str, width: usize) -> String {
let mut fitted: String = text.chars().take(width).collect();
let padding = width - fitted.chars().count();
fitted.push_str(&" ".repeat(padding));
fitted
}
pub fn overlay(row: &mut Row, x: usize, piece: &Span) {
let mut cells: Vec<(Style, Zone, char)> = row
.iter()
.flat_map(|span| span.text.chars().map(|c| (span.style, span.zone, c)))
.collect();
if cells.len() < x {
cells.resize(x, (Style::Plain, Zone::Text, ' '));
}
let end = (x + piece.text.chars().count()).min(cells.len());
if x > 0 && cells.get(x).is_some_and(|cell| cell.2 == WIDE_PAD) {
cells[x - 1].2 = ' ';
}
if cells.get(end).is_some_and(|cell| cell.2 == WIDE_PAD) {
cells[end].2 = ' ';
}
cells.splice(x..end, piece.text.chars().map(|c| (piece.style, piece.zone, c)));
row.clear();
for (style, zone, c) in cells {
match row.last_mut() {
Some(last) if last.style == style && last.zone == zone => last.text.push(c),
_ => row.push(Span { style, zone, text: c.to_string() }),
}
}
}
fn change_look(out: &mut impl Write, current: &mut Look, look: Look) -> std::io::Result<()> {
let attributes = |look: &Look| {
[
(look.bold, Attribute::Bold),
(look.dim, Attribute::Dim),
(look.italic, Attribute::Italic),
(look.underlined, Attribute::Underlined),
(look.struck, Attribute::CrossedOut),
(look.reverse, Attribute::Reverse),
]
};
let start_over = attributes(current) != attributes(&look)
|| (current.fg.is_some() && look.fg.is_none())
|| (current.bg.is_some() && look.bg.is_none());
if start_over {
queue!(out, SetAttribute(Attribute::Reset))?;
*current = Look::default();
for (_, attribute) in attributes(&look).iter().filter(|(wanted, _)| *wanted) {
queue!(out, SetAttribute(*attribute))?;
}
}
if let Some(color) = look.fg.filter(|_| current.fg != look.fg) {
queue!(out, SetForegroundColor(color))?;
}
if let Some(color) = look.bg.filter(|_| current.bg != look.bg) {
queue!(out, SetBackgroundColor(color))?;
}
*current = look;
Ok(())
}
#[derive(Default)]
pub struct Screen {
last_frame: Vec<Row>,
last_size: (usize, usize),
pub theme: Theme,
}
impl Screen {
pub fn with_theme(theme: Theme) -> Self {
Self {
theme,
..Self::default()
}
}
pub fn draw(
&mut self,
frame: Vec<Row>,
size: (usize, usize),
cursor: Option<(usize, usize)>,
) -> std::io::Result<()> {
let mut out = BufWriter::new(stdout().lock());
self.write(&mut out, frame, size, cursor)?;
out.flush()
}
pub fn write(
&mut self,
out: &mut impl Write,
frame: Vec<Row>,
size: (usize, usize),
cursor: Option<(usize, usize)>,
) -> std::io::Result<()> {
queue!(out, BeginSynchronizedUpdate, Hide)?;
if self.last_size != size {
if let Some(color) = self.theme.background(Zone::Text) {
queue!(out, SetBackgroundColor(color))?;
}
queue!(out, Clear(ClearType::All), ResetColor)?;
self.last_frame.clear();
self.last_size = size;
}
let base = self.theme.background(Zone::Text);
let mut current = Look::default();
queue!(out, SetAttribute(Attribute::Reset))?;
for (y, row) in frame.iter().enumerate() {
if self.last_frame.get(y) == Some(row) {
continue;
}
queue!(out, MoveTo(0, y as u16))?;
let mut rest = base;
for span in row {
let look = self.theme.look(span.style, span.zone);
change_look(out, &mut current, look)?;
if span.text.contains(WIDE_PAD) {
queue!(out, Print(span.text.replace(WIDE_PAD, "")))?;
} else {
queue!(out, Print(&span.text))?;
}
rest = look.bg.filter(|_| !look.reverse).or(base);
}
change_look(out, &mut current, Look { bg: rest, ..Look::default() })?;
queue!(out, Clear(ClearType::UntilNewLine))?;
}
queue!(out, SetAttribute(Attribute::Reset))?;
self.last_frame = frame;
if let Some((x, y)) = cursor {
queue!(out, MoveTo(x as u16, y as u16), Show)?;
}
queue!(out, EndSynchronizedUpdate)?;
Ok(())
}
}