uncurses 0.0.9

A Rust terminal rendering library
Documentation
//! Front → back buffer sync with per-cell equality filtering.
//!
//! Screens write freely into their `front_buf`; `fill_rect` and bulk
//! ops mark whole rows as touched even when the resulting content
//! matches the previous frame. [`Renderer::sync_front`] copies those
//! touched spans into [`Renderer::back_buf`] using
//! [`RenderBuffer::set_cell`], which only flips `back_buf.touched`
//! when the destination cell actually differs. The diff pass then
//! visits only rows that genuinely changed on the wire.
//!
//! Only the cells inside `front_buf.touched(y)` spans are read — no
//! full-buffer scan.

use crate::renderer::Renderer;
use crate::renderer::buffer::RenderBuffer;

use crate::buffer::Surface;

impl Renderer {
    /// Sync a caller-facing buffer into the renderer staging buffer.
    ///
    /// # Parameters
    ///
    /// - `front`: desired cell grid whose touched spans identify writes
    ///   since the last sync.
    ///
    /// # Returns
    ///
    /// `true` when the renderer has real work to render: either the
    /// staging buffer now has touched rows that differ from its previous
    /// contents, the dimensions changed, or a force-clear is pending.
    /// Returns `false` for pure no-op writes.
    ///
    /// # Behavior
    ///
    /// Copies only cells within `front`'s touched spans, skips
    /// continuation cells, steps by wide-cell width, and clears
    /// `front`'s touched flags before returning.
    pub(crate) fn sync_front(&mut self, front: &mut RenderBuffer) -> bool {
        let width = front.width();
        let height = front.height();
        if self.back_buf.width() != width || self.back_buf.height() != height {
            self.back_buf.resize(width, height);
            // Copies below mark real cell changes; geometry changes also
            // reach the frame pipeline when every added cell is blank.
            self.back_buf.clear_touched();
        }

        for y in 0..height {
            let Some(span) = front.touched(y) else {
                continue;
            };
            let mut x = span.first;
            while x <= span.last {
                let pos = (x, y).into();
                let Some(new_cell) = front.cell(pos) else {
                    x += 1;
                    continue;
                };
                // Skip continuation columns. Copying the primary places
                // the continuation on the far side as part of the same
                // write, so the column is already carrying the value this
                // loop would ask for. `Buffer::set` ignores a continuation
                // offered on its own, so passing one on would be a wasted
                // call rather than a wrong one, and stepping over it keeps
                // the walk in step with the widths it advances by.
                if new_cell.is_continuation() {
                    x += 1;
                    continue;
                }
                // `RenderBuffer::set_cell` does a value-equality
                // check before writing, so unchanged cells pay no
                // clone and no touch.
                self.back_buf.set_cell(pos, new_cell);
                // Step over any continuation columns owned by the cell
                // we just wrote so we don't try to re-copy them.
                let step = (new_cell.width() as u16).max(1);
                x = x.saturating_add(step);
            }
        }
        front.clear_touched();

        self.force_clear || self.back_buf.has_changes() || self.size_changed(width, height)
    }

    pub(super) fn size_changed(&self, width: u16, height: u16) -> bool {
        width != self.last_width || height != self.last_height
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cell::Cell;
    use crate::renderer::buffer::RenderBuffer;

    fn cell(c: &str) -> Cell {
        Cell::new(c, 1)
    }

    fn fill_row(buf: &mut RenderBuffer, y: u16, content: &str) {
        for (x, ch) in content.chars().enumerate() {
            buf.set_cell((x as u16, y), &cell(&ch.to_string()));
        }
    }

    #[test]
    fn sync_lazy_resizes_back_buf() {
        let mut r = Renderer::new();
        let mut front = RenderBuffer::new(10, 3);
        r.sync_front(&mut front);
        assert_eq!(r.back_buf.width(), 10);
        assert_eq!(r.back_buf.height(), 3);
    }

    #[test]
    fn sync_clears_front_touched() {
        let mut r = Renderer::new();
        let mut front = RenderBuffer::new(10, 3);
        fill_row(&mut front, 0, "Hello");
        r.sync_front(&mut front);
        assert!(!front.has_changes());
    }

    #[test]
    fn sync_propagates_real_changes_to_back_buf() {
        let mut r = Renderer::new();
        let mut front = RenderBuffer::new(10, 3);
        fill_row(&mut front, 1, "World");
        let need = r.sync_front(&mut front);
        assert!(need);
        assert!(r.back_buf.touched(1).is_some());
        assert!(r.back_buf.touched(0).is_none());
        assert_eq!(r.back_buf.cell((0, 1).into()).unwrap().content(), "W");
    }

    #[test]
    fn sync_skips_touched_rows_with_identical_content() {
        let mut r = Renderer::new();
        let mut front = RenderBuffer::new(10, 3);
        fill_row(&mut front, 0, "Hello");
        fill_row(&mut front, 1, "World");
        // Render the first sync to establish the displayed geometry.
        assert!(r.sync_front(&mut front));
        r.render_back(&mut Vec::new()).unwrap();

        // Second pass: touch every row but write identical content.
        front.touch_all();
        fill_row(&mut front, 0, "Hello");
        fill_row(&mut front, 1, "World");
        let need = r.sync_front(&mut front);
        assert!(!need, "identical content must leave back_buf untouched");
        assert!(!r.back_buf.has_changes());
    }

    #[test]
    fn sync_only_touches_rows_that_actually_changed() {
        let mut r = Renderer::new();
        let mut front = RenderBuffer::new(10, 3);
        fill_row(&mut front, 0, "Hello");
        fill_row(&mut front, 1, "World");
        fill_row(&mut front, 2, "!!!!");
        r.sync_front(&mut front);
        r.back_buf.clear_touched();

        // Touch all rows but only row 1 genuinely changes.
        front.touch_all();
        fill_row(&mut front, 0, "Hello");
        fill_row(&mut front, 1, "Xorld");
        fill_row(&mut front, 2, "!!!!");
        assert!(r.sync_front(&mut front));
        assert!(r.back_buf.touched(0).is_none());
        assert!(r.back_buf.touched(1).is_some());
        assert!(r.back_buf.touched(2).is_none());
    }

    #[test]
    fn sync_only_walks_touched_spans() {
        let mut r = Renderer::new();
        let mut front = RenderBuffer::new(10, 3);
        fill_row(&mut front, 0, "preset");
        fill_row(&mut front, 2, "preset");
        r.sync_front(&mut front);
        r.back_buf.clear_touched();

        // A fresh buffer leaves blank cells untouched. Only its explicit
        // write may replace the content from the previous buffer.
        let mut front = RenderBuffer::new(10, 3);
        front.set_cell((3, 0), &cell("X"));
        r.sync_front(&mut front);
        assert!(r.back_buf.touched(0).is_some());
        assert!(r.back_buf.touched(2).is_none());
        assert_eq!(r.back_buf.cell((3, 0).into()).unwrap().content(), "X");
        assert_eq!(
            r.back_buf.cell((0, 0).into()).unwrap().content(),
            "p",
            "columns outside the touched span must keep their content"
        );
        assert_eq!(
            r.back_buf.cell((0, 2).into()).unwrap().content(),
            "p",
            "row 2 in back_buf must keep its pre-existing content"
        );
    }

    #[test]
    fn sync_reports_force_clear_even_with_no_changes() {
        let mut r = Renderer::new();
        let mut front = RenderBuffer::new(10, 3);
        assert!(r.sync_front(&mut front));
        r.render_back(&mut Vec::new()).unwrap();
        assert!(!r.sync_front(&mut front));

        r.request_clear();
        assert!(r.sync_front(&mut front));
    }

    /// Regression: sync_front used to step by 1 column even on wide
    /// cells, which re-visited the continuation column and overwrote
    /// the wide primary in back_buf with a blank. With the width-
    /// aware step the primary survives and the continuation is
    /// skipped.
    #[test]
    fn sync_advances_by_wide_cell_width_and_skips_continuation() {
        let mut r = Renderer::new();
        let mut front = RenderBuffer::new(10, 1);
        // Wide CJK cell at col 0; col 1 is its continuation.
        let wide = Cell::new("漢", 2);
        front.set_cell((0, 0), &wide);
        front.set_cell((3, 0), &cell("a"));
        r.sync_front(&mut front);

        assert_eq!(r.back_buf.cell((0, 0).into()).unwrap().content(), "漢");
        assert_eq!(r.back_buf.cell((0, 0).into()).unwrap().width(), 2);
        assert!(
            r.back_buf.cell((1, 0).into()).unwrap().is_continuation(),
            "col 1 must remain the wide cell's continuation, not be blanked"
        );
        assert_eq!(r.back_buf.cell((3, 0).into()).unwrap().content(), "a");
    }
}