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;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Style {
Plain,
Dim,
Bold,
Reverse,
Error,
Warning,
Colored(Color),
Menu,
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,
}
fn color_of(kind: TokenKind) -> Color {
match kind {
TokenKind::Keyword => Color::Magenta,
TokenKind::Function => Color::Blue,
TokenKind::Type => Color::Cyan,
TokenKind::String => Color::Green,
TokenKind::Constant => Color::DarkYellow,
TokenKind::Comment => Color::DarkGrey,
TokenKind::Macro => Color::DarkCyan,
TokenKind::Namespace => Color::DarkGreen,
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Span {
pub style: Style,
pub text: String,
}
impl Span {
pub fn new(style: Style, text: impl Into<String>) -> Self {
Self {
style,
text: text.into(),
}
}
}
pub type Row = Vec<Span>;
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, char)> = row
.iter()
.flat_map(|span| span.text.chars().map(|c| (span.style, c)))
.collect();
if cells.len() < x {
cells.resize(x, (Style::Plain, ' '));
}
let end = (x + piece.text.chars().count()).min(cells.len());
cells.splice(x..end, piece.text.chars().map(|c| (piece.style, c)));
row.clear();
for (style, c) in cells {
match row.last_mut() {
Some(last) if last.style == style => last.text.push(c),
_ => row.push(Span::new(style, c.to_string())),
}
}
}
#[derive(Default)]
pub struct Screen {
last_frame: Vec<Row>,
last_size: (usize, usize),
}
impl Screen {
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());
queue!(out, BeginSynchronizedUpdate, Hide)?;
if self.last_size != size {
queue!(out, Clear(ClearType::All))?;
self.last_frame.clear();
self.last_size = size;
}
for (y, row) in frame.iter().enumerate() {
if self.last_frame.get(y) == Some(row) {
continue;
}
queue!(out, MoveTo(0, y as u16), Clear(ClearType::UntilNewLine))?;
for span in row {
match span.style {
Style::Plain => {}
Style::Dim => queue!(out, SetAttribute(Attribute::Dim))?,
Style::Bold => queue!(out, SetAttribute(Attribute::Bold))?,
Style::Reverse => queue!(out, SetAttribute(Attribute::Reverse))?,
Style::Error => queue!(out, SetForegroundColor(Color::Red))?,
Style::Warning => queue!(out, SetForegroundColor(Color::Yellow))?,
Style::Colored(color) => queue!(out, SetForegroundColor(color))?,
Style::Menu => queue!(
out,
SetBackgroundColor(Color::DarkGrey),
SetForegroundColor(Color::White)
)?,
Style::Code(decoration) => {
if let Some(kind) = decoration.kind {
queue!(out, SetForegroundColor(color_of(kind)))?;
}
if decoration.underlined {
queue!(out, SetAttribute(Attribute::Underlined))?;
}
if decoration.faded {
queue!(out, SetAttribute(Attribute::Dim))?;
}
if decoration.struck {
queue!(out, SetAttribute(Attribute::CrossedOut))?;
}
if decoration.marked {
queue!(out, SetAttribute(Attribute::Reverse))?;
}
}
}
queue!(out, Print(&span.text))?;
if span.style != Style::Plain {
queue!(out, SetAttribute(Attribute::Reset), ResetColor)?;
}
}
}
self.last_frame = frame;
if let Some((x, y)) = cursor {
queue!(out, MoveTo(x as u16, y as u16), Show)?;
}
queue!(out, EndSynchronizedUpdate)?;
out.flush()
}
}