Guide API
Skip to main content

tvision_rs/screen/
snapshot.rs

1//! Deterministic textual rendering of a [`Buffer`] for golden snapshot tests.
2//!
3//! This is the verification backbone of the framework: every widget test diffs
4//! its `HeadlessBackend` screen against a golden string produced here. The
5//! format is therefore frozen here, once — not improvised per test.
6//!
7//! ## Format
8//!
9//! [`snapshot`] renders three layers plus cursor metadata, with **no
10//! timestamps** (so goldens are stable):
11//!
12//! ```text
13//! size: 10x3
14//! cursor: 5,0
15//! text:
16//! |Hello     |
17//! |World     |
18//! |          |
19//! attr:
20//! |aaaaa.....|
21//! |bbbbb.....|
22//! |..........|
23//! legend:
24//!   . default
25//!   a fg=BIOS(15) bg=BIOS(1)
26//!   b fg=RGB(255,0,0) bg=default +bold
27//! ```
28//!
29//! - **text layer** — the on-screen glyphs, one framed line per row. Each line
30//!   is bounded by `|` so trailing spaces stay visible in the golden file (the
31//!   leading/trailing `|` are frame delimiters, identified by position, not
32//!   content — note box-drawing uses U+2502 `│`, distinct from ASCII `|`).
33//! - **attr layer** — one key char per *display column*, aligned beneath the
34//!   text. `.` is always the default style; other styles are keyed `a..z`,
35//!   `A..Z`, `0..9` in row-major first-appearance order.
36//! - **legend** — key → style description (`fg=… bg=… [+mod…]`), `.` first,
37//!   then the rest in assignment order.
38//! - **cursor** — `x,y` when shown, or `hidden`.
39//!
40//! ## Wide glyphs
41//!
42//! A double-width grapheme occupies a `wide` lead cell plus a `trail` cell in
43//! the buffer. In the snapshot the lead contributes its 2-column glyph to the
44//! text layer and its key **twice** to the attr layer; the trail cell is
45//! absorbed (contributes nothing). So both layers are exactly `width` display
46//! columns wide and stay aligned.
47//!
48//! # Turbo Vision heritage
49//! **tvision-rs extension**: no Turbo Vision counterpart. It serializes the screen
50//! grid to a stable golden string so the framework can be verified with snapshot
51//! tests rather than a live terminal (deviation D11).
52
53use crate::color::{Color, Style};
54use crate::screen::{Buffer, Cell};
55
56/// The cursor state for a snapshot: `Some((x, y))` when visible at that cell,
57/// `None` when hidden.
58pub type SnapshotCursor = Option<(u16, u16)>;
59
60/// Render `buffer` (and the `cursor` state) to the canonical golden-snapshot
61/// string documented on this module.
62///
63/// Pass the result to `insta::assert_snapshot!`. The output is fully
64/// deterministic — same buffer + cursor always yields the same string, with no
65/// timestamps or addresses.
66///
67/// # Panics
68/// Panics if the buffer contains more than 63 distinct styles (the 1-char-key
69/// legend is exhausted). Real widget tests use a handful of styles; a test that
70/// genuinely needs more should be split.
71pub fn snapshot(buffer: &Buffer, cursor: SnapshotCursor) -> String {
72    let mut legend = Legend::new();
73    let width = buffer.width();
74    let height = buffer.height();
75
76    let mut text = String::new();
77    let mut attr = String::new();
78
79    for y in 0..height {
80        text.push('|');
81        attr.push('|');
82        let mut x = 0;
83        while x < width {
84            let cell = buffer.get(x, y);
85            if cell.is_wide_trail() {
86                // Absorbed by the preceding wide lead; contributes nothing.
87                x += 1;
88                continue;
89            }
90            let key = legend.key_for(cell.style());
91            let cols = display_cols(cell);
92            // Text layer: the glyph itself already spans `cols` display columns.
93            text.push_str(cell.symbol());
94            // Attr layer: one key per display column.
95            for _ in 0..cols {
96                attr.push(key);
97            }
98            x += 1;
99        }
100        text.push('|');
101        attr.push('|');
102        text.push('\n');
103        attr.push('\n');
104    }
105
106    let mut out = String::new();
107    out.push_str(&format!("size: {width}x{height}\n"));
108    match cursor {
109        Some((cx, cy)) => out.push_str(&format!("cursor: {cx},{cy}\n")),
110        None => out.push_str("cursor: hidden\n"),
111    }
112    out.push_str("text:\n");
113    out.push_str(&text);
114    out.push_str("attr:\n");
115    out.push_str(&attr);
116    out.push_str("legend:\n");
117    out.push_str(&legend.render());
118    out
119}
120
121/// Display columns a cell occupies: a `wide` lead is 2, anything else is 1.
122/// (Trail cells are handled by the caller and never reach here.)
123fn display_cols(cell: &Cell) -> usize {
124    if cell.is_wide() { 2 } else { 1 }
125}
126
127/// Assigns a stable one-character key to each distinct [`Style`], reserving `.`
128/// for the default style.
129struct Legend {
130    /// (key, style) in assignment order; `.`/default is always first.
131    entries: Vec<(char, Style)>,
132}
133
134impl Legend {
135    fn new() -> Self {
136        Legend {
137            entries: vec![('.', Style::default())],
138        }
139    }
140
141    /// The key for `style`, assigning a fresh one on first sighting.
142    fn key_for(&mut self, style: Style) -> char {
143        if let Some(&(key, _)) = self.entries.iter().find(|&&(_, s)| s == style) {
144            return key;
145        }
146        let key = nth_key(self.entries.len() - 1); // -1: default doesn't consume the a/b/c… space
147        self.entries.push((key, style));
148        key
149    }
150
151    /// The `legend:` body, one `  <key> <desc>` line per style. The default
152    /// style is shown as the shorthand `default`.
153    fn render(&self) -> String {
154        let mut s = String::new();
155        for &(key, style) in &self.entries {
156            let desc = if style == Style::default() {
157                "default".to_string()
158            } else {
159                describe_style(style)
160            };
161            s.push_str(&format!("  {key} {desc}\n"));
162        }
163        s
164    }
165}
166
167/// The `n`-th legend key (0-based) over the alphabet `a..z`, `A..Z`, `0..9`.
168fn nth_key(n: usize) -> char {
169    const KEYS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
170    *KEYS
171        .get(n)
172        .expect("snapshot legend exhausted: more than 63 distinct styles in one buffer") as char
173}
174
175/// Human-readable one-line style description, e.g. `fg=BIOS(15) bg=default +bold +reverse`.
176fn describe_style(style: Style) -> String {
177    let mut s = format!(
178        "fg={} bg={}",
179        describe_color(style.fg),
180        describe_color(style.bg)
181    );
182    let m = style.modifiers;
183    for (on, name) in [
184        (m.bold, "bold"),
185        (m.italic, "italic"),
186        (m.underline, "underline"),
187        (m.blink, "blink"),
188        (m.reverse, "reverse"),
189        (m.strike, "strike"),
190        (m.no_shadow, "no_shadow"),
191    ] {
192        if on {
193            s.push_str(" +");
194            s.push_str(name);
195        }
196    }
197    s
198}
199
200/// Human-readable color, matching the [`Color`] variants.
201fn describe_color(color: Color) -> String {
202    match color {
203        Color::Default => "default".to_string(),
204        Color::Bios(n) => format!("BIOS({n})"),
205        Color::Indexed(n) => format!("idx({n})"),
206        Color::Rgb(r, g, b) => format!("RGB({r},{g},{b})"),
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use crate::color::{Color, Style};
214
215    #[test]
216    fn blank_buffer_is_all_default() {
217        let buf = Buffer::new(3, 2);
218        let s = snapshot(&buf, None);
219        assert_eq!(
220            s,
221            "size: 3x2\n\
222             cursor: hidden\n\
223             text:\n\
224             |   |\n\
225             |   |\n\
226             attr:\n\
227             |...|\n\
228             |...|\n\
229             legend:\n\
230             \x20\x20. default\n"
231        );
232    }
233
234    #[test]
235    fn text_and_styles_with_legend() {
236        let mut buf = Buffer::new(5, 1);
237        let a = Style::new(Color::Bios(0xF), Color::Bios(0x1));
238        for (i, ch) in "Hi".chars().enumerate() {
239            let c = buf.get_mut(i as u16, 0);
240            c.set_char(ch);
241            c.set_style(a);
242        }
243        let s = snapshot(&buf, Some((2, 0)));
244        let expected = "size: 5x1\n\
245             cursor: 2,0\n\
246             text:\n\
247             |Hi   |\n\
248             attr:\n\
249             |aa...|\n\
250             legend:\n\
251             \x20\x20. default\n\
252             \x20\x20a fg=BIOS(15) bg=BIOS(1)\n";
253        assert_eq!(s, expected);
254    }
255
256    #[test]
257    fn wide_glyph_lead_keyed_twice_trail_absorbed() {
258        let mut buf = Buffer::new(4, 1);
259        let a = Style::new(Color::Rgb(255, 0, 0), Color::Default);
260        buf.get_mut(0, 0).set_str("中", true);
261        buf.get_mut(0, 0).set_style(a);
262        buf.get_mut(1, 0).set_wide_trail();
263        let s = snapshot(&buf, None);
264        // text: 中 (2 cols) then two blanks = 4 display cols.
265        // attr: lead key twice, then two defaults.
266        let expected = "size: 4x1\n\
267             cursor: hidden\n\
268             text:\n\
269             |中  |\n\
270             attr:\n\
271             |aa..|\n\
272             legend:\n\
273             \x20\x20. default\n\
274             \x20\x20a fg=RGB(255,0,0) bg=default\n";
275        assert_eq!(s, expected);
276    }
277
278    #[test]
279    fn modifiers_are_described() {
280        let mut buf = Buffer::new(1, 1);
281        let mut style = Style::new(Color::Default, Color::Default);
282        style.modifiers.bold = true;
283        style.modifiers.reverse = true;
284        buf.get_mut(0, 0).set_style(style);
285        let s = snapshot(&buf, None);
286        assert!(
287            s.contains("a fg=default bg=default +bold +reverse"),
288            "got:\n{s}"
289        );
290    }
291
292    #[test]
293    fn default_style_always_keyed_dot_even_if_seen_later() {
294        // A non-default style appears first (cell 0), default second (cell 1).
295        let mut buf = Buffer::new(2, 1);
296        buf.get_mut(0, 0)
297            .set_style(Style::new(Color::Bios(2), Color::Default));
298        let s = snapshot(&buf, None);
299        // cell 0 -> 'a', cell 1 (default) -> '.'
300        assert!(s.contains("|a.|"), "attr row wrong:\n{s}");
301    }
302}