Skip to main content

cellix_term/
cells.rs

1use std::io::{self, Write};
2
3use cellix_render::{Grid, Piece, Rect, Style};
4
5use crate::Backend;
6
7/// Styled text cells. Works everywhere, so every feature must work here.
8#[derive(Default)]
9pub struct CellBackend {
10    shown: Option<Grid>,
11    /// A scroll opened a synchronized update and moved the cursor, for this present to end.
12    scrolled: bool,
13    /// What it has done since the counters last asked: rows written count as rows.
14    work: crate::Work,
15}
16
17fn sgr(style: Style, out: &mut Vec<u8>) {
18    let (f, b) = (style.fg, style.bg);
19    let _ = write!(
20        out,
21        "\x1b[0;38;2;{};{};{};48;2;{};{};{}",
22        f.0, f.1, f.2, b.0, b.1, b.2
23    );
24    if style.bold {
25        out.extend_from_slice(b";1");
26    }
27    if style.italic {
28        out.extend_from_slice(b";3");
29    }
30    if style.underline {
31        out.extend_from_slice(b";4");
32    }
33    out.push(b'm');
34}
35
36impl Backend for CellBackend {
37    fn present(&mut self, grid: &Grid, out: &mut dyn Write) -> io::Result<()> {
38        let mut bytes = Vec::new();
39        // Synchronized output stops terminals showing half a frame. One that doesn't know it
40        // shows each run as it comes, so the cursor is hidden while they're written, or it
41        // runs over the screen with them, and shown again where it belongs at the end.
42        bytes.extend_from_slice(b"\x1b[?2026h\x1b[?25l");
43        let runs = match &self.shown {
44            Some(shown) => grid.diff(shown),
45            None => grid.diff(&Grid::new(0, 0, Style::default())),
46        };
47        // Nothing different, and the cursor where it was: nothing to send.
48        let cursor_kept = self.shown.as_ref().is_some_and(|s| s.cursor == grid.cursor);
49        if runs.is_empty() && cursor_kept && !std::mem::take(&mut self.scrolled) {
50            return Ok(());
51        }
52        self.scrolled = false;
53        let mut last = None;
54        let mut rows = runs.iter().map(|run| run.y).collect::<Vec<_>>();
55        rows.dedup();
56        self.work.rows += rows.len() as u64;
57        for run in runs {
58            let _ = write!(bytes, "\x1b[{};{}H", run.y + 1, run.x + 1);
59            for x in run.x..run.x + run.len {
60                let cell = grid.cell(x, run.y);
61                if last != Some(cell.style) {
62                    sgr(cell.style, &mut bytes);
63                    last = Some(cell.style);
64                }
65                match Piece::decode(&cell.symbol) {
66                    Some(piece) => bytes.extend_from_slice(piece.fallback().as_bytes()),
67                    None => bytes.extend_from_slice(cell.symbol.as_bytes()),
68                }
69            }
70        }
71        if let Some((x, y)) = grid.cursor {
72            let _ = write!(bytes, "\x1b[{};{}H\x1b[?25h", y + 1, x + 1);
73        }
74        bytes.extend_from_slice(b"\x1b[?2026l");
75        out.write_all(&bytes)?;
76        out.flush()?;
77        self.shown = Some(grid.clone());
78        Ok(())
79    }
80
81    fn invalidate(&mut self) {
82        self.shown = None;
83    }
84
85    fn take_work(&mut self) -> crate::Work {
86        std::mem::take(&mut self.work)
87    }
88
89    /// Has the terminal shift the band of rows the scrolled area spans, as vim and Claude
90    /// Code do, so only the lines that come into view and the columns that stay put (rail,
91    /// sidebar, minimap) are sent after it. Rewriting every row instead is what shows as a
92    /// scan over a slow link, in tmux especially. A whole-width region works in every
93    /// terminal, which left and right margins don't. The present that follows closes the
94    /// synchronized update this opens, so the shift and the repair land as one frame.
95    fn scroll(
96        &mut self,
97        _from: &Grid,
98        to: &Grid,
99        area: Rect,
100        rows: i32,
101        out: &mut dyn Write,
102    ) -> io::Result<()> {
103        let Some(shown) = &mut self.shown else {
104            return Ok(());
105        };
106        let fits = (shown.width(), shown.height()) == (to.width(), to.height());
107        if !fits || rows == 0 || rows.unsigned_abs() >= u32::from(area.h) || area.h == 0 {
108            return Ok(());
109        }
110        let (top, bottom) = (area.y, area.bottom() - 1);
111        let mut bytes = b"\x1b[?2026h\x1b[?25l".to_vec();
112        let _ = write!(bytes, "\x1b[{};{}r", top + 1, bottom + 1);
113        let n = rows.unsigned_abs();
114        let _ = if rows > 0 {
115            write!(bytes, "\x1b[{n}S")
116        } else {
117            write!(bytes, "\x1b[{n}T")
118        };
119        bytes.extend_from_slice(b"\x1b[r");
120        out.write_all(&bytes)?;
121        shown.scroll_rows(top, bottom, rows);
122        self.scrolled = true;
123        Ok(())
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    /// A grid with a sidebar column that stays and lines of text that move.
132    fn page(first: usize) -> Grid {
133        let mut grid = Grid::new(40, 12, Style::default());
134        for y in 0..12u16 {
135            grid.put_str(0, y, "|side|", Style::default(), 40);
136            let letter = (b'a' + ((first + y as usize) % 26) as u8) as char;
137            let line = format!("{} {}", first + y as usize, letter.to_string().repeat(28));
138            grid.put_str(8, y, &line, Style::default(), 40);
139        }
140        grid
141    }
142
143    #[test]
144    fn a_scroll_shifts_the_band_and_sends_only_what_it_must() {
145        let mut backend = CellBackend::default();
146        let mut sink = Vec::new();
147        let before = page(0);
148        backend.present(&before, &mut sink).unwrap();
149        let after = page(1);
150        let mut full = CellBackend::default();
151        let mut redrawn = Vec::new();
152        full.present(&before, &mut Vec::new()).unwrap();
153        full.present(&after, &mut redrawn).unwrap();
154        let mut moved = Vec::new();
155        let area = Rect::new(8, 0, 32, 12);
156        backend
157            .scroll(&before, &after, area, 1, &mut moved)
158            .unwrap();
159        backend.present(&after, &mut moved).unwrap();
160        let text = String::from_utf8_lossy(&moved);
161        assert!(
162            text.contains("\x1b[1;12r\x1b[1S\x1b[r"),
163            "the terminal shifts the band"
164        );
165        assert!(
166            text.contains("12 mmmm"),
167            "the line coming into view is sent"
168        );
169        assert!(
170            moved.len() * 2 < redrawn.len(),
171            "{} bytes where a redraw takes {}",
172            moved.len(),
173            redrawn.len()
174        );
175        // The sidebar the shift moved is put back.
176        assert_eq!(backend.shown.as_ref().unwrap().cell(0, 11).symbol, "|");
177    }
178
179    /// Nothing different and the cursor where it was: nothing is written. A moved cursor
180    /// is, and so is what follows a scroll, which leaves an update open for it to end.
181    #[test]
182    fn an_unchanged_frame_writes_nothing() {
183        let mut backend = CellBackend::default();
184        let mut grid = Grid::new(20, 5, Style::default());
185        grid.cursor = Some((2, 2));
186        backend.present(&grid, &mut Vec::new()).unwrap();
187        let mut again = Vec::new();
188        backend.present(&grid, &mut again).unwrap();
189        assert!(again.is_empty(), "{:?}", String::from_utf8_lossy(&again));
190        grid.cursor = Some((3, 2));
191        let mut moved = Vec::new();
192        backend.present(&grid, &mut moved).unwrap();
193        assert!(moved.windows(6).any(|w| w == b"\x1b[3;4H"));
194        let area = Rect::new(0, 0, 20, 5);
195        backend
196            .scroll(&grid, &grid, area, 1, &mut Vec::new())
197            .unwrap();
198        let mut after = Vec::new();
199        backend.present(&grid, &mut after).unwrap();
200        assert!(
201            after.ends_with(b"\x1b[?2026l"),
202            "the scroll's update is ended"
203        );
204    }
205
206    /// The cursor is hidden before anything is written and shown only once the frame is
207    /// whole, where it belongs: a terminal without synchronized output shows every run as it
208    /// comes, and the cursor ran over the screen with them.
209    #[test]
210    fn the_cursor_is_hidden_while_a_frame_is_written() {
211        let mut backend = CellBackend::default();
212        let mut grid = Grid::new(20, 5, Style::default());
213        grid.put_str(0, 0, "first", Style::default(), 20);
214        grid.put_str(0, 4, "last", Style::default(), 20);
215        grid.cursor = Some((2, 1));
216        let mut out = Vec::new();
217        backend.present(&grid, &mut out).unwrap();
218        let text = String::from_utf8_lossy(&out).into_owned();
219        assert!(text.starts_with("\x1b[?2026h\x1b[?25l"), "{text:?}");
220        let shown = text.find("\x1b[?25h").expect("the cursor comes back");
221        assert!(shown > text.find("last").unwrap(), "after the last run");
222        assert!(text[shown..].starts_with("\x1b[?25h\x1b[?2026l"));
223        assert!(text.contains("\x1b[2;3H\x1b[?25h"), "where it belongs");
224        // Without a cursor, it stays hidden.
225        grid.cursor = None;
226        grid.put_str(0, 2, "more", Style::default(), 20);
227        let mut out = Vec::new();
228        backend.present(&grid, &mut out).unwrap();
229        assert!(!String::from_utf8_lossy(&out).contains("\x1b[?25h"));
230    }
231
232    #[test]
233    fn second_present_sends_only_the_change() {
234        let mut backend = CellBackend::default();
235        let mut grid = Grid::new(20, 5, Style::default());
236        let mut first = Vec::new();
237        backend.present(&grid, &mut first).unwrap();
238        grid.put_str(3, 2, "x", Style::default(), 20);
239        let mut second = Vec::new();
240        backend.present(&grid, &mut second).unwrap();
241        assert!(second.len() < 80, "sent {} bytes", second.len());
242        assert!(second.windows(6).any(|w| w == b"\x1b[3;4H"));
243    }
244}