Skip to main content

waxterm/
backend.rs

1//! Minimal ANSI terminal backend for ratatui.
2//! Works under WASI by writing escape sequences directly to stdout.
3//! No platform-specific APIs needed.
4
5use std::io::{self, Write};
6
7use ratatui::{
8    backend::{Backend, ClearType, WindowSize},
9    buffer::Cell,
10    layout::{Position, Size},
11    style::{Color, Modifier},
12};
13
14// Re-export SGR functions for backward compatibility
15pub use crate::sgr::{write_bg_params, write_combined_sgr, write_fg_params};
16
17/// A backend that writes ANSI escape codes to any `Write` sink.
18pub struct AnsiBackend<W: Write> {
19    writer: W,
20    width: u16,
21    height: u16,
22    /// Optional Wanix pipe heartbeat bytes (60 cursor-move sequences).
23    /// Built once in `new()` to avoid 60 format calls per frame.
24    /// None on native terminals where heartbeat is unnecessary.
25    heartbeat: Option<Box<[u8]>>,
26}
27
28impl<W: Write> AnsiBackend<W> {
29    pub fn new(writer: W, width: u16, height: u16, heartbeat: bool) -> Self {
30        let heartbeat = if heartbeat {
31            Some(
32                (1u16..=60)
33                    .flat_map(|col| format!("\x1b[{};{}H", height, col).into_bytes())
34                    .collect(),
35            )
36        } else {
37            None
38        };
39        AnsiBackend {
40            writer,
41            width,
42            height,
43            heartbeat,
44        }
45    }
46
47    /// Resize the backend dimensions. Caller must clear + redraw after.
48    pub fn resize(&mut self, width: u16, height: u16) {
49        self.width = width;
50        self.height = height;
51    }
52
53    /// Borrow the underlying writer (e.g. `&Vec<u8>` for off-screen rendering).
54    pub fn writer(&self) -> &W {
55        &self.writer
56    }
57
58    fn write_csi(&mut self, args: &str) -> io::Result<()> {
59        write!(self.writer, "\x1b[{}", args)
60    }
61}
62
63impl<W: Write> Backend for AnsiBackend<W> {
64    type Error = io::Error;
65
66    fn draw<'a, I>(&mut self, content: I) -> Result<(), Self::Error>
67    where
68        I: Iterator<Item = (u16, u16, &'a Cell)>,
69    {
70        let mut last_pos: Option<(u16, u16)> = None;
71        let mut last_fg: Option<Color> = None;
72        let mut last_bg: Option<Color> = None;
73        let mut last_mods: Option<Modifier> = None;
74
75        for (x, y, cell) in content {
76            let need_move = match last_pos {
77                Some((lx, ly)) => !(ly == y && lx + 1 == x),
78                None => true,
79            };
80
81            if need_move {
82                write!(self.writer, "\x1b[{};{}H", y + 1, x + 1)?;
83            }
84
85            // Emit a single combined SGR sequence when any style component changes,
86            // instead of separate reset + modifiers + fg + bg sequences.
87            let fg_changed = last_fg != Some(cell.fg);
88            let bg_changed = last_bg != Some(cell.bg);
89            let mods_changed = last_mods != Some(cell.modifier);
90
91            if fg_changed || bg_changed || mods_changed {
92                write_combined_sgr(&mut self.writer, cell.fg, cell.bg, cell.modifier)?;
93                last_fg = Some(cell.fg);
94                last_bg = Some(cell.bg);
95                last_mods = Some(cell.modifier);
96            }
97
98            self.writer.write_all(cell.symbol().as_bytes())?;
99            last_pos = Some((x, y));
100        }
101
102        self.write_csi("0m")?;
103
104        // Wanix VFS pipe heartbeat: cursor moves on the last row.
105        //
106        // The Wanix pipe accumulates small writes and delivers them in 1024-byte
107        // chunks to the JS ReadableStream reader. During idle periods (no cell
108        // changes), each render frame produces only the 4-byte SGR reset above.
109        // At 30fps this gives ~120 bytes/s — far below the 1024-byte delivery
110        // threshold — causing multi-second write gaps.
111        //
112        // Cursor moves to different columns are each ~9 bytes and have no visual
113        // effect when the cursor is hidden. Writing 60 of them adds ~540 bytes,
114        // bringing idle frames closer to the 1024-byte threshold.
115        if let Some(ref hb) = self.heartbeat {
116            self.writer.write_all(hb)?;
117        }
118
119        self.writer.flush()
120    }
121
122    fn hide_cursor(&mut self) -> Result<(), Self::Error> {
123        self.write_csi("?25l")?;
124        self.writer.flush()
125    }
126
127    fn show_cursor(&mut self) -> Result<(), Self::Error> {
128        self.write_csi("?25h")?;
129        self.writer.flush()
130    }
131
132    fn get_cursor_position(&mut self) -> Result<Position, Self::Error> {
133        Ok(Position::new(0, 0))
134    }
135
136    fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> Result<(), Self::Error> {
137        let pos = position.into();
138        write!(self.writer, "\x1b[{};{}H", pos.y + 1, pos.x + 1)?;
139        self.writer.flush()
140    }
141
142    fn clear(&mut self) -> Result<(), Self::Error> {
143        self.write_csi("2J")?;
144        self.write_csi("H")?;
145        self.writer.flush()
146    }
147
148    fn clear_region(&mut self, clear_type: ClearType) -> Result<(), Self::Error> {
149        match clear_type {
150            ClearType::All => self.write_csi("2J")?,
151            ClearType::AfterCursor => self.write_csi("0J")?,
152            ClearType::BeforeCursor => self.write_csi("1J")?,
153            ClearType::CurrentLine => self.write_csi("2K")?,
154            ClearType::UntilNewLine => self.write_csi("0K")?,
155        }
156        self.writer.flush()
157    }
158
159    fn size(&self) -> Result<Size, Self::Error> {
160        Ok(Size::new(self.width, self.height))
161    }
162
163    fn window_size(&mut self) -> Result<WindowSize, Self::Error> {
164        Ok(WindowSize {
165            columns_rows: Size::new(self.width, self.height),
166            pixels: Size::new(0, 0),
167        })
168    }
169
170    fn flush(&mut self) -> Result<(), Self::Error> {
171        self.writer.flush()
172    }
173}
174
175// SGR functions are now in crate::sgr module, re-exported above via `pub use`.