Skip to main content

Crate tenui

Crate tenui 

Source
Expand description

§Tenui

Tenui is a modular, high-performance terminal user interface (TUI) framework for Rust. It unifies the mechanical sympathy and predictable efficiency of immediate-mode rendering with the compositional power of flexbox layout, fine-grained reactivity, and an enterprise widget suite.

§Core Architecture & Feature Layers

Tenui is organized as a layered stack of focused, cohesive crates through progressive disclosure:

┌────────────────────────────────────────────────────────────────────────┐
│  Standard Suite (tenui-std) — Chat, Tables, Code, Diff, Charts, Themes │
├────────────────────────────────────────────────────────────────────────┤
│  Retained Runtime (tenui-runtime) — App Reactor, Focus, Invalidation   │
├────────────────────────────────────────────────────────────────────────┤
│  Layer 2 (tenui-compositor) — Z-Layers, Occlusion Cut, Spatial Nav     │
├────────────────────────────────────────────────────────────────────────┤
│  Layer 1 (tenui-reactive)   — Two-Lane Bus (PAINT vs LAYOUT), Batch    │
├────────────────────────────────────────────────────────────────────────┤
│  Layer 0 (tenui-layout)     — Immediate Flexbox Layout via Taffy       │
├────────────────────────────────────────────────────────────────────────┤
│  Core (tenui-core)          — Cell, Buffer, Diff Coalescer, Terminal   │
└────────────────────────────────────────────────────────────────────────┘

§Progressive Feature Tiers

  • Core (core): The bare-metal foundation. Provides the compact 8-byte Cell data union, double-buffered Buffer, differential SgrCoalescer emission engine, RAII TerminalGuard, and non-blocking terminal I/O drivers.
  • Layer 0 (layer0 / layout): Pure-Rust immediate-mode flexbox layout engine built on Taffy. Allows declarative styling and proportional grid positioning without an asynchronous runtime.
  • Layer 1 (layer1 / reactive): Fine-grained reactive signal graph and the Two-Lane Invalidation Engine. Explicitly distinguishes cosmetic changes (Invalidation::PAINT) from structural changes (Invalidation::LAYOUT), guaranteeing that paint-only updates never trigger layout reflow.
  • Layer 2 (layer2 / compositor): Off-screen spatial layer compositor (LayerCompositor), coordinate cut-finding occlusion culling, WICG spatial navigation, and sub-cell vector graphics (Braille, half-block, and quadrant rasterizers).
  • Kinetics (anim / anim): Closed-form analytical spring dynamics (AnalyticalSpring), sub-cell Unicode 1/8th fractional micro-stepping (MicroStepper), and zero-idle power scheduling (ActiveTicker).
  • Runtime (runtime / runtime): Retained-mode App reactor driving a persistent Taffy tree, focus management, and the two-lane invalidation bus.
  • Standard Library (std / std_widgets): Batteries-included widget suite including ChatThread, VirtualTable, TextInput, TextEditor, CodeView, DiffView, Form, LinePlot, BarChart, TreeView, FilePicker, and ThemePalette.
  • Visual Effects (vfx / vfx): Procedural sub-cell shaders, acrylic blur filters, particle kinematics, and CRT/shimmer/glitch effects.
  • Extensibility (ext / ext): The open CustomWidget trait, Tower-inspired input middleware pipeline, WASM component model contract, and embedded Lua/Rhai scripting bridge.
  • Macros (macros / macros): Compile-time declarative view! macro for structured UI composition.
  • Advanced Systems (advanced): Drag-and-drop docking (dnd), virtual list acceleration (virt), text buffers with branching undo (text), daemon workspace persistence (session), tactile audio cues (sound), and hardware-accelerated GPU terminal rendering (wgpu).
  • Frontier Systems (frontier]): Vectorized SIMD differential scanning (simd), multi-seat CRDT presence (collab), half-block video streaming (media), sub-cell math typesetting (math), hardware/MIDI input bridges (hid), and stream chaos fuzzing (chaos).

§Quickstart: Immediate-Mode “Hello, TUI”

Below is a minimal, fully functional immediate-mode program:

use std::io;
use tenui::{Terminal, Rect, Color, Modifier};

fn main() -> io::Result<()> {
    // Initialize terminal and acquire RAII guard (raw mode + alternate screen)
    let mut term = Terminal::new()?;

    // Render an immediate-mode frame
    term.draw(|canvas| {
        let (w, h) = (canvas.width(), canvas.height());
        canvas.clear(Color::Reset);
        canvas.write_str_clipped(
            2,
            1,
            "Hello from Tenui!",
            Color::Cyan,
            Color::Reset,
        );
    })?;

    Ok(())
}

For automated testing and headless assertion, buffers can be inspected in memory without a TTY:

use tenui::{Buffer, Rect, Color};

let mut buffer = Buffer::new(40, 5);
{
    let mut canvas = buffer.subview_mut(Rect::new(0, 0, 40, 5));
    canvas.write_str_clipped(1, 1, "Headless Test", Color::Green, Color::Reset);
}

assert_eq!(buffer.get(1, 1).unwrap().symbol.as_str(), "H");
assert_eq!(buffer.get(2, 1).unwrap().symbol.as_str(), "e");

§Flagship Example: Streaming Chat Client

For a complete, real-world application showcasing Tenui’s three-zone shell (collapsible sidebar, hybrid conversational transcript, multi-line composer), live SSE token streaming, reasoning blocks, mouse drag-resizing, and theme switching, run:

cargo run --release --example chat

Located at crates/tenui/examples/chat/, it serves as the canonical worked case study for building flagship terminal applications.

§The Prelude

For convenience, common types and traits can be imported via:

use tenui::prelude::*;

Re-exports§

pub use crossterm;
pub use taffy;
pub use tenui_anim as anim;
pub use tenui_chaos as chaos;
pub use tenui_collab as collab;
pub use tenui_compositor as compositor;
pub use tenui_core as core;
pub use tenui_dnd as dnd;
pub use tenui_ext as ext;
pub use tenui_hid as hid;
pub use tenui_layout as layout;
pub use tenui_macros as macros;
pub use tenui_math as math;
pub use tenui_media as media;
pub use tenui_reactive as reactive;
pub use tenui_runtime as runtime;
pub use tenui_session as session;
pub use tenui_simd as simd;
pub use tenui_sound as sound;
pub use tenui_std as std_widgets;
pub use tenui_text as text;
pub use tenui_vfx as vfx;
pub use tenui_virt as virt;
pub use tenui_wgpu as wgpu;

Modules§

prelude
Common imports for rapid application development with Tenui.

Macros§

view
Compile-time declarative UI macro expanding into zero-cost typed builder calls.

Structs§

Announcer
A live-region announcer: the app pushes updates, the bridge drains and speaks them.
Buffer
A 2D grid of terminal cells.
CanvasSubviewMut
An isolated, hardware-clipped subview into a Buffer. Local coordinates are relative to the subview’s top-left bound.
Cell
A single character cell on the terminal grid.
Clipboard
A clipboard combining the system clipboard (OSC 52, write-only) with a local register.
DndManager
Central spatial drag-and-drop event bus mapping OS pointer coordinates and paste payloads to target layout nodes.
DropTargetEntry
Registration descriptor for an active drop target in the spatial layout index.
FrameClock
Precision frame clock applying Exponentially Weighted Moving Average (EWMA) to eliminate instantaneous framerate display jitter.
Modifier
ANSI text modifiers (SGR attributes).
MouseDispatcher
Central spatial mouse event dispatcher with Z-index sorting, modal barriers, :hover / :active state tracking, and click synthesis.
MouseTargetEntry
Registration descriptor for an active mouse interaction target.
NodeId
A unique identifier for a layout node or container in the visual hierarchy.
PathSanitizer
Sanitizes dropped payloads, decoding RFC 8089 file URIs, percent-encoded bytes, and shell-escaped file paths into valid OS PathBuf representations.
Point
A 2D point in terminal cell coordinates.
Rect
A 2D rectangle in terminal cell coordinates.
ScreenReaderBridge
Renders semantic information to a textual form a screen reader (or a test) consumes.
Selection
An anchored selection: anchor is where it started, head is the moving end.
SemanticNode
A node in the semantic accessibility tree.
SemanticTree
A retained accessibility tree.
SgrCoalescer
An ANSI SGR coalescing difference engine.
SgrMouseParser
Parser for ANSI SGR 1006 (\x1b[<B;X;YM / \x1b[<B;X;Ym) mouse escape sequences.
Terminal
The primary Terminal interface managing double buffers, differential rendering, and terminal hardware synchronization.
TerminalGuard
RAII Terminal guard ensuring emergency terminal restoration upon normal exit, POSIX termination signals, or application panic.

Enums§

ClipboardCommand
A clipboard action, decoupled from the key chord that triggered it. Produced by an input layer (e.g. tenui-ext’s ClipboardLayer) and applied to a focused ClipboardTarget via apply_clipboard_command.
Color
Terminal color representations.
DragEvent
Discrete events in the spatial drag-and-drop lifecycle.
MouseButton
Button identifier in the pointer tracking subsystem.
MouseEvent
Unified mouse events dispatched across the spatial hit-test tree.
Politeness
How urgently a live-region update should be announced.
Role
The accessible role of a node (a pragmatic subset of the ARIA roles that map to TUIs).
TextOverflow
Strategies for handling text that exceeds available box, rectangle, or container width.

Traits§

ClipboardTarget
A widget that can participate in clipboard operations. Implemented by the text widgets so one input path (Ctrl+C/X/V, bracketed paste) drives them all.

Functions§

apply_clipboard_command
Applies a ClipboardCommand to a focused target, returning the OSC 52 escape to emit (for Copy/Cut), or None (for Paste/SelectAll).
encode_osc52
Builds the OSC 52 clipboard-set escape for text (\x1b]52;c;<base64>\x07).