Guide API
Skip to main content

tvision_rs/screen/
buffer.rs

1//! `Buffer`, the render back-buffer and cell diff (documented on the type).
2//
3// Portions adapted from ratatui (https://github.com/ratatui-org/ratatui),
4// licensed under the MIT License. Copyright (c) 2023-2024 The Ratatui Developers.
5
6use crate::screen::Cell;
7
8/// In-memory screen grid; the render target for one complete frame.
9///
10/// Render back-buffer and cell diff.
11///
12/// [`Buffer`] is the in-memory screen grid: the whole view tree is painted into
13/// it each frame, then [`Buffer::diff`] compares it against the previous frame so
14/// only changed cells are flushed to the terminal.
15///
16/// The diff algorithm is adapted from ratatui's `Buffer::diff` (MIT). Our `Cell`
17/// (see `cell.rs`) already encodes double-width glyphs with explicit
18/// `wide`/`trail` flags, so the wide-char skipping is driven off those rather
19/// than off `unicode-width`. ratatui's `skip` field is dropped — tvision-rs repaints
20/// the whole tree, so there is nothing to opt out of.
21///
22/// Call [`Buffer::new`] to create a blank grid sized to the terminal, paint the
23/// full view tree into it via the renderer, then call [`Buffer::diff`] against
24/// the previous frame's buffer to obtain only the changed cells to flush to the
25/// terminal. The `Program` root owns two buffers (current and previous) and
26/// swaps them each iteration of the event loop.
27///
28/// Unlike ratatui, `Buffer` stores only `width` × `height` rather than an
29/// `area: Rect`, because the back buffer is always screen-origin (`(0, 0)` to
30/// `(width-1, height-1)`). There is no offset to carry.
31///
32/// # Turbo Vision heritage
33///
34/// Replaces Turbo Vision's per-view incremental screen writes with a
35/// double-buffered whole-tree repaint plus cell diff (deviation D8). The grid
36/// and diff are adapted from ratatui rather than ported from the original.
37///
38/// Replaces `TVideoBuf` (a fixed 80×25 word array of `char+attr` cells) and
39/// the per-view incremental `writeView` calls. The dynamic-size grid and
40/// double-buffered whole-tree repaint follow magiblot/tvision's modernised
41/// screen model rather than the original fixed-buffer approach.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct Buffer {
44    width: u16,
45    height: u16,
46    /// Row-major cell storage; length == `width * height`.
47    content: Vec<Cell>,
48}
49
50impl Buffer {
51    /// A new buffer filled with [`Cell::default()`] (a blank space, default style).
52    pub fn new(width: u16, height: u16) -> Self {
53        let len = width as usize * height as usize;
54        Buffer {
55            width,
56            height,
57            content: vec![Cell::default(); len],
58        }
59    }
60
61    /// A new buffer where every cell is a clone of `cell`.
62    pub fn filled(width: u16, height: u16, cell: Cell) -> Self {
63        let len = width as usize * height as usize;
64        Buffer {
65            width,
66            height,
67            content: vec![cell; len],
68        }
69    }
70
71    /// The buffer width in columns.
72    pub fn width(&self) -> u16 {
73        self.width
74    }
75
76    /// The buffer height in rows.
77    pub fn height(&self) -> u16 {
78        self.height
79    }
80
81    /// Total number of cells (`width * height`).
82    pub fn area_len(&self) -> usize {
83        self.width as usize * self.height as usize
84    }
85
86    /// Convert `(x, y)` to a linear index into `content`.
87    ///
88    /// Panics in debug builds if `x >= width` or `y >= height`.
89    pub fn index_of(&self, x: u16, y: u16) -> usize {
90        debug_assert!(
91            x < self.width && y < self.height,
92            "index_of({x}, {y}) out of bounds for {w}×{h} buffer",
93            w = self.width,
94            h = self.height,
95        );
96        // Cast to usize *before* multiplying to avoid u16 overflow.
97        y as usize * self.width as usize + x as usize
98    }
99
100    /// Convert a linear index back to `(x, y)`.
101    pub fn pos_of(&self, i: usize) -> (u16, u16) {
102        let w = self.width as usize;
103        // Widths of 0 would be degenerate; guard in debug.
104        debug_assert!(w > 0, "pos_of called on zero-width buffer");
105        ((i % w) as u16, (i / w) as u16)
106    }
107
108    /// Return a shared reference to the cell at `(x, y)`.
109    pub fn get(&self, x: u16, y: u16) -> &Cell {
110        let i = self.index_of(x, y);
111        &self.content[i]
112    }
113
114    /// Return a mutable reference to the cell at `(x, y)`.
115    pub fn get_mut(&mut self, x: u16, y: u16) -> &mut Cell {
116        let i = self.index_of(x, y);
117        &mut self.content[i]
118    }
119
120    /// A slice over all cells in row-major order (for tests / snapshots).
121    pub fn cells(&self) -> &[Cell] {
122        &self.content
123    }
124
125    /// A shared slice over row `y` (`width` cells), for width-aware row writes.
126    ///
127    /// Panics in debug builds if `y >= height`.
128    pub fn row(&self, y: u16) -> &[Cell] {
129        debug_assert!(
130            y < self.height,
131            "row({y}) out of bounds for height {}",
132            self.height
133        );
134        let w = self.width as usize;
135        let start = y as usize * w;
136        &self.content[start..start + w]
137    }
138
139    /// A mutable slice over row `y` (`width` cells), for width-aware row writes
140    /// (e.g. feeding `text::draw_str` a clipped sub-slice).
141    ///
142    /// Panics in debug builds if `y >= height`.
143    pub fn row_mut(&mut self, y: u16) -> &mut [Cell] {
144        debug_assert!(
145            y < self.height,
146            "row_mut({y}) out of bounds for height {}",
147            self.height
148        );
149        let w = self.width as usize;
150        let start = y as usize * w;
151        &mut self.content[start..start + w]
152    }
153
154    /// Reset every cell to [`Cell::default()`].
155    pub fn reset(&mut self) {
156        for cell in &mut self.content {
157            *cell = Cell::default();
158        }
159    }
160
161    /// Resize the buffer to `width × height`, resetting all content to
162    /// [`Cell::default()`].
163    pub fn resize(&mut self, width: u16, height: u16) {
164        let len = width as usize * height as usize;
165        self.width = width;
166        self.height = height;
167        self.content = vec![Cell::default(); len];
168    }
169
170    /// Compare `self` (the previous/front buffer) against `other` (the
171    /// next/back buffer) and return the cells in `other` that differ.
172    ///
173    /// Each entry is `(x, y, &cell)` pointing into `other`.
174    ///
175    /// Both buffers must have the same dimensions. The invariant is asserted in
176    /// debug builds; in release the comparison is limited to the overlapping
177    /// index range.
178    ///
179    /// The algorithm is adapted from ratatui's `Buffer::diff`: it iterates the
180    /// flat cell array, suppressing the trail cell of a wide glyph via
181    /// `to_skip`, and using `invalidated` to force repainting the cell that
182    /// follows a cell whose *previous* width was greater than its *current*
183    /// width (e.g. a wide glyph replaced by a narrow one — the trail cell must
184    /// be repainted even if it happens to be equal to the old trail cell).
185    pub fn diff<'a>(&self, other: &'a Buffer) -> Vec<(u16, u16, &'a Cell)> {
186        debug_assert_eq!(
187            (self.width, self.height),
188            (other.width, other.height),
189            "Buffer::diff called on buffers with different dimensions"
190        );
191
192        let len = self.content.len().min(other.content.len());
193        let mut updates: Vec<(u16, u16, &'a Cell)> = vec![];
194        let mut invalidated: usize = 0;
195        let mut to_skip: usize = 0;
196
197        for (i, (current, previous)) in other.content[..len]
198            .iter()
199            .zip(self.content[..len].iter())
200            .enumerate()
201        {
202            if (current != previous || invalidated > 0) && to_skip == 0 {
203                let (x, y) = self.pos_of(i);
204                updates.push((x, y, current));
205            }
206
207            let current_width = render_width(current);
208            let previous_width = render_width(previous);
209            to_skip = current_width.saturating_sub(1);
210            let affected = current_width.max(previous_width);
211            invalidated = affected.max(invalidated).saturating_sub(1);
212        }
213
214        updates
215    }
216}
217
218/// Returns the number of terminal columns a cell occupies.
219///
220/// A `wide` lead cell occupies 2 columns; every other cell (including the
221/// `trail` continuation cell) counts as 1. This mirrors ratatui's skipping of
222/// empty continuation cells, but is driven off our typed flags instead of
223/// `unicode-width`.
224fn render_width(cell: &Cell) -> usize {
225    if cell.is_wide() { 2 } else { 1 }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231    use crate::color::{Color, Style};
232
233    // --- construction ---
234
235    #[test]
236    fn new_has_correct_dimensions() {
237        let b = Buffer::new(80, 25);
238        assert_eq!(b.width(), 80);
239        assert_eq!(b.height(), 25);
240        assert_eq!(b.area_len(), 80 * 25);
241        assert_eq!(b.cells().len(), 80 * 25);
242    }
243
244    #[test]
245    fn new_all_cells_default() {
246        let b = Buffer::new(5, 3);
247        for cell in b.cells() {
248            assert_eq!(*cell, Cell::default());
249        }
250    }
251
252    #[test]
253    fn filled_sets_every_cell() {
254        let s = Style::new(Color::Bios(0xF), Color::Bios(0x1));
255        let seed = Cell::blank(s);
256        let b = Buffer::filled(4, 4, seed.clone());
257        for cell in b.cells() {
258            assert_eq!(*cell, seed);
259        }
260    }
261
262    // --- index_of / pos_of round-trip ---
263
264    #[test]
265    fn index_pos_roundtrip() {
266        let b = Buffer::new(10, 5);
267        for y in 0..5u16 {
268            for x in 0..10u16 {
269                let i = b.index_of(x, y);
270                assert_eq!(b.pos_of(i), (x, y));
271            }
272        }
273    }
274
275    #[test]
276    fn index_of_row_major() {
277        let b = Buffer::new(10, 5);
278        assert_eq!(b.index_of(0, 0), 0);
279        assert_eq!(b.index_of(9, 0), 9);
280        assert_eq!(b.index_of(0, 1), 10);
281        assert_eq!(b.index_of(9, 4), 49);
282    }
283
284    // --- get / get_mut ---
285
286    #[test]
287    fn get_mut_mutates() {
288        let mut b = Buffer::new(5, 5);
289        b.get_mut(2, 3).set_char('X');
290        assert_eq!(b.get(2, 3).symbol(), "X");
291        // neighbouring cells unaffected
292        assert_eq!(b.get(1, 3).symbol(), " ");
293        assert_eq!(b.get(3, 3).symbol(), " ");
294    }
295
296    // --- diff: identical buffers ---
297
298    #[test]
299    fn diff_identical_is_empty() {
300        let a = Buffer::new(5, 3);
301        let b = Buffer::new(5, 3);
302        assert!(a.diff(&b).is_empty());
303    }
304
305    // --- diff: changed cells ---
306
307    #[test]
308    fn diff_returns_changed_cells() {
309        let front = Buffer::new(5, 3);
310        let mut back = Buffer::new(5, 3);
311        // change three scattered cells
312        back.get_mut(0, 0).set_char('A');
313        back.get_mut(3, 1).set_char('B');
314        back.get_mut(4, 2).set_char('C');
315
316        let changes: Vec<(u16, u16)> = front.diff(&back).iter().map(|&(x, y, _)| (x, y)).collect();
317        assert_eq!(changes.len(), 3);
318        assert!(changes.contains(&(0, 0)));
319        assert!(changes.contains(&(3, 1)));
320        assert!(changes.contains(&(4, 2)));
321
322        // verify the cell content points into `back`
323        for &(x, y, cell) in &front.diff(&back) {
324            assert_eq!(*cell, *back.get(x, y));
325        }
326    }
327
328    // --- diff: wide glyph — lead emitted once, trail suppressed ---
329
330    #[test]
331    fn diff_wide_lead_emitted_once_trail_suppressed() {
332        let front = Buffer::new(4, 1);
333        let mut back = Buffer::new(4, 1);
334        // place a double-width glyph at columns 0–1
335        back.get_mut(0, 0).set_str("中", true);
336        back.get_mut(1, 0).set_wide_trail();
337
338        let changes = front.diff(&back);
339        // Only the lead cell at (0, 0) should appear; the trail is suppressed
340        // by `to_skip = 1`.
341        let coords: Vec<(u16, u16)> = changes.iter().map(|&(x, y, _)| (x, y)).collect();
342        assert_eq!(coords, vec![(0, 0)]);
343
344        // The emitted cell is indeed the lead cell.
345        let (_, _, cell) = changes[0];
346        assert!(cell.is_wide());
347        assert_eq!(cell.symbol(), "中");
348    }
349
350    // --- diff: narrow replaces wide — trail repainted via `invalidated` ---
351
352    #[test]
353    fn diff_narrow_replacing_wide_repaints_trail_via_invalidated() {
354        // front has a wide glyph at (0,0)+(1,0)
355        let mut front = Buffer::new(4, 1);
356        front.get_mut(0, 0).set_str("中", true);
357        front.get_mut(1, 0).set_wide_trail();
358
359        // back has a narrow char at (0,0) and the *same* trail as front at (1,0)
360        // so (1,0) is NOT different by equality — only `invalidated` forces it.
361        let mut back = Buffer::new(4, 1);
362        back.get_mut(0, 0).set_char('a');
363        back.get_mut(1, 0).set_wide_trail(); // equal to front[1]
364
365        let changes = front.diff(&back);
366        let coords: Vec<(u16, u16)> = changes.iter().map(|&(x, y, _)| (x, y)).collect();
367        // Both (0,0) and (1,0) must be emitted.
368        assert!(
369            coords.contains(&(0, 0)),
370            "expected (0,0) in changes, got {coords:?}"
371        );
372        assert!(
373            coords.contains(&(1, 0)),
374            "expected (1,0) in changes (via invalidated), got {coords:?}"
375        );
376    }
377
378    // --- reset ---
379
380    #[test]
381    fn reset_clears_all_cells() {
382        let mut b = Buffer::new(3, 3);
383        for y in 0..3u16 {
384            for x in 0..3u16 {
385                b.get_mut(x, y).set_char('X');
386            }
387        }
388        b.reset();
389        for cell in b.cells() {
390            assert_eq!(*cell, Cell::default());
391        }
392    }
393
394    // --- resize ---
395
396    #[test]
397    fn resize_changes_dimensions_and_resets() {
398        let mut b = Buffer::new(5, 5);
399        b.get_mut(0, 0).set_char('Z');
400        b.resize(10, 3);
401        assert_eq!(b.width(), 10);
402        assert_eq!(b.height(), 3);
403        assert_eq!(b.area_len(), 30);
404        assert_eq!(b.cells().len(), 30);
405        // content reset
406        for cell in b.cells() {
407            assert_eq!(*cell, Cell::default());
408        }
409    }
410}