rustimal 0.4.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Find text in a pane's screen and scrollback (Ctrl+Shift+F).
//!
//! Matching is plain substring search on each grid row, ignoring case unless the
//! query has an uppercase letter ("smart case"). A match never spans a wrapped line.

use std::time::{Duration, Instant};

use alacritty_terminal::event::EventListener;
use alacritty_terminal::grid::{Dimensions, Scroll};
use alacritty_terminal::index::{Column, Line};
use alacritty_terminal::term::Term;
use alacritty_terminal::term::cell::Flags;

const MAX_MATCHES: usize = 10_000;
/// Longest wait before matches are recomputed after new output.
const REFRESH_EVERY: Duration = Duration::from_millis(200);

/// One match: `line` is a grid line (negative = scrollback), columns are `start..end`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Match {
    pub line: i32,
    pub start: usize,
    pub end: usize,
}

/// The characters of one grid row as `(column, char, width)`, without wide-char spacer cells.
pub fn row_chars<T>(term: &Term<T>, line: Line) -> Vec<(usize, char, usize)> {
    let row = &term.grid()[line];
    let mut out = Vec::with_capacity(term.columns());
    for col in 0..term.columns() {
        let cell = &row[Column(col)];
        if cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER) {
            continue;
        }
        let width = if cell.flags.contains(Flags::WIDE_CHAR) { 2 } else { 1 };
        out.push((col, if cell.c == '\0' { ' ' } else { cell.c }, width));
    }
    out
}

pub fn find<T>(term: &Term<T>, query: &str) -> Vec<Match> {
    let mut found = Vec::new();
    if query.is_empty() {
        return found;
    }
    let sensitive = query.chars().any(char::is_uppercase);
    let fold = |c: char| if sensitive { c } else { c.to_lowercase().next().unwrap_or(c) };
    let needle: Vec<char> = query.chars().map(fold).collect();
    for line in term.topmost_line().0..=term.bottommost_line().0 {
        let row = row_chars(term, Line(line));
        let hay: Vec<char> = row.iter().map(|&(_, c, _)| fold(c)).collect();
        let mut i = 0;
        while i + needle.len() <= hay.len() {
            if hay[i..i + needle.len()] == needle[..] {
                let (start, ..) = row[i];
                let (last, _, width) = row[i + needle.len() - 1];
                found.push(Match { line, start, end: last + width });
                if found.len() >= MAX_MATCHES {
                    return found;
                }
                i += needle.len();
            } else {
                i += 1;
            }
        }
    }
    found
}

pub struct Search {
    pub query: String,
    pub matches: Vec<Match>,
    pub current: usize,
    /// New output arrived since the matches were computed.
    pub dirty: bool,
    refreshed: Instant,
    /// Scrollback size when the matches were computed, to follow lines as they scroll.
    history: usize,
}

impl Search {
    pub fn new() -> Self {
        Self { query: String::new(), matches: Vec::new(), current: 0, dirty: false, refreshed: Instant::now(), history: 0 }
    }

    /// The query changed: search again and jump to the newest match.
    pub fn update<T: EventListener>(&mut self, term: &mut Term<T>) {
        self.matches = find(term, &self.query);
        self.current = self.matches.len().saturating_sub(1);
        self.history = term.history_size();
        self.dirty = false;
        self.refreshed = Instant::now();
        self.reveal(term);
    }

    /// Search again after new output, keeping the same match selected.
    pub fn refresh<T>(&mut self, term: &Term<T>) {
        let keep = self.matches.get(self.current).map(|m| (m.line + self.history as i32, m.start));
        self.matches = find(term, &self.query);
        self.history = term.history_size();
        self.current = keep
            .and_then(|(abs, start)| {
                self.matches.iter().position(|m| m.line + self.history as i32 == abs && m.start == start)
            })
            .unwrap_or_else(|| self.current.min(self.matches.len().saturating_sub(1)));
        self.dirty = false;
        self.refreshed = Instant::now();
    }

    /// How long until a dirty search may refresh (zero if it can now); `None` if it's clean.
    pub fn refresh_in(&self) -> Option<Duration> {
        self.dirty.then(|| REFRESH_EVERY.saturating_sub(self.refreshed.elapsed()))
    }

    /// Move to the next match: older (up) or newer (down), wrapping around.
    pub fn step<T: EventListener>(&mut self, term: &mut Term<T>, older: bool) {
        if self.dirty {
            self.refresh(term);
        }
        let n = self.matches.len();
        if n == 0 {
            return;
        }
        self.current = if older { (self.current + n - 1) % n } else { (self.current + 1) % n };
        self.reveal(term);
    }

    /// Scroll so the current match is on screen (only if it isn't already).
    fn reveal<T: EventListener>(&self, term: &mut Term<T>) {
        let Some(m) = self.matches.get(self.current) else { return };
        let rows = term.screen_lines() as i32;
        let offset = term.grid().display_offset() as i32;
        if (0..rows).contains(&(m.line + offset)) {
            return;
        }
        let target = (rows / 2 - m.line).clamp(0, term.history_size() as i32);
        term.scroll_display(Scroll::Delta(target - offset));
    }

    /// Text for the counter in the search bar.
    pub fn label(&self) -> String {
        if self.query.is_empty() {
            String::new()
        } else if self.matches.is_empty() {
            "no matches".to_string()
        } else {
            let more = if self.matches.len() >= MAX_MATCHES { "+" } else { "" };
            format!("{}/{}{more}", self.current + 1, self.matches.len())
        }
    }
}

#[cfg(test)]
mod tests {
    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 term_with(text: &str, rows: usize) -> Term<VoidListener> {
        let mut term = Term::new(Config::default(), &Size(rows, 40), VoidListener);
        let mut parser: Processor = Processor::new();
        parser.advance(&mut term, text.as_bytes());
        term
    }

    #[test]
    fn finds_text_in_screen_and_scrollback() {
        // 30 lines on a 5-row screen: most of it is scrollback.
        let text: String = (0..30).map(|i| format!("line {i}\r\n")).collect();
        let term = term_with(&text, 5);
        let found = find(&term, "line 1");
        // line 1 and line 10..=19
        assert_eq!(found.len(), 11);
        assert!(found[0].line < 0, "the oldest match is in scrollback");
        assert_eq!((found[0].start, found[0].end), (0, 6));
    }

    #[test]
    fn smart_case() {
        let term = term_with("Hello hello HELLO\r\n", 5);
        assert_eq!(find(&term, "hello").len(), 3);
        assert_eq!(find(&term, "Hello").len(), 1);
        assert_eq!(find(&term, "nope").len(), 0);
        assert_eq!(find(&term, "").len(), 0);
    }

    #[test]
    fn stepping_wraps_and_scrolls_to_the_match() {
        let text: String = (0..30).map(|i| format!("row {i}\r\n")).collect();
        let mut term = term_with(&text, 5);
        let mut search = Search::new();
        search.query = "row 2".into();
        search.update(&mut term);
        // row 2 and row 20..=29: the newest (row 29) is selected first.
        assert_eq!(search.matches.len(), 11);
        assert_eq!(search.current, 10);
        search.step(&mut term, false); // newer than the newest: wraps to the oldest
        assert_eq!(search.current, 0);
        let m = search.matches[0];
        let row = m.line + term.grid().display_offset() as i32;
        assert!((0..5).contains(&row), "the current match is scrolled into view, row {row}");
        search.step(&mut term, true); // older than the oldest: wraps to the newest
        assert_eq!(search.current, 10);
        assert_eq!(search.label(), "11/11");
    }

    #[test]
    fn wide_characters_span_two_columns() {
        let term = term_with("a日本b\r\n", 3);
        let found = find(&term, "本");
        assert_eq!(found.len(), 1);
        assert_eq!((found[0].start, found[0].end), (3, 5));
    }
}