crates/tui-termion/src/backend.rs 7.0 KiB raw
1
//! Termion-backed terminal output.
2
3
use std::io::{self, Write};
4
5
use rustik_tui_core as tui_core;
6
use tui_core::backend::Backend;
7
use tui_core::buffer::DirtyRun;
8
use tui_core::layout::Point;
9
use tui_core::{PaintMode, Size, Style};
10
11
/// Termion-backed terminal output.
12
#[derive(Debug)]
13
pub struct TermionBackend<W> {
14
    writer: W,
15
    paint: PaintMode,
16
}
17
18
impl<W> TermionBackend<W> {
19
    /// Creates a backend that writes ANSI styling escapes.
20
    pub fn new(writer: W) -> Self {
21
        Self {
22
            writer,
23
            paint: PaintMode::Styled,
24
        }
25
    }
26
27
    /// Creates a backend that writes no ANSI styling escapes.
28
    pub fn plain(writer: W) -> Self {
29
        Self {
30
            writer,
31
            paint: PaintMode::Plain,
32
        }
33
    }
34
35
    /// Returns the wrapped writer.
36
    pub fn into_inner(self) -> W {
37
        self.writer
38
    }
39
}
40
41
impl<W: Write> Backend for TermionBackend<W> {
42
    type Error = io::Error;
43
44
    fn size(&mut self) -> Result<Size, Self::Error> {
45
        let (cols, rows) = termion::terminal_size()?;
46
47
        Ok(Size::new(cols as usize, rows as usize))
48
    }
49
50
    fn draw(&mut self, runs: &[DirtyRun<'_>]) -> Result<(), Self::Error> {
51
        for run in runs {
52
            write!(
53
                self.writer,
54
                "{}",
55
                termion::cursor::Goto(coord(run.x), coord(run.y))
56
            )?;
57
            match self.paint {
58
                PaintMode::Plain => self.draw_plain_cells(run.cells)?,
59
                PaintMode::Styled => self.draw_styled_cells(run.cells)?,
60
            }
61
        }
62
        Ok(())
63
    }
64
65
    fn clear(&mut self) -> Result<(), Self::Error> {
66
        write!(self.writer, "{}", termion::clear::All)
67
    }
68
69
    fn flush(&mut self) -> Result<(), Self::Error> {
70
        self.writer.flush()
71
    }
72
73
    fn set_cursor_position(&mut self, point: Point) -> Result<(), Self::Error> {
74
        write!(
75
            self.writer,
76
            "{}",
77
            termion::cursor::Goto(coord(point.x), coord(point.y))
78
        )
79
    }
80
81
    fn set_cursor_visible(&mut self, visible: bool) -> Result<(), Self::Error> {
82
        if visible {
83
            write!(self.writer, "{}", termion::cursor::Show)
84
        } else {
85
            write!(self.writer, "{}", termion::cursor::Hide)
86
        }
87
    }
88
}
89
90
impl<W: Write> TermionBackend<W> {
91
    /// Writes cells without ANSI styling.
92
    fn draw_plain_cells(&mut self, cells: &[tui_core::buffer::Cell]) -> io::Result<()> {
93
        for cell in cells {
94
            if cell.is_continuation() {
95
                continue;
96
            }
97
            self.writer.write_all(cell.glyph().as_bytes())?;
98
        }
99
        Ok(())
100
    }
101
102
    /// Writes cells while keeping one ANSI style active across matching cells.
103
    fn draw_styled_cells(&mut self, cells: &[tui_core::buffer::Cell]) -> io::Result<()> {
104
        let mut style = Style::default();
105
106
        for cell in cells {
107
            if cell.is_continuation() {
108
                continue;
109
            }
110
            let next = cell.style();
111
            if next != style {
112
                self.write_style_suffix(style)?;
113
                self.write_style_prefix(next)?;
114
                style = next;
115
            }
116
            self.writer.write_all(cell.glyph().as_bytes())?;
117
        }
118
        self.write_style_suffix(style)
119
    }
120
121
    /// Writes the ANSI prefix for `style`.
122
    fn write_style_prefix(&mut self, style: Style) -> io::Result<()> {
123
        let mut text = String::new();
124
        style
125
            .fmt_prefix(&mut text)
126
            .map_err(|_| io::Error::other("write_style_prefix: failed to format style prefix"))?;
127
        self.writer.write_all(text.as_bytes())
128
    }
129
130
    /// Writes the ANSI suffix for `style`.
131
    fn write_style_suffix(&mut self, style: Style) -> io::Result<()> {
132
        let mut text = String::new();
133
        style
134
            .fmt_suffix(&mut text)
135
            .map_err(|_| io::Error::other("write_style_suffix: failed to format style suffix"))?;
136
        self.writer.write_all(text.as_bytes())
137
    }
138
}
139
140
/// Converts a zero-based coordinate into a terminal coordinate.
141
fn coord(value: usize) -> u16 {
142
    u16::try_from(value.saturating_add(1)).unwrap_or(u16::MAX)
143
}
144
145
#[cfg(test)]
146
#[allow(clippy::unwrap_used)]
147
mod tests {
148
    use super::*;
149
    use tui_core::{Buffer, Color, Rect, Style};
150
151
    #[test]
152
    fn termion_backend_writes_dirty_runs_with_one_based_coordinates() {
153
        let cells = [tui_core::buffer::Cell::new('x', Style::default())];
154
        let run = DirtyRun {
155
            x: 2,
156
            y: 3,
157
            cells: &cells,
158
        };
159
        let mut backend = TermionBackend::new(Vec::new());
160
161
        backend.draw(&[run]).unwrap();
162
        backend.flush().unwrap();
163
        let out = String::from_utf8(backend.into_inner()).unwrap();
164
165
        assert!(out.starts_with("\x1B[4;3H"));
166
        assert!(out.ends_with('x'));
167
    }
168
169
    #[test]
170
    fn termion_backend_paint_mode_is_explicit() {
171
        let cells = [tui_core::buffer::Cell::new('x', Color::Red.style())];
172
        let run = DirtyRun {
173
            x: 0,
174
            y: 0,
175
            cells: &cells,
176
        };
177
178
        let mut styled = TermionBackend::new(Vec::new());
179
        styled.draw(&[run]).unwrap();
180
        assert!(
181
            String::from_utf8(styled.into_inner())
182
                .unwrap()
183
                .contains("\x1B[31m")
184
        );
185
186
        let mut plain = TermionBackend::plain(Vec::new());
187
        plain.draw(&[run]).unwrap();
188
        let out = String::from_utf8(plain.into_inner()).unwrap();
189
190
        assert_eq!(out, "\x1B[1;1Hx");
191
    }
192
193
    #[test]
194
    fn termion_backend_keeps_matching_cell_styles_active() {
195
        let cells = [
196
            tui_core::buffer::Cell::new('x', Color::Red.style()),
197
            tui_core::buffer::Cell::new('y', Color::Red.style()),
198
        ];
199
        let run = DirtyRun {
200
            x: 0,
201
            y: 0,
202
            cells: &cells,
203
        };
204
        let mut backend = TermionBackend::new(Vec::new());
205
206
        backend.draw(&[run]).unwrap();
207
        let out = String::from_utf8(backend.into_inner()).unwrap();
208
209
        assert_eq!(out, "\x1B[1;1H\x1B[31mxy\x1B[0m");
210
    }
211
212
    #[test]
213
    fn termion_backend_does_not_write_wide_continuation_cells() {
214
        let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1));
215
        buffer.reset_dirty();
216
        buffer.set_str(0, 0, "๐Ÿa", Style::default());
217
        let runs = buffer.dirty_runs();
218
        let mut backend = TermionBackend::new(Vec::new());
219
220
        backend.draw(&runs).unwrap();
221
        let out = String::from_utf8(backend.into_inner()).unwrap();
222
223
        assert!(out.ends_with("๐Ÿa"));
224
        assert!(!out.ends_with("๐Ÿ a"));
225
    }
226
227
    #[test]
228
    fn termion_backend_cursor_and_visibility_commands_are_written() {
229
        let mut backend = TermionBackend::new(Vec::new());
230
231
        backend.set_cursor_visible(false).unwrap();
232
        backend.set_cursor_position(Point::new(1, 2)).unwrap();
233
        backend.set_cursor_visible(true).unwrap();
234
        let out = String::from_utf8(backend.into_inner()).unwrap();
235
236
        assert!(out.contains("\x1B[?25l"));
237
        assert!(out.contains("\x1B[3;2H"));
238
        assert!(out.contains("\x1B[?25h"));
239
    }
240
}