Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Drawing & backends

A tvision-rs app never writes to the terminal directly. Every view paints into an in-memory grid; once per frame the framework diffs that grid against the previous one and pushes only the changed cells to a pluggable backend. This is the whole-tree-redraw-plus-diff draw model, with no damage-tracking and no per-view "dirty" bookkeeping. A view fills in its cells; the diff keeps terminal I/O bounded.

The cell and the draw buffer

The atom is a Cell: one screen position holding a grapheme cluster (its text), a colour Style, and two flags marking the lead and trailing halves of a double-width glyph. It is the Rust form of magiblot's TScreenCell.

A view does not poke cells one at a time. It fills a DrawBuffer, a single fixed-width row of cells under construction, then blits that row. Writes past the buffer's width are clipped. Text goes in through width-aware primitives, so truncation and double-width handling are shared with the rest of the renderer.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{DrawBuffer, Style};
fn _demo(style: Style) {
let width = 10usize;
// In a view's draw(): build one line, then write it out.
let mut b = DrawBuffer::new(width);
b.move_str(0, "Hello", style);
// ... hand `b` to the framework to blit at row y ...
}
}

In the typed cell model, move_char always writes both char and style; there is no retain-sentinel. To update only the character or only the style, use put_char / put_attribute.

The back buffer and the diff

The full view tree is painted into a Buffer, the screen-sized grid, always rooted at (0, 0). Each frame the renderer keeps two buffers: the back buffer (painted this frame) and the front buffer (last frame, the diff reference). Buffer::diff walks the two grids and returns the cells that changed, handling double-width lead/trail cells. The algorithm is adapted from ratatui without its skip opt-out, since a full repaint leaves nothing to skip.

The Renderer cycle

The Renderer owns the back/front buffer pair and a boxed backend, and runs one frame per call to render:

  1. Reset the back buffer to blank.
  2. Paint the whole view tree into it.
  3. Diff it against the front buffer.
  4. Draw the changed cells to the backend.
  5. Set cursor to the focused position (or hide it).
  6. Flush.
  7. Swap back and front so this frame becomes next frame's reference.

This runs at the end of every event-loop pump.

The Backend trait

The terminal seam is the Backend trait (deviation D11). The app holds a Box<dyn Backend>, so the trait is object-safe and the view tree never carries a backend type parameter. Its surface is small: report size, draw a slice of changed cells, flush, set_cursor, set_caret_size, poll_event, plus clipboard and suspend/resume hooks.

Two implementations ship:

BackendRole
CrosstermBackendProduction. Wraps crossterm; sets up raw mode, the alternate screen, and mouse capture, and restores the terminal on Drop.
HeadlessBackendTests. An in-memory grid that never blocks: poll_event pops a queued event or returns immediately, so tests drive the loop deterministically.

The port's tests are built on the headless backend: a widget is rendered onto it and its grid is compared, via the frozen screen::snapshot format, against a golden string.

Clipping to owner bounds

Every view paints through a DrawCtx, the clipped, themed writer handed down from its parent group. A DrawCtx carries an absolute clip rectangle already intersected with its parent's clip rectangle, and every cell write is discarded if it falls outside that rect. A view can never paint outside the bounds its owner carved out for it, regardless of what coordinates it writes to.

The clip is set up when a group descends into a child's draw:

// src/view/group.rs — Group::draw (simplified)
for child in self.children.iter_mut().filter(|c| c.view.state().state.visible) {
    let bounds = child.view.state().get_bounds();
    // `ctx.sub(bounds)` intersects the parent's clip with the child's bounds
    // and creates a DrawCtx whose origin is at the child's top-left corner.
    let mut sub = ctx.sub(bounds);
    child.view.draw(&mut sub);
}

DrawCtx::sub computes child_clip = parent_clip ∩ child_bounds_absolute. A child that extends beyond its owner's edge (or is partially scrolled off screen) receives a sub with a narrowed clip; it still calls its own draw code unchanged, but the writes that land outside the clip are dropped in the buffer writer.

Because clips are intersected at each level of the tree, a deeply nested view inherits the intersection of all its ancestors' clips. There is no separate getClipRect call before drawing; the DrawCtx already carries the correct clip.

// src/view/context.rs — DrawCtx::sub (verbatim logic)
pub fn sub(&mut self, area_local: Rect) -> DrawCtx<'_> {
    let mut abs = area_local;
    abs.r#move(self.origin.x, self.origin.y);  // child's absolute position
    let mut clip = self.clip;
    clip.intersect(&abs);                        // narrow to owner's clip
    DrawCtx {
        buffer: &mut *self.buffer,
        clip,                                    // already intersected
        origin: self.origin + area_local.a,
        theme: self.theme,
    }
}

This is the getClipRect successor: in C++ a view called getClipRect before writing to avoid painting into occluded regions. In tvision-rs there is nothing to call: the clip comes down with the DrawCtx, and the draw code never needs to query or adjust it. It serves correctness (a view must not paint outside its bounds); minimizing writes is left to the diff.

Sources: DrawCtx::sub and DrawCtx::clip in src/view/context.rs; Group::draw in src/view/group.rs.

Turbo Vision heritage: TView::getClipRect (tview.cpp) returned the intersection of the view's bounds with the visible area; views checked it before writing. In tvision-rs the intersected clip is pre-computed and carried by DrawCtx; views write unconditionally and the clip discards out-of-bounds cells.

Colour depth

Terminals vary in colour capability, so the backend maps each Style's colours down a quantization ladder selected by ColorDepth: TrueColor passes 24-bit RGB through unchanged, Xterm256 quantizes RGB to the nearest palette entry, Ansi16 reduces everything to the 16-colour set, and NoColor drops colour entirely. The ladder itself (RGB → xterm-256 → xterm-16 → BIOS) is pure, I/O-free maths; see the Theme/Role port note for how the typed theme feeds it.