Skip to main content

waxterm/
structured.rs

1//! Packed binary cell backend for ratatui.
2//!
3//! Implements `ratatui::backend::Backend` with a binary wire format instead of
4//! ANSI escape sequences. Each cell is packed into ~14 bytes:
5//!
6//! ```text
7//! [x: u16] [y: u16] [symbol_len: u8] [symbol: 1-4 bytes] [fg: u32] [bg: u32] [modifiers: u16]
8//! ```
9//!
10//! The TUI display server deserializes directly into `PaneBuffer` cells,
11//! bypassing VTE parsing (~30ns/cell vs ~120ns/cell for ANSI→VTE).
12
13use std::io::{self, Write};
14
15use ratatui::{
16    backend::{Backend, ClearType, WindowSize},
17    buffer::Cell,
18    layout::{Position, Size},
19    style::{Color, Modifier},
20};
21
22/// Magic header bytes identifying a structured frame.
23pub const STRUCTURED_MAGIC: [u8; 4] = [0x54, 0x55, 0x49, 0x53]; // "TUIS"
24
25/// A backend that writes packed binary cell data to a sink.
26pub struct StructuredBackend<W: Write> {
27    writer: W,
28    width: u16,
29    height: u16,
30}
31
32impl<W: Write> StructuredBackend<W> {
33    pub fn new(writer: W, width: u16, height: u16) -> Self {
34        Self {
35            writer,
36            width,
37            height,
38        }
39    }
40
41    /// Get the underlying writer.
42    pub fn writer(&self) -> &W {
43        &self.writer
44    }
45
46    /// Get a mutable reference to the underlying writer.
47    pub fn writer_mut(&mut self) -> &mut W {
48        &mut self.writer
49    }
50}
51
52impl<W: Write> Backend for StructuredBackend<W> {
53    type Error = io::Error;
54
55    fn draw<'a, I>(&mut self, content: I) -> Result<(), Self::Error>
56    where
57        I: Iterator<Item = (u16, u16, &'a Cell)>,
58    {
59        // Write magic header
60        self.writer.write_all(&STRUCTURED_MAGIC)?;
61
62        // Write dimensions
63        self.writer.write_all(&self.width.to_le_bytes())?;
64        self.writer.write_all(&self.height.to_le_bytes())?;
65
66        for (x, y, cell) in content {
67            // Position
68            self.writer.write_all(&x.to_le_bytes())?;
69            self.writer.write_all(&y.to_le_bytes())?;
70
71            // Symbol (length-prefixed, UTF-8)
72            let symbol = cell.symbol().as_bytes();
73            let len = symbol.len().min(255) as u8;
74            self.writer.write_all(&[len])?;
75            self.writer.write_all(&symbol[..len as usize])?;
76
77            // Colors
78            self.writer.write_all(&pack_color(cell.fg).to_le_bytes())?;
79            self.writer.write_all(&pack_color(cell.bg).to_le_bytes())?;
80
81            // Modifiers
82            self.writer
83                .write_all(&(cell.modifier.bits()).to_le_bytes())?;
84        }
85
86        self.writer.flush()
87    }
88
89    fn hide_cursor(&mut self) -> Result<(), Self::Error> {
90        Ok(())
91    }
92
93    fn show_cursor(&mut self) -> Result<(), Self::Error> {
94        Ok(())
95    }
96
97    fn get_cursor_position(&mut self) -> Result<Position, Self::Error> {
98        Ok(Position::new(0, 0))
99    }
100
101    fn set_cursor_position<P: Into<Position>>(&mut self, _position: P) -> Result<(), Self::Error> {
102        Ok(())
103    }
104
105    fn clear(&mut self) -> Result<(), Self::Error> {
106        Ok(())
107    }
108
109    fn clear_region(&mut self, _clear_type: ClearType) -> Result<(), Self::Error> {
110        Ok(())
111    }
112
113    fn size(&self) -> Result<Size, Self::Error> {
114        Ok(Size::new(self.width, self.height))
115    }
116
117    fn window_size(&mut self) -> Result<WindowSize, Self::Error> {
118        Ok(WindowSize {
119            columns_rows: Size::new(self.width, self.height),
120            pixels: Size::new(0, 0),
121        })
122    }
123
124    fn flush(&mut self) -> Result<(), Self::Error> {
125        self.writer.flush()
126    }
127}
128
129/// Pack a ratatui Color into a u32 for wire format.
130///
131/// Encoding: `0x01_RR_GG_BB` for RGB, `0x02_00_00_II` for indexed, ordinal for named.
132pub fn pack_color(color: Color) -> u32 {
133    match color {
134        Color::Reset => 0,
135        Color::Black => 1,
136        Color::Red => 2,
137        Color::Green => 3,
138        Color::Yellow => 4,
139        Color::Blue => 5,
140        Color::Magenta => 6,
141        Color::Cyan => 7,
142        Color::Gray => 8,
143        Color::DarkGray => 9,
144        Color::LightRed => 10,
145        Color::LightGreen => 11,
146        Color::LightYellow => 12,
147        Color::LightBlue => 13,
148        Color::LightMagenta => 14,
149        Color::LightCyan => 15,
150        Color::White => 16,
151        Color::Rgb(r, g, b) => 0x0100_0000 | ((r as u32) << 16) | ((g as u32) << 8) | (b as u32),
152        Color::Indexed(i) => 0x0200_0000 | (i as u32),
153    }
154}
155
156/// Unpack a u32 into a ratatui Color.
157pub fn unpack_color(packed: u32) -> Color {
158    if packed & 0x0200_0000 != 0 {
159        Color::Indexed((packed & 0xFF) as u8)
160    } else if packed & 0x0100_0000 != 0 {
161        Color::Rgb(
162            ((packed >> 16) & 0xFF) as u8,
163            ((packed >> 8) & 0xFF) as u8,
164            (packed & 0xFF) as u8,
165        )
166    } else {
167        match packed {
168            0 => Color::Reset,
169            1 => Color::Black,
170            2 => Color::Red,
171            3 => Color::Green,
172            4 => Color::Yellow,
173            5 => Color::Blue,
174            6 => Color::Magenta,
175            7 => Color::Cyan,
176            8 => Color::Gray,
177            9 => Color::DarkGray,
178            10 => Color::LightRed,
179            11 => Color::LightGreen,
180            12 => Color::LightYellow,
181            13 => Color::LightBlue,
182            14 => Color::LightMagenta,
183            15 => Color::LightCyan,
184            16 => Color::White,
185            _ => Color::Reset,
186        }
187    }
188}
189
190/// Decode structured cells from a binary buffer.
191///
192/// Returns `(cols, rows, cells)` where cells is a vec of `(x, y, symbol, fg, bg, modifiers)`.
193pub fn decode_structured(data: &[u8]) -> io::Result<(u16, u16, Vec<DecodedCell>)> {
194    if data.len() < 8 || data[..4] != STRUCTURED_MAGIC {
195        return Err(io::Error::new(
196            io::ErrorKind::InvalidData,
197            "invalid structured frame magic",
198        ));
199    }
200
201    let cols = u16::from_le_bytes([data[4], data[5]]);
202    let rows = u16::from_le_bytes([data[6], data[7]]);
203    let mut cells = Vec::new();
204    let mut pos = 8;
205
206    while pos < data.len() {
207        if pos + 5 > data.len() {
208            break;
209        }
210        let x = u16::from_le_bytes([data[pos], data[pos + 1]]);
211        let y = u16::from_le_bytes([data[pos + 2], data[pos + 3]]);
212        let sym_len = data[pos + 4] as usize;
213        pos += 5;
214
215        if pos + sym_len + 10 > data.len() {
216            break;
217        }
218        let symbol = String::from_utf8_lossy(&data[pos..pos + sym_len]).to_string();
219        pos += sym_len;
220
221        let fg = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
222        pos += 4;
223        let bg = u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]);
224        pos += 4;
225        let mods = u16::from_le_bytes([data[pos], data[pos + 1]]);
226        pos += 2;
227
228        cells.push(DecodedCell {
229            x,
230            y,
231            symbol,
232            fg: unpack_color(fg),
233            bg: unpack_color(bg),
234            modifiers: Modifier::from_bits_retain(mods),
235        });
236    }
237
238    Ok((cols, rows, cells))
239}
240
241/// A decoded cell from structured binary data.
242#[derive(Debug, Clone)]
243pub struct DecodedCell {
244    pub x: u16,
245    pub y: u16,
246    pub symbol: String,
247    pub fg: Color,
248    pub bg: Color,
249    pub modifiers: Modifier,
250}
251
252// ============================================================================
253// Tests
254// ============================================================================
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259    use ratatui::buffer::Buffer;
260    use ratatui::layout::Rect;
261    use ratatui::style::Style;
262
263    #[test]
264    fn test_binary_layout() {
265        let mut buf = Vec::new();
266        let mut backend = StructuredBackend::new(&mut buf, 2, 1);
267
268        let rect = Rect::new(0, 0, 2, 1);
269        let mut buffer = Buffer::empty(rect);
270        buffer[(0, 0)].set_symbol("A");
271        buffer[(1, 0)].set_symbol("B");
272
273        let cells: Vec<_> = buffer
274            .content()
275            .iter()
276            .enumerate()
277            .map(|(i, cell)| {
278                let x = (i % 2) as u16;
279                let y = (i / 2) as u16;
280                (x, y, cell)
281            })
282            .collect();
283
284        backend.draw(cells.into_iter()).unwrap();
285
286        // Verify magic header
287        assert_eq!(&buf[..4], &STRUCTURED_MAGIC);
288        // Verify dimensions
289        assert_eq!(u16::from_le_bytes([buf[4], buf[5]]), 2);
290        assert_eq!(u16::from_le_bytes([buf[6], buf[7]]), 1);
291    }
292
293    #[test]
294    fn test_roundtrip() {
295        let mut buf = Vec::new();
296        let mut backend = StructuredBackend::new(&mut buf, 3, 1);
297
298        let rect = Rect::new(0, 0, 3, 1);
299        let mut buffer = Buffer::empty(rect);
300        buffer[(0, 0)]
301            .set_symbol("X")
302            .set_style(Style::new().fg(Color::Red).bg(Color::Blue));
303        buffer[(1, 0)].set_symbol("Y");
304        buffer[(2, 0)]
305            .set_symbol("Z")
306            .set_style(Style::new().fg(Color::Rgb(255, 128, 0)));
307
308        let cells: Vec<_> = buffer
309            .content()
310            .iter()
311            .enumerate()
312            .map(|(i, cell)| {
313                let x = (i % 3) as u16;
314                let y = (i / 3) as u16;
315                (x, y, cell)
316            })
317            .collect();
318
319        backend.draw(cells.into_iter()).unwrap();
320
321        let (cols, rows, decoded) = decode_structured(&buf).unwrap();
322        assert_eq!(cols, 3);
323        assert_eq!(rows, 1);
324        assert_eq!(decoded.len(), 3);
325        assert_eq!(decoded[0].symbol, "X");
326        assert_eq!(decoded[0].fg, Color::Red);
327        assert_eq!(decoded[0].bg, Color::Blue);
328        assert_eq!(decoded[2].fg, Color::Rgb(255, 128, 0));
329    }
330
331    #[test]
332    fn test_color_roundtrip() {
333        let colors = [
334            Color::Reset,
335            Color::Black,
336            Color::Red,
337            Color::White,
338            Color::Rgb(255, 128, 0),
339            Color::Indexed(42),
340        ];
341        for c in &colors {
342            assert_eq!(
343                unpack_color(pack_color(*c)),
344                *c,
345                "roundtrip failed for {:?}",
346                c
347            );
348        }
349    }
350
351    #[test]
352    fn test_size_returns_config() {
353        let buf = Vec::new();
354        let backend = StructuredBackend::new(buf, 120, 40);
355        assert_eq!(backend.size().unwrap(), Size::new(120, 40));
356    }
357}