rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Reading rustimal's prompt off a pane's screen: whether the cursor is at one, what is
//! typed after it, and what the last command printed.

use alacritty_terminal::grid::Dimensions;
use alacritty_terminal::index::{Column, Line, Point, Side};
use alacritty_terminal::selection::{Selection, SelectionType};
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::{Term, TermMode};

/// The cursor sits right after rustimal's prompt (`... ❯ `) with nothing typed on the line, on
/// the normal screen.
pub fn cursor_at_prompt<T>(term: &Term<T>) -> bool {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return false;
    }
    let cursor = term.grid().cursor.point;
    let row = crate::terminal::search::row_chars(term, cursor.line);
    let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
    let after_is_empty = row.iter().all(|&(col, c, _)| col < cursor.column.0 || c == ' ');
    before.ends_with("\u{276f} ") && after_is_empty
}

/// Readline is showing a long list a page at a time and waiting for a key (`--More--`).
pub fn awaiting_more<T>(term: &Term<T>) -> bool {
    let cursor = term.grid().cursor.point;
    let row = crate::terminal::search::row_chars(term, cursor.line);
    let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
    !term.mode().contains(TermMode::ALT_SCREEN) && before.trim_end().ends_with("--More--")
}

/// The output of the last command: everything printed after its prompt line, up to the next
/// prompt (or the cursor, while it is still running). Found from the prompts on screen, so it
/// works with rustimal's prompt only, and as far back as the scrollback goes.
pub fn last_output<T>(term: &Term<T>) -> Option<String> {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return None;
    }
    let marker = "\u{276f} ";
    let text = |line: i32| -> String {
        crate::terminal::search::row_chars(term, Line(line)).iter().map(|&(_, c, _)| c).collect()
    };
    let top = term.topmost_line().0;
    // The prompt waiting at the cursor (maybe with text typed) is not output.
    let mut end = term.grid().cursor.point.line.0 - i32::from(typed_text(term).is_some());
    while end >= top && text(end).trim().is_empty() {
        end -= 1;
    }
    let cmd = (top..=end).rev().find(|&line| text(line).contains(marker))?;
    // A long command wraps onto more rows; the output starts after the last of them.
    let last_col = Column(term.columns().saturating_sub(1));
    let mut first = cmd;
    while first < end && term.grid()[Line(first)][last_col].flags.contains(Flags::WRAPLINE) {
        first += 1;
    }
    first += 1;
    if first > end {
        return None;
    }
    let out = term.bounds_to_string(Point::new(Line(first), Column(0)), Point::new(Line(end), last_col));
    let out = out.trim_matches('\n').trim_end().to_string();
    (!out.is_empty()).then_some(out)
}

/// The command being typed at the prompt: its characters with their screen columns, and where
/// the cursor is among them.
pub struct CmdLine {
    pub line: i32,
    pub cells: Vec<(usize, char, usize)>,
    pub cursor: usize,
}

impl CmdLine {
    pub fn chars(&self) -> Vec<char> {
        self.cells.iter().map(|c| c.1).collect()
    }

    pub fn text(&self) -> String {
        self.cells.iter().map(|c| c.1).collect()
    }

    /// Which gap between characters a click lands in: `col` is the screen column clicked, and
    /// `right` whether it was the right half of that cell. Left of the text is 0, right of it
    /// is the end.
    pub fn index_at(&self, col: usize, right: bool) -> usize {
        self.cells.iter().take_while(|&&(c, _, w)| c + w <= col || (c <= col && right)).count()
    }
}

/// The command line at the cursor, from rustimal's prompt to the last character on the row.
/// Not for a command that wraps onto several rows, or on the alternate screen.
pub fn command_line<T>(term: &Term<T>) -> Option<CmdLine> {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return None;
    }
    let cursor = term.grid().cursor.point;
    let last_col = Column(term.columns().saturating_sub(1));
    if term.grid()[cursor.line][last_col].flags.contains(Flags::WRAPLINE) {
        return None;
    }
    let row = crate::terminal::search::row_chars(term, cursor.line);
    let marker = row.windows(2).rposition(|w| w[0].1 == '\u{276f}' && w[1].1 == ' ')?;
    let after = &row[marker + 2..];
    let cursor_idx = after.iter().filter(|&&(col, ..)| col < cursor.column.0).count();
    let text_end = after.iter().rposition(|c| c.1 != ' ').map_or(0, |i| i + 1);
    let end = text_end.max(cursor_idx);
    Some(CmdLine { line: cursor.line.0, cells: after[..end].to_vec(), cursor: cursor_idx })
}

/// Highlight `lo..hi` of the command line as the terminal selection (or none if it is empty).
pub fn show_selection<T>(term: &mut Term<T>, cl: &CmdLine, lo: usize, hi: usize) {
    if lo >= hi || hi > cl.cells.len() {
        term.selection = None;
        return;
    }
    let cols = term.columns();
    let start = cl.cells[lo].0;
    let (end, side) = if hi < cl.cells.len() {
        (cl.cells[hi].0, Side::Left)
    } else {
        let (col, _, width) = cl.cells[hi - 1];
        if col + width >= cols { (cols - 1, Side::Right) } else { (col + width, Side::Left) }
    };
    let mut sel = Selection::new(SelectionType::Simple, Point::new(Line(cl.line), Column(start)), Side::Left);
    sel.update(Point::new(Line(cl.line), Column(end)), side);
    term.selection = Some(sel);
}

/// What is typed on the prompt line after rustimal's `❯ `, up to the cursor.
pub fn typed_text<T>(term: &Term<T>) -> Option<String> {
    if term.mode().contains(TermMode::ALT_SCREEN) {
        return None;
    }
    let cursor = term.grid().cursor.point;
    let row = crate::terminal::search::row_chars(term, cursor.line);
    let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
    let marker = "\u{276f} ";
    let at = before.rfind(marker)?;
    Some(before[at + marker.len()..].to_string())
}

#[cfg(test)]
mod tests {
    #[test]
    fn a_click_lands_between_characters() {
        // "ab" at columns 0..2, a wide character at 2..4, "c" at 4.
        let cl = CmdLine { line: 0, cells: vec![(0, 'a', 1), (1, 'b', 1), (2, '世', 2), (4, 'c', 1)], cursor: 4 };
        assert_eq!(cl.index_at(0, false), 0, "left half of the first character");
        assert_eq!(cl.index_at(0, true), 1, "right half of it");
        assert_eq!(cl.index_at(1, false), 1);
        assert_eq!(cl.index_at(2, false), 2, "before the wide character");
        assert_eq!(cl.index_at(3, true), 3, "after the wide character");
        assert_eq!(cl.index_at(4, true), 4);
        assert_eq!(cl.index_at(30, false), 4, "past the end of the text is the end");
        let empty = CmdLine { line: 0, cells: vec![], cursor: 0 };
        assert_eq!(empty.index_at(5, true), 0);
    }
    use super::*;
    use alacritty_terminal::event::VoidListener;
    use alacritty_terminal::term::Config;
    use alacritty_terminal::vte::ansi::Processor;

    struct Size(usize, usize);

    impl Dimensions for Size {
        fn total_lines(&self) -> usize {
            self.0
        }
        fn screen_lines(&self) -> usize {
            self.0
        }
        fn columns(&self) -> usize {
            self.1
        }
    }

    fn screen(rows: usize, cols: usize, text: &str) -> Term<VoidListener> {
        let mut term = Term::new(Config::default(), &Size(rows, cols), VoidListener);
        let mut parser: Processor = Processor::new();
        parser.advance(&mut term, text.as_bytes());
        term
    }

    #[test]
    fn last_output_is_what_the_last_command_printed() {
        let term =
            screen(20, 60, "~ \u{276f} echo one\r\none\r\n\r\n~ \u{276f} ls\r\nfile a\r\nfile b\r\n\r\n~ \u{276f} ");
        assert_eq!(last_output(&term).as_deref(), Some("file a\nfile b"));
        // With something typed on the new prompt, the output is still the same.
        let term = screen(20, 60, "~ \u{276f} ls\r\nfile a\r\nfile b\r\n\r\n~ \u{276f} cd sr");
        assert_eq!(last_output(&term).as_deref(), Some("file a\nfile b"));
    }

    #[test]
    fn last_output_while_the_command_still_runs() {
        let term = screen(20, 60, "~ \u{276f} make\r\nbuilding a\r\nbuilding b");
        assert_eq!(last_output(&term).as_deref(), Some("building a\nbuilding b"));
    }

    #[test]
    fn last_output_survives_scrolling_and_wrapped_commands() {
        // Output taller than the screen scrolls the command line into scrollback.
        let mut text = String::from("~ \u{276f} seq 1 40\r\n");
        for i in 1..=40 {
            text += &format!("{i}\r\n");
        }
        text += "\r\n~ \u{276f} ";
        let term = screen(10, 40, &text);
        let out = last_output(&term).unwrap();
        assert!(out.starts_with("1\n2\n3\n") && out.ends_with("\n39\n40"), "{out:?}");
        assert_eq!(out.lines().count(), 40);
        // A command long enough to wrap: its second row is not output.
        let long = "x".repeat(50);
        let term = screen(10, 30, &format!("~ \u{276f} echo {long}\r\n{long}\r\n\r\n~ \u{276f} "));
        assert_eq!(last_output(&term).as_deref(), Some(long.as_str()));
    }

    #[test]
    fn the_command_line_is_found_with_the_cursor_in_it() {
        // "cd src" typed, then the cursor moved back two characters.
        let term = screen(10, 40, "~ \u{276f} cd src\x1b[2D");
        let cl = command_line(&term).unwrap();
        assert_eq!(cl.text(), "cd src");
        assert_eq!(cl.cursor, 4);
        // An empty prompt has an empty line.
        let term = screen(10, 40, "~ \u{276f} ");
        let cl = command_line(&term).unwrap();
        assert!(cl.cells.is_empty() && cl.cursor == 0);
        // Trailing spaces up to the cursor belong to the line.
        let term = screen(10, 40, "~ \u{276f} ls  ");
        let cl = command_line(&term).unwrap();
        assert_eq!((cl.text().as_str(), cl.cursor), ("ls  ", 4));
        // Output has no command line.
        assert!(command_line(&screen(10, 40, "just output")).is_none());
    }

    #[test]
    fn the_selection_covers_the_chosen_characters() {
        let mut term = screen(10, 40, "~ \u{276f} echo hello world");
        let cl = command_line(&term).unwrap();
        show_selection(&mut term, &cl, 5, 10);
        assert_eq!(term.selection_to_string().as_deref(), Some("hello"));
        show_selection(&mut term, &cl, 11, cl.cells.len());
        assert_eq!(term.selection_to_string().as_deref(), Some("world"), "up to the end of the line");
        show_selection(&mut term, &cl, 0, cl.cells.len());
        assert_eq!(term.selection_to_string().as_deref(), Some("echo hello world"));
        show_selection(&mut term, &cl, 3, 3);
        assert!(term.selection.is_none(), "an empty range is no selection");
    }

    #[test]
    fn no_output_for_a_command_that_printed_nothing() {
        let term = screen(10, 40, "~ \u{276f} true\r\n\r\n~ \u{276f} ");
        assert_eq!(last_output(&term), None);
        assert_eq!(last_output(&screen(10, 40, "")), None);
    }
}