curd-editor 0.6.0

A small terminal code editor: projects with a file tree, git status, tabs, quick open and language-server support
//! What goes on the screen, and getting it there.
//!
//! Every part of the editor describes its piece of the screen as rows of
//! styled text. `Screen` remembers the last frame it drew and rewrites only
//! the rows that changed.

use std::io::{stdout, BufWriter, Write};

use crossterm::{
    cursor::{Hide, MoveTo, Show},
    queue,
    style::{Attribute, Color, Print, ResetColor, SetAttribute, SetForegroundColor},
    terminal::{BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate},
};

use crate::highlight::TokenKind;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Style {
    Plain,
    Dim,
    Bold,
    Reverse,
    Error,
    Warning,
    /// Text in one of the terminal's colours.
    Colored(Color),
    /// Code with a colour or a decoration from the language server.
    Code(Decoration),
}

/// How one character of code is dressed up.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Decoration {
    /// Gives the colour: keyword, string and so on.
    pub kind: Option<TokenKind>,
    /// An error or warning covers this character.
    pub underlined: bool,
    /// Unused code.
    pub faded: bool,
    /// Deprecated code.
    pub struck: bool,
}

/// The colour for each kind of code. These are the terminal's own sixteen
/// colours, so they follow whatever theme the terminal uses.
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,
    }
}

/// A piece of a screen row drawn in one style.
#[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>;

/// Cuts or pads `text` to exactly `width` characters.
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
}

/// The terminal screen as it was last drawn.
#[derive(Default)]
pub struct Screen {
    last_frame: Vec<Row>,
    last_size: (usize, usize),
}

impl Screen {
    /// Updates the terminal to show `frame`, rewriting only the rows that
    /// differ from what is already there, and puts the cursor at `cursor`
    /// (column, row) or hides it.
    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());

        // A synchronized update asks the terminal to show the new frame in
        // one go, so a half-drawn screen is never visible. Terminals that
        // do not know the request ignore it.
        queue!(out, BeginSynchronizedUpdate, Hide)?;
        if self.last_size != size {
            // The window was resized: nothing on screen can be trusted.
            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::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))?;
                        }
                    }
                }
                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()
    }
}