Skip to main content

cellix_term/
cells.rs

1use std::io::{self, Write};
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use cellix_render::{CursorShape, Grid, Piece, Rect, Style};
5
6use crate::Backend;
7
8/// Whether the terminal's cursor was given a shape, so it's given its own back at the end.
9static STYLED: AtomicBool = AtomicBool::new(false);
10
11/// Whether a cell tier asked the terminal for a cursor of its own shape, which leaving should
12/// undo with `CURSOR_DEFAULT`.
13pub fn cursor_styled() -> bool {
14    STYLED.load(Ordering::Relaxed)
15}
16
17/// DECSCUSR 0: the cursor the terminal's own settings give it.
18pub const CURSOR_DEFAULT: &str = "\x1b[0 q";
19
20/// DECSCUSR for a shape, blinking or steady: 1 and 2 a block, 3 and 4 an underline, 5 and 6
21/// a bar, the odd ones blinking.
22fn cursor_style(shape: CursorShape, blinks: bool) -> String {
23    let steady = match shape {
24        CursorShape::Block => 2,
25        CursorShape::Underline => 4,
26        CursorShape::Bar => 6,
27    };
28    format!("\x1b[{} q", steady - u8::from(blinks))
29}
30
31/// Styled text cells. Works everywhere, so every feature must work here.
32#[derive(Default)]
33pub struct CellBackend {
34    shown: Option<Grid>,
35    /// A scroll opened a synchronized update and moved the cursor, for this present to end.
36    scrolled: bool,
37    /// What it has done since the counters last asked: rows written count as rows.
38    work: crate::Work,
39    /// The cursor's shape and blink as the terminal was last told them. The terminal blinks
40    /// its own cursor, so a blink costs Cellix nothing here: no wake, no byte.
41    told: Option<(CursorShape, bool)>,
42}
43
44fn sgr(style: Style, out: &mut Vec<u8>) {
45    let (f, b) = (style.fg, style.bg);
46    let _ = write!(
47        out,
48        "\x1b[0;38;2;{};{};{};48;2;{};{};{}",
49        f.0, f.1, f.2, b.0, b.1, b.2
50    );
51    if style.bold {
52        out.extend_from_slice(b";1");
53    }
54    if style.italic {
55        out.extend_from_slice(b";3");
56    }
57    if style.underline {
58        out.extend_from_slice(b";4");
59    }
60    out.push(b'm');
61}
62
63impl Backend for CellBackend {
64    fn present(&mut self, grid: &Grid, out: &mut dyn Write) -> io::Result<()> {
65        let mut bytes = Vec::new();
66        // Synchronized output stops terminals showing half a frame. One that doesn't know it
67        // shows each run as it comes, so the cursor is hidden while they're written, or it
68        // runs over the screen with them, and shown again where it belongs at the end.
69        bytes.extend_from_slice(b"\x1b[?2026h\x1b[?25l");
70        let runs = match &self.shown {
71            Some(shown) => grid.diff(shown),
72            None => grid.diff(&Grid::new(0, 0, Style::default())),
73        };
74        // The cursor's shape and blink, said only when they change, and only for a cursor
75        // that shows.
76        let look = (grid.cursor_shape, grid.cursor_blinks);
77        let restyle = grid.cursor.is_some() && self.told != Some(look);
78        // Nothing different, and the cursor where it was: nothing to send.
79        let cursor_kept = self.shown.as_ref().is_some_and(|s| s.cursor == grid.cursor);
80        if runs.is_empty() && cursor_kept && !restyle && !std::mem::take(&mut self.scrolled) {
81            return Ok(());
82        }
83        if restyle {
84            bytes.extend_from_slice(cursor_style(look.0, look.1).as_bytes());
85            self.told = Some(look);
86            STYLED.store(true, Ordering::Relaxed);
87        }
88        self.scrolled = false;
89        let mut last = None;
90        let mut rows = runs.iter().map(|run| run.y).collect::<Vec<_>>();
91        rows.dedup();
92        self.work.rows += rows.len() as u64;
93        for run in runs {
94            let _ = write!(bytes, "\x1b[{};{}H", run.y + 1, run.x + 1);
95            for x in run.x..run.x + run.len {
96                let cell = grid.cell(x, run.y);
97                if last != Some(cell.style) {
98                    sgr(cell.style, &mut bytes);
99                    last = Some(cell.style);
100                }
101                match Piece::decode(&cell.symbol) {
102                    Some(piece) => bytes.extend_from_slice(piece.fallback().as_bytes()),
103                    None => bytes.extend_from_slice(cell.symbol.as_bytes()),
104                }
105            }
106        }
107        if let Some((x, y)) = grid.cursor {
108            let _ = write!(bytes, "\x1b[{};{}H\x1b[?25h", y + 1, x + 1);
109        }
110        bytes.extend_from_slice(b"\x1b[?2026l");
111        out.write_all(&bytes)?;
112        out.flush()?;
113        self.shown = Some(grid.clone());
114        Ok(())
115    }
116
117    fn invalidate(&mut self) {
118        self.shown = None;
119        // A terminal that forgot what it showed, as a multiplexer's new client, is told again.
120        self.told = None;
121    }
122
123    fn take_work(&mut self) -> crate::Work {
124        std::mem::take(&mut self.work)
125    }
126
127    /// Has the terminal shift the band of rows the scrolled area spans, as vim and Claude
128    /// Code do, so only the lines that come into view and the columns that stay put (rail,
129    /// sidebar, minimap) are sent after it. Rewriting every row instead is what shows as a
130    /// scan over a slow link, in tmux especially. A whole-width region works in every
131    /// terminal, which left and right margins don't. The present that follows closes the
132    /// synchronized update this opens, so the shift and the repair land as one frame.
133    fn scroll(
134        &mut self,
135        _from: &Grid,
136        to: &Grid,
137        area: Rect,
138        rows: i32,
139        out: &mut dyn Write,
140    ) -> io::Result<()> {
141        let Some(shown) = &mut self.shown else {
142            return Ok(());
143        };
144        let fits = (shown.width(), shown.height()) == (to.width(), to.height());
145        if !fits || rows == 0 || rows.unsigned_abs() >= u32::from(area.h) || area.h == 0 {
146            return Ok(());
147        }
148        let (top, bottom) = (area.y, area.bottom() - 1);
149        let mut bytes = b"\x1b[?2026h\x1b[?25l".to_vec();
150        let _ = write!(bytes, "\x1b[{};{}r", top + 1, bottom + 1);
151        let n = rows.unsigned_abs();
152        let _ = if rows > 0 {
153            write!(bytes, "\x1b[{n}S")
154        } else {
155            write!(bytes, "\x1b[{n}T")
156        };
157        bytes.extend_from_slice(b"\x1b[r");
158        out.write_all(&bytes)?;
159        shown.scroll_rows(top, bottom, rows);
160        self.scrolled = true;
161        Ok(())
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    /// A grid with a sidebar column that stays and lines of text that move.
170    fn page(first: usize) -> Grid {
171        let mut grid = Grid::new(40, 12, Style::default());
172        for y in 0..12u16 {
173            grid.put_str(0, y, "|side|", Style::default(), 40);
174            let letter = (b'a' + ((first + y as usize) % 26) as u8) as char;
175            let line = format!("{} {}", first + y as usize, letter.to_string().repeat(28));
176            grid.put_str(8, y, &line, Style::default(), 40);
177        }
178        grid
179    }
180
181    #[test]
182    fn a_scroll_shifts_the_band_and_sends_only_what_it_must() {
183        let mut backend = CellBackend::default();
184        let mut sink = Vec::new();
185        let before = page(0);
186        backend.present(&before, &mut sink).unwrap();
187        let after = page(1);
188        let mut full = CellBackend::default();
189        let mut redrawn = Vec::new();
190        full.present(&before, &mut Vec::new()).unwrap();
191        full.present(&after, &mut redrawn).unwrap();
192        let mut moved = Vec::new();
193        let area = Rect::new(8, 0, 32, 12);
194        backend
195            .scroll(&before, &after, area, 1, &mut moved)
196            .unwrap();
197        backend.present(&after, &mut moved).unwrap();
198        let text = String::from_utf8_lossy(&moved);
199        assert!(
200            text.contains("\x1b[1;12r\x1b[1S\x1b[r"),
201            "the terminal shifts the band"
202        );
203        assert!(
204            text.contains("12 mmmm"),
205            "the line coming into view is sent"
206        );
207        assert!(
208            moved.len() * 2 < redrawn.len(),
209            "{} bytes where a redraw takes {}",
210            moved.len(),
211            redrawn.len()
212        );
213        // The sidebar the shift moved is put back.
214        assert_eq!(backend.shown.as_ref().unwrap().cell(0, 11).symbol, "|");
215    }
216
217    /// Nothing different and the cursor where it was: nothing is written. A moved cursor
218    /// is, and so is what follows a scroll, which leaves an update open for it to end.
219    #[test]
220    fn an_unchanged_frame_writes_nothing() {
221        let mut backend = CellBackend::default();
222        let mut grid = Grid::new(20, 5, Style::default());
223        grid.cursor = Some((2, 2));
224        backend.present(&grid, &mut Vec::new()).unwrap();
225        let mut again = Vec::new();
226        backend.present(&grid, &mut again).unwrap();
227        assert!(again.is_empty(), "{:?}", String::from_utf8_lossy(&again));
228        grid.cursor = Some((3, 2));
229        let mut moved = Vec::new();
230        backend.present(&grid, &mut moved).unwrap();
231        assert!(moved.windows(6).any(|w| w == b"\x1b[3;4H"));
232        let area = Rect::new(0, 0, 20, 5);
233        backend
234            .scroll(&grid, &grid, area, 1, &mut Vec::new())
235            .unwrap();
236        let mut after = Vec::new();
237        backend.present(&grid, &mut after).unwrap();
238        assert!(
239            after.ends_with(b"\x1b[?2026l"),
240            "the scroll's update is ended"
241        );
242    }
243
244    /// The cursor is hidden before anything is written and shown only once the frame is
245    /// whole, where it belongs: a terminal without synchronized output shows every run as it
246    /// comes, and the cursor ran over the screen with them.
247    #[test]
248    fn the_cursor_is_hidden_while_a_frame_is_written() {
249        let mut backend = CellBackend::default();
250        let mut grid = Grid::new(20, 5, Style::default());
251        grid.put_str(0, 0, "first", Style::default(), 20);
252        grid.put_str(0, 4, "last", Style::default(), 20);
253        grid.cursor = Some((2, 1));
254        let mut out = Vec::new();
255        backend.present(&grid, &mut out).unwrap();
256        let text = String::from_utf8_lossy(&out).into_owned();
257        assert!(text.starts_with("\x1b[?2026h\x1b[?25l"), "{text:?}");
258        let shown = text.find("\x1b[?25h").expect("the cursor comes back");
259        assert!(shown > text.find("last").unwrap(), "after the last run");
260        assert!(text[shown..].starts_with("\x1b[?25h\x1b[?2026l"));
261        assert!(text.contains("\x1b[2;3H\x1b[?25h"), "where it belongs");
262        // Without a cursor, it stays hidden.
263        grid.cursor = None;
264        grid.put_str(0, 2, "more", Style::default(), 20);
265        let mut out = Vec::new();
266        backend.present(&grid, &mut out).unwrap();
267        assert!(!String::from_utf8_lossy(&out).contains("\x1b[?25h"));
268    }
269
270    /// On cells the terminal blinks its own cursor: it's told the cursor's shape and whether it
271    /// blinks (DECSCUSR) once, as they change, and a frame after that with nothing different
272    /// sends nothing, so a blink costs no wake and no byte. A bar for the caret, a terminal
273    /// pane's program's own shape, steady where the grid says so.
274    #[test]
275    fn the_terminal_is_told_to_blink_its_own_cursor_once() {
276        let mut backend = CellBackend::default();
277        let mut grid = Grid::new(20, 5, Style::default());
278        grid.cursor = Some((2, 1));
279        grid.cursor_blinks = true;
280        let mut out = Vec::new();
281        backend.present(&grid, &mut out).unwrap();
282        let text = String::from_utf8_lossy(&out).into_owned();
283        assert!(text.contains("\x1b[5 q"), "a blinking bar: {text:?}");
284        assert!(
285            cursor_styled(),
286            "so leaving gives the terminal its own back"
287        );
288        let mut again = Vec::new();
289        backend.present(&grid, &mut again).unwrap();
290        assert!(
291            again.is_empty(),
292            "told once: {:?}",
293            String::from_utf8_lossy(&again)
294        );
295        // The window behind another: steady.
296        grid.cursor_blinks = false;
297        let mut out = Vec::new();
298        backend.present(&grid, &mut out).unwrap();
299        assert_eq!(
300            String::from_utf8_lossy(&out),
301            "\x1b[?2026h\x1b[?25l\x1b[6 q\x1b[2;3H\x1b[?25h\x1b[?2026l"
302        );
303        // A program's block, blinking, and an underline it asked to keep still.
304        grid.cursor_shape = CursorShape::Block;
305        grid.cursor_blinks = true;
306        let mut out = Vec::new();
307        backend.present(&grid, &mut out).unwrap();
308        assert!(String::from_utf8_lossy(&out).contains("\x1b[1 q"));
309        grid.cursor_shape = CursorShape::Underline;
310        grid.cursor_blinks = false;
311        let mut out = Vec::new();
312        backend.present(&grid, &mut out).unwrap();
313        assert!(String::from_utf8_lossy(&out).contains("\x1b[4 q"));
314        // With no cursor shown, nothing is said of its shape.
315        grid.cursor = None;
316        grid.cursor_shape = CursorShape::Bar;
317        let mut out = Vec::new();
318        backend.present(&grid, &mut out).unwrap();
319        assert!(!String::from_utf8_lossy(&out).contains(" q"));
320    }
321
322    #[test]
323    fn second_present_sends_only_the_change() {
324        let mut backend = CellBackend::default();
325        let mut grid = Grid::new(20, 5, Style::default());
326        let mut first = Vec::new();
327        backend.present(&grid, &mut first).unwrap();
328        grid.put_str(3, 2, "x", Style::default(), 20);
329        let mut second = Vec::new();
330        backend.present(&grid, &mut second).unwrap();
331        assert!(second.len() < 80, "sent {} bytes", second.len());
332        assert!(second.windows(6).any(|w| w == b"\x1b[3;4H"));
333    }
334}