1use std::io::{self, Write};
2
3use cellix_render::{Grid, Piece, Rect, Style};
4
5use crate::Backend;
6
7#[derive(Default)]
9pub struct CellBackend {
10 shown: Option<Grid>,
11}
12
13fn sgr(style: Style, out: &mut Vec<u8>) {
14 let (f, b) = (style.fg, style.bg);
15 let _ = write!(
16 out,
17 "\x1b[0;38;2;{};{};{};48;2;{};{};{}",
18 f.0, f.1, f.2, b.0, b.1, b.2
19 );
20 if style.bold {
21 out.extend_from_slice(b";1");
22 }
23 if style.italic {
24 out.extend_from_slice(b";3");
25 }
26 if style.underline {
27 out.extend_from_slice(b";4");
28 }
29 out.push(b'm');
30}
31
32impl Backend for CellBackend {
33 fn present(&mut self, grid: &Grid, out: &mut dyn Write) -> io::Result<()> {
34 let mut bytes = Vec::new();
35 bytes.extend_from_slice(b"\x1b[?2026h");
37 let runs = match &self.shown {
38 Some(shown) => grid.diff(shown),
39 None => grid.diff(&Grid::new(0, 0, Style::default())),
40 };
41 let mut last = None;
42 for run in runs {
43 let _ = write!(bytes, "\x1b[{};{}H", run.y + 1, run.x + 1);
44 for x in run.x..run.x + run.len {
45 let cell = grid.cell(x, run.y);
46 if last != Some(cell.style) {
47 sgr(cell.style, &mut bytes);
48 last = Some(cell.style);
49 }
50 match Piece::decode(&cell.symbol) {
51 Some(piece) => bytes.extend_from_slice(piece.fallback().as_bytes()),
52 None => bytes.extend_from_slice(cell.symbol.as_bytes()),
53 }
54 }
55 }
56 match grid.cursor {
57 Some((x, y)) => {
58 let _ = write!(bytes, "\x1b[{};{}H\x1b[?25h", y + 1, x + 1);
59 }
60 None => bytes.extend_from_slice(b"\x1b[?25l"),
61 }
62 bytes.extend_from_slice(b"\x1b[?2026l");
63 out.write_all(&bytes)?;
64 out.flush()?;
65 self.shown = Some(grid.clone());
66 Ok(())
67 }
68
69 fn invalidate(&mut self) {
70 self.shown = None;
71 }
72
73 fn scroll(
80 &mut self,
81 _from: &Grid,
82 to: &Grid,
83 area: Rect,
84 rows: i32,
85 out: &mut dyn Write,
86 ) -> io::Result<()> {
87 let Some(shown) = &mut self.shown else {
88 return Ok(());
89 };
90 let fits = (shown.width(), shown.height()) == (to.width(), to.height());
91 if !fits || rows == 0 || rows.unsigned_abs() >= u32::from(area.h) || area.h == 0 {
92 return Ok(());
93 }
94 let (top, bottom) = (area.y, area.bottom() - 1);
95 let mut bytes = b"\x1b[?2026h".to_vec();
96 let _ = write!(bytes, "\x1b[{};{}r", top + 1, bottom + 1);
97 let n = rows.unsigned_abs();
98 let _ = if rows > 0 {
99 write!(bytes, "\x1b[{n}S")
100 } else {
101 write!(bytes, "\x1b[{n}T")
102 };
103 bytes.extend_from_slice(b"\x1b[r");
104 out.write_all(&bytes)?;
105 shown.scroll_rows(top, bottom, rows);
106 Ok(())
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113
114 fn page(first: usize) -> Grid {
116 let mut grid = Grid::new(40, 12, Style::default());
117 for y in 0..12u16 {
118 grid.put_str(0, y, "|side|", Style::default(), 40);
119 let letter = (b'a' + ((first + y as usize) % 26) as u8) as char;
120 let line = format!("{} {}", first + y as usize, letter.to_string().repeat(28));
121 grid.put_str(8, y, &line, Style::default(), 40);
122 }
123 grid
124 }
125
126 #[test]
127 fn a_scroll_shifts_the_band_and_sends_only_what_it_must() {
128 let mut backend = CellBackend::default();
129 let mut sink = Vec::new();
130 let before = page(0);
131 backend.present(&before, &mut sink).unwrap();
132 let after = page(1);
133 let mut full = CellBackend::default();
134 let mut redrawn = Vec::new();
135 full.present(&before, &mut Vec::new()).unwrap();
136 full.present(&after, &mut redrawn).unwrap();
137 let mut moved = Vec::new();
138 let area = Rect::new(8, 0, 32, 12);
139 backend
140 .scroll(&before, &after, area, 1, &mut moved)
141 .unwrap();
142 backend.present(&after, &mut moved).unwrap();
143 let text = String::from_utf8_lossy(&moved);
144 assert!(
145 text.contains("\x1b[1;12r\x1b[1S\x1b[r"),
146 "the terminal shifts the band"
147 );
148 assert!(
149 text.contains("12 mmmm"),
150 "the line coming into view is sent"
151 );
152 assert!(
153 moved.len() * 2 < redrawn.len(),
154 "{} bytes where a redraw takes {}",
155 moved.len(),
156 redrawn.len()
157 );
158 assert_eq!(backend.shown.as_ref().unwrap().cell(0, 11).symbol, "|");
160 }
161
162 #[test]
163 fn second_present_sends_only_the_change() {
164 let mut backend = CellBackend::default();
165 let mut grid = Grid::new(20, 5, Style::default());
166 let mut first = Vec::new();
167 backend.present(&grid, &mut first).unwrap();
168 grid.put_str(3, 2, "x", Style::default(), 20);
169 let mut second = Vec::new();
170 backend.present(&grid, &mut second).unwrap();
171 assert!(second.len() < 80, "sent {} bytes", second.len());
172 assert!(second.windows(6).any(|w| w == b"\x1b[3;4H"));
173 }
174}