Guide API
Skip to main content

tvision_rs/backend/
renderer.rs

1//! `Renderer`, the per-frame draw cycle (documented on the type).
2
3use crate::backend::Backend;
4use crate::screen::Buffer;
5
6/// Owns the back/front buffer pair and a boxed [`Backend`].
7///
8/// Renderer — the per-frame draw cycle.
9///
10/// The `Renderer` owns the back/front `Buffer` pair plus a boxed `Backend`.  Each
11/// frame it:
12/// 1. Resets the back buffer.
13/// 2. Runs the paint closure into the back buffer.
14/// 3. Diffs the back buffer against the front buffer.
15/// 4. Pushes changed cells to the backend.
16/// 5. Sets the cursor and, while it is shown, the caret size.
17/// 6. Flushes.
18/// 7. Swaps back/front so the new frame becomes the reference for the next diff.
19///
20/// This mirrors the role of ratatui's `Terminal::draw` but is simpler: there is
21/// no partial-repaint or damage-tracking — the whole view tree is painted every
22/// frame and the cell diff keeps the terminal I/O bounded.
23///
24/// Constructed with [`Renderer::new`]; the frame cycle is [`Renderer::render`].
25///
26/// # Turbo Vision heritage
27///
28/// Replaces Turbo Vision's incremental, per-view screen writes (each view wrote
29/// its buffer straight through the screen driver) with a double-buffered
30/// whole-tree repaint plus diff. The per-view damage tracking is dropped in favour
31/// of repaint-and-diff (deviation D8).
32pub struct Renderer {
33    backend: Box<dyn Backend>,
34    /// `buffers[0]` and `buffers[1]` alternate roles each frame.
35    buffers: [Buffer; 2],
36    /// Index of the *back* buffer (the one being painted this frame).
37    current: usize,
38    /// Desired hardware cursor position: `Some((x,y))` or `None` (hidden).
39    cursor: Option<(u16, u16)>,
40    /// Desired caret size (see [`Backend::set_caret_size`]), sent while the
41    /// cursor is shown.
42    caret_size: u8,
43}
44
45impl Renderer {
46    /// Create a new `Renderer` backed by `backend`.
47    ///
48    /// Both buffers are initialized to the backend's current size.
49    pub fn new(backend: Box<dyn Backend>) -> Self {
50        let (w, h) = backend.size();
51        Renderer {
52            backend,
53            buffers: [Buffer::new(w, h), Buffer::new(w, h)],
54            current: 0,
55            cursor: None,
56            caret_size: crate::backend::CARET_NORMAL,
57        }
58    }
59
60    /// Run one frame cycle.
61    ///
62    /// 1. Resets the back buffer to blank.
63    /// 2. Calls `paint` with a mutable reference to the back buffer.
64    /// 3. Diffs the back buffer against the front buffer.
65    /// 4. Pushes changed cells to the backend.
66    /// 5. Sets the cursor and, while it is shown, the caret size.
67    /// 6. Flushes.
68    /// 7. Swaps back/front.
69    ///
70    /// The borrow structure: `self.buffers[back]` and `self.buffers[front]` are
71    /// distinct elements (different indices), so Rust's disjoint-field borrow
72    /// lets the compiler see that `diff` borrows `self.buffers[front]` while
73    /// `self.backend` is a separate field. No cloning is needed.
74    pub fn render(&mut self, paint: impl FnOnce(&mut Buffer)) {
75        let back = self.current;
76        let front = 1 - self.current;
77
78        // Reset the back buffer, then paint into it.
79        self.buffers[back].reset();
80        paint(&mut self.buffers[back]);
81
82        // Compute the diff (borrows self.buffers[front] and self.buffers[back]).
83        // We collect into a Vec to end the borrow on self.buffers before calling
84        // self.backend.draw (which also needs &mut self).
85        let diff: Vec<(u16, u16, _)> = self.buffers[front].diff(&self.buffers[back]);
86
87        // Push changes to the backend.
88        self.backend.draw(&diff);
89        self.backend.set_cursor(self.cursor);
90        if self.cursor.is_some() {
91            self.backend.set_caret_size(self.caret_size);
92        }
93        self.backend.flush();
94
95        // Swap: the back buffer is now the reference for the next frame.
96        self.current = front;
97    }
98
99    /// Set the desired cursor position (used by the next [`render`](Self::render) call).
100    pub fn set_cursor(&mut self, pos: Option<(u16, u16)>) {
101        self.cursor = pos;
102    }
103
104    /// Set the desired caret size (used by the next [`render`](Self::render)
105    /// call while the cursor is shown). See [`Backend::set_caret_size`].
106    pub fn set_caret_size(&mut self, size: u8) {
107        self.caret_size = size;
108    }
109
110    /// Borrow the backend.
111    pub fn backend(&self) -> &dyn Backend {
112        &*self.backend
113    }
114
115    /// Borrow the backend mutably (e.g. to call `poll_event`).
116    pub fn backend_mut(&mut self) -> &mut dyn Backend {
117        &mut *self.backend
118    }
119
120    /// Resize both buffers to `width × height`, resetting all content.
121    ///
122    /// Call this when the terminal reports a resize.
123    pub fn resize(&mut self, width: u16, height: u16) {
124        self.buffers[0].resize(width, height);
125        self.buffers[1].resize(width, height);
126    }
127
128    /// Force a full terminal repaint on the next [`render`](Self::render) call.
129    ///
130    /// Clears the front (reference) buffer so the next diff sees every cell as
131    /// changed. Call after [`Backend::resume`] — the terminal's alt-screen is
132    /// blank, so a full repaint is required.
133    pub fn invalidate_all(&mut self) {
134        let front = 1 - self.current;
135        self.buffers[front].reset();
136    }
137}