curd-editor 0.19.0

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a Claude panel that uses your own claude command
//! 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, SetBackgroundColor, SetForegroundColor,
    },
    terminal::{BeginSynchronizedUpdate, Clear, ClearType, EndSynchronizedUpdate},
};

use crate::highlight::TokenKind;
use crate::theme::Theme;

#[cfg(test)]
mod tests;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Style {
    Plain,
    Dim,
    Bold,
    Error,
    Warning,
    /// Text in one of the terminal's colours.
    Colored(Color),
    /// A row of a pop-up list, on a background of its own.
    Menu,
    /// A status bar.
    Bar,
    /// The title of the panel that has the keys.
    Title,
    /// The row of a list that is picked.
    Selected,
    /// The tab of the file in front, and the other tabs.
    TabActive,
    Tab,
    /// The line of a pop-up list that is typed on.
    Input,
    /// A line number: `true` for the line the cursor is on.
    LineNumber(bool),
    /// A line that keeps two parts of the window apart.
    Border,
    /// What the user said, in a conversation.
    Accent,
    /// A box that is typed in, and a note that belongs to it.
    Field,
    FieldNote,
    /// 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,
    /// Part of a search match.
    pub marked: bool,
    /// On the line the cursor is on.
    pub current: bool,
}

/// The part of the window a piece of text is in. A theme gives each its
/// own background.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Zone {
    /// The text of the file.
    #[default]
    Text,
    /// The file tree.
    Side,
    /// The panels under and beside the text.
    Panel,
    /// A list that pops up over the text.
    Popup,
}

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

/// Says that `rows` are in `zone` of the window.
pub fn place(rows: &mut [Row], zone: Zone) {
    for span in rows.iter_mut().flatten() {
        span.zone = zone;
    }
}

pub type Row = Vec<Span>;

/// A tab moves on to the next column that is a multiple of this.
pub const TAB_STOP: usize = 4;
/// Stands in a row for the second half of a character that is two cells
/// wide (Chinese, Japanese, Korean, most emoji). With it, one character
/// of a row's text is always one cell of the screen, so everything that
/// counts characters to find a column stays right. It is never printed.
pub const WIDE_PAD: char = '\0';

/// The screen cells `text` takes, left to right: what is shown in each,
/// and the index of the character of `text` it belongs to. A tab is
/// spaces up to the next tab stop; a wide character is itself and a
/// `WIDE_PAD`; characters that take no room of their own (marks that
/// join the letter before them) are left out.
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
}

/// `text` as it is laid out on screen, one character per cell: see
/// `cells`. Text from files and from programs goes through this before it
/// is cut or padded to a width.
pub fn widen(text: &str) -> String {
    // Nearly all text is plain: leave it as it is.
    if text.bytes().all(|byte| (b' '..0x7f).contains(&byte)) {
        return text.to_string();
    }
    cells(text).into_iter().map(|(_, c)| c).collect()
}

/// 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
}

/// Lays `piece` over `row` starting at column `x`, replacing what was
/// there. A row that is too short is padded with spaces first.
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());
    // A wide character that the piece covers half of cannot be shown.
    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() }),
        }
    }
}

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

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.
            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);
        for (y, row) in frame.iter().enumerate() {
            if self.last_frame.get(y) == Some(row) {
                continue;
            }
            queue!(out, MoveTo(0, y as u16))?;
            // What is left of the row after its text takes the background
            // of the last piece: a status bar runs to the edge, and so
            // does the highlight of the cursor line.
            let mut rest = base;
            for span in row {
                let look = self.theme.look(span.style, span.zone);
                queue!(out, SetAttribute(Attribute::Reset), ResetColor)?;
                if let Some(color) = look.fg {
                    queue!(out, SetForegroundColor(color))?;
                }
                if let Some(color) = look.bg {
                    queue!(out, SetBackgroundColor(color))?;
                }
                let attributes = [
                    (look.bold, Attribute::Bold),
                    (look.dim, Attribute::Dim),
                    (look.italic, Attribute::Italic),
                    (look.underlined, Attribute::Underlined),
                    (look.struck, Attribute::CrossedOut),
                    (look.reverse, Attribute::Reverse),
                ];
                for (_, attribute) in attributes.iter().filter(|(wanted, _)| *wanted) {
                    queue!(out, SetAttribute(*attribute))?;
                }
                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);
            }
            queue!(out, SetAttribute(Attribute::Reset), ResetColor)?;
            if let Some(color) = rest {
                queue!(out, SetBackgroundColor(color))?;
            }
            queue!(out, Clear(ClearType::UntilNewLine), 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()
    }
}