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

The tvision-rs Developer Guide

tvision-rs is a TUI framework for Rust: a faithful, idiomatic port of magiblot/tvision, the modern C++ version of Borland's Turbo Vision. An app built with this crate looks and behaves like a DOS-era Turbo Vision program, with overlapping windows, a menu bar at the top and a status line at the bottom.

A Turbo Vision veteran recognises the framework, and the code is native Rust without inheritance, raw pointers or a preprocessor. The class hierarchy became a View trait plus composition; TView* pointers became ViewId handles; the cmXxx/sfXxx constant families became namespaced consts and named boolean fields. The event loop, the modal dialogs, the draw model and the widget set behave as in Turbo Vision.

The tv:: house style

By convention the crate is imported under the short alias tv, and the historic T prefix is dropped. TButton is tv::Button, TDialog is tv::Dialog, TProgram is tv::Program. A Turbo Vision class maps to a tv:: type by this rule:

C++ Turbo Visiontvision-rs (Rust)
TButtontv::Button
TWindowtv::Window
TDeskToptv::Desktop
TMenuBartv::MenuBar
TStatusLinetv::StatusLine

How to read these docs

This documentation has two layers served as one site:

  • The Guide (these pages) is the narrative you read to learn. It is organised by task and by concept, carries colored screenshots of running programs, and pulls its code from compiled examples.
  • The API reference is the per-type reference: every struct, trait, and method, generated by rustdoc from the source. When the Guide names a type it links into the API, and the API links back into the Guide. Use the Guide ⇄ API toggle in the top bar to move between them.

A suggested path:

  1. Getting Started: add the crate, build and run your first app.
  2. If you are coming from C++ Turbo Vision, read The Idiomatic Port next: it explains the ideas behind each deviation.
  3. Otherwise jump to Building Apps for task recipes. The data-movement model explains in one place how values travel between dialogs, controls, siblings, and modals. Dip into How It Works when you want to write your own View.

Installation & the tv:: alias

Add the crate

tvision-rs targets a recent stable Rust (the crate uses the 2024 edition, so you need Rust 1.85 or newer). Add it to your Cargo.toml. The house style is to alias the package to tv, so import it under that name with Cargo's package key:

[dependencies]
tv = { package = "tvision-rs", version = "0.18.0" }

To track the development version on main, depend on the git repository instead:

[dependencies]
tv = { package = "tvision-rs", git = "https://github.com/oetiker/tvision-rs" }

Everything is then reachable through the tv:: namespace, which replaces the old T prefix:

#![allow(unused)]
fn main() {
#![allow(unused_imports)]
use tvision_rs as tv;
use tv::{Program, Desktop, MenuBar, StatusLine, CrosstermBackend};
}

The tv alias is a convention; use tvision_rs::… works as well.

Feature flags

FeatureDefaultWhat it does
os-clipboardonNative OS clipboard (via arboard) as the first rung of the clipboard chain

The clipboard is a fall-through chain: native OS clipboard → terminal OSC 52 escape → an internal in-process buffer. Turning os-clipboard off drops the arboard dependency (and its system libraries) but still leaves the OSC 52 and internal rungs, so copy/paste keeps working on capable terminals:

[dependencies]
tv = { package = "tvision-rs", version = "0.18.0", default-features = false }

The git dependency takes the same default-features = false key.

Verify the build

A build confirms that the crate resolves and compiles for your toolchain:

$ cargo build
   Compiling tvision-rs vX.Y.Z
   Compiling my-app v0.1.0 (/home/me/my-app)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 12.34s

vX.Y.Z is the tvision-rs version Cargo resolved; for a git dependency Cargo also prints the repository URL and commit.

Next: your first app.

Your first app

The shortest path to something on screen is the hello example that ships with the crate. It builds the three parts every Turbo Vision program has (a desktop with a patterned background, a menu bar along the top, and a status line along the bottom) and then runs the event loop:

$ cargo run --example hello

The result is a classic Turbo Vision screen. Overlapping demo windows sit on the desktop; F10 enters the menu, Alt-F/Alt-W/Alt-C open the menus by hot-key, and Alt-X quits:

  File  Window  Color                                                           
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░┌──────── Window 1 ──1─────┐░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░│                          │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░│   ┌──────── Window 2 ──2─────┐░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░│   │                          │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░│   │   ╔═[■]════ Window 3 ══3═[↑]═╗░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░│   │   ║                          ║░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░│   │   ║                          ║░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░└───│   ║                          ║░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░│   ║                          ║░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░└───║                          ║░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░║                          ║░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░└─════════════════════════─┘░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F3 Open  F4 New  F10 Menu  Alt-X Exit                                          

The screenshot above is the terminal output, captured from the running program and rendered as colored, selectable HTML. See The screenshot tooling for how it is made.

Building the program

A tvision-rs app is assembled from three factory functions, one each for the desktop, the status line, and the menu bar, passed to Program::new at construction. (They are the successors to C++ TApplication's initDeskTop / initStatusLine / initMenuBar overrides.)

//! `hello` — a minimal Turbo Vision application, written in the shape a
//! magiblot/tvision (C++) veteran will recognise on sight: a desktop with a
//! patterned background and a few windows, a menu bar at the top, and a status
//! line at the bottom, all driven by the real `TProgram::run` event loop.
//!
//! The C++ skeleton this mirrors:
//!
//! ```cpp
//! class HelloApp : public TApplication {
//!     static TDeskTop    *initDeskTop(TRect);
//!     static TStatusLine *initStatusLine(TRect);
//!     static TMenuBar    *initMenuBar(TRect);
//! };
//!
//! int main() {
//!     HelloApp app;
//!     app.run();          // spins the event loop until cmQuit
//! }
//! ```
//!
//! Run it:  `cargo run --example hello`
//!   - `F10` enters the menu bar; arrows + Enter navigate it.
//!   - `Alt-F`/`Alt-W` open the File / Window menus by hot-key.
//!   - `Alt-X` (or File → Exit) quits.
//!   - `F3` or File → Open opens a file in an editor window.
//!   - `F4` or File → New opens an untitled editor window.
//!   - `F2` or File → Save saves the current editor file.
//!   - `F5` zooms the current window, `Alt-F3` closes it, `F6` cycles.
//!   - `Alt-1`..`Alt-9` select a window by number.
//!   - `Color → Color Picker…` opens the truecolor picker.

use std::io;

use tvision_rs::{
    Backend, Color, Command, CrosstermBackend, Desktop, EditWindow, Key, KeyEvent, Menu, MenuBar,
    Program, Rect, StatusDef, StatusLine, SystemClock, Theme, View, Window, alt,
};

const CMD_COLOR_PICKER: Command = Command::custom("hello.color_picker");
const CMD_NEW: Command = Command::custom("hello.new");
const CMD_OPEN: Command = Command::custom("hello.open");

// ---------------------------------------------------------------------------
// HelloApp : public TApplication
// ---------------------------------------------------------------------------

/// The application class. In C++ this would derive `TApplication` and override
/// the three `init*` factories; here it wraps the [`Program`] it builds from
/// them via [`Program::new`] (the port's `TProgInit` factory-mixin seam).
struct HelloApp {
    program: Program,
}

impl HelloApp {
    /// `HelloApp::HelloApp` → `TProgInit(initStatusLine, initMenuBar, initDeskTop)`.
    fn new(backend: Box<dyn Backend>) -> Self {
        let program = Program::new(
            backend,
            Box::new(SystemClock::new()),
            Theme::classic_blue(),
            Self::init_desktop,
            Self::init_status_line,
            Self::init_menu_bar,
        );
        // No enable_command registration is needed for the app-minted commands
        // (CMD_COLOR_PICKER / CMD_NEW / CMD_OPEN): every command is enabled by
        // default (D1 denylist) — only the five window-management commands start
        // disabled, until a window grants them on selection.
        HelloApp { program }
    }

    /// `TApplication::initDeskTop` — `r.a.y++; r.b.y--` to inset the desktop one
    /// row below the menu bar and one row above the status line, the patterned
    /// background (`TDeskTop::initBackground`), then a few demo windows so the
    /// window-management commands (zoom / close / next) have something to act on.
    fn init_desktop(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.a.y += 1; // below the menu bar
        r.b.y -= 1; // above the status line
        let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
        // Insert three staggered demo windows numbered 1..=3 (Alt-1..Alt-3 select
        // them; the desktop's cmNext/cmPrev cycle them).
        for num in 1..=3i16 {
            let x = 4 + (num as i32) * 4;
            let y = 1 + (num as i32) * 2;
            let mut win = Window::new(
                Rect::new(x, y, x + 28, y + 8),
                Some(format!("Window {num}")),
                num,
            );
            // TWindow does NOT set ofTileable; the app opts its windows in so
            // Window → Tile / Cascade lay them out.
            win.state_mut().options.tileable = true;
            desktop.insert_view(Box::new(win));
        }
        Some(Box::new(desktop))
    }

    /// `TApplication::initStatusLine` — `r.a.y = r.b.y - 1` (pin to the bottom
    /// row), then the standard line: labelled `Alt-X Exit` (cmQuit) and
    /// `F10 Menu` (cmMenu), plus hidden hotkey bindings for `Alt-F3` close,
    /// `F5` zoom, `F6` next — the shape `initStatusLine` builds.
    fn init_status_line(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.a.y = r.b.y - 1;
        let defs = StatusDef::list()
            .def_all(|d| {
                d.item("~F3~ Open", KeyEvent::from(Key::F(3)), CMD_OPEN)
                    .item("~F4~ New", KeyEvent::from(Key::F(4)), CMD_NEW)
                    .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                    .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
                    .key_item(alt_f3(), Command::CLOSE)
                    .key_item(KeyEvent::from(Key::F(5)), Command::ZOOM)
                    .key_item(KeyEvent::from(Key::F(6)), Command::NEXT)
            })
            .build();
        Some(Box::new(StatusLine::new(r, defs)))
    }

    /// `TApplication::initMenuBar` — `r.b.y = r.a.y + 1` (pin to the top row),
    /// then a File / Window menu. The Window menu now includes **Tile** and
    /// **Cascade** (cmTile/cmCascade route through `program_handle_event` to
    /// `Desktop::tile`/`cascade`); every item wires a command that routes.
    fn init_menu_bar(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.b.y = r.a.y + 1;
        let menu = Menu::builder()
            .submenu("~F~ile", alt('f'), |m| {
                m.command_key("~O~pen…", CMD_OPEN, KeyEvent::from(Key::F(3)), "F3")
                    .command_key("~N~ew", CMD_NEW, KeyEvent::from(Key::F(4)), "F4")
                    .separator()
                    .command_key("~S~ave", Command::SAVE, KeyEvent::from(Key::F(2)), "F2")
                    .command("Save ~A~s…", Command::SAVE_AS)
                    .separator()
                    .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
            })
            .submenu("~W~indow", alt('w'), |m| {
                m.command_key("~N~ext", Command::NEXT, KeyEvent::from(Key::F(6)), "F6")
                    .command_key("~Z~oom", Command::ZOOM, KeyEvent::from(Key::F(5)), "F5")
                    .command_key("~C~lose", Command::CLOSE, alt_f3(), "Alt-F3")
                    .command("~T~ile", Command::TILE)
                    .command("C~a~scade", Command::CASCADE)
            })
            .submenu("~C~olor", alt('c'), |m| {
                m.command("Color ~P~icker…", CMD_COLOR_PICKER)
            })
            .build();
        Some(Box::new(MenuBar::new(r, menu)))
    }

    /// `TApplication::run` — spin the real event loop until a `cmQuit` ends it.
    /// Handles application-level commands (the `TApplication::handleEvent` slot).
    fn run(&mut self) -> Command {
        let mut next_num: i16 = 4; // demo windows 1-3 are pre-inserted; start at 4
        self.program.run_app(move |prog, cmd| {
            if cmd == CMD_NEW {
                let r = prog.desktop_rect();
                let win = EditWindow::new(r, None, next_num);
                prog.desktop_insert(Box::new(win));
                next_num += 1;
            } else if cmd == CMD_OPEN {
                if let Some(path) = prog.open_file_dialog("Open a File", "*.*") {
                    let r = prog.desktop_rect();
                    let win = EditWindow::new(r, Some(path), next_num);
                    prog.desktop_insert(Box::new(win));
                    next_num += 1;
                }
            } else if cmd == CMD_COLOR_PICKER {
                let initial = Color::Rgb(30, 144, 255);
                if let Some(color) = prog.color_dialog(initial) {
                    eprintln!("Color picker returned: {color:?}");
                }
            }
        })
    }
}

/// `Alt-F3` — the classic "close window" accelerator (`kbAltF3`).
fn alt_f3() -> KeyEvent {
    use tvision_rs::KeyModifiers;
    KeyEvent::new(
        Key::F(3),
        KeyModifiers {
            alt: true,
            ..Default::default()
        },
    )
}

// ---------------------------------------------------------------------------
// int main()
// ---------------------------------------------------------------------------

fn main() -> io::Result<()> {
    // CrosstermBackend::new() owns the whole terminal lifecycle (raw mode,
    // alternate screen, mouse capture; restored on drop / panic / signal) —
    // just like the C++ TApplication constructor chain.
    let mut app = HelloApp::new(Box::new(CrosstermBackend::new()?));
    let _result: Command = app.run();
    Ok(())
}

Every command is enabled by default (the framework starts from a denylist, not an allowlist), so the app-minted commands need no registration. Only the five window-management commands begin disabled, until a window grants them when it is selected.

Entering the event loop

main owns the terminal and runs the loop until a quit command ends it. The CrosstermBackend constructor takes over raw mode, the alternate screen, and mouse capture, and restores all of it on drop, also on a panic or a signal:

//! `hello` — a minimal Turbo Vision application, written in the shape a
//! magiblot/tvision (C++) veteran will recognise on sight: a desktop with a
//! patterned background and a few windows, a menu bar at the top, and a status
//! line at the bottom, all driven by the real `TProgram::run` event loop.
//!
//! The C++ skeleton this mirrors:
//!
//! ```cpp
//! class HelloApp : public TApplication {
//!     static TDeskTop    *initDeskTop(TRect);
//!     static TStatusLine *initStatusLine(TRect);
//!     static TMenuBar    *initMenuBar(TRect);
//! };
//!
//! int main() {
//!     HelloApp app;
//!     app.run();          // spins the event loop until cmQuit
//! }
//! ```
//!
//! Run it:  `cargo run --example hello`
//!   - `F10` enters the menu bar; arrows + Enter navigate it.
//!   - `Alt-F`/`Alt-W` open the File / Window menus by hot-key.
//!   - `Alt-X` (or File → Exit) quits.
//!   - `F3` or File → Open opens a file in an editor window.
//!   - `F4` or File → New opens an untitled editor window.
//!   - `F2` or File → Save saves the current editor file.
//!   - `F5` zooms the current window, `Alt-F3` closes it, `F6` cycles.
//!   - `Alt-1`..`Alt-9` select a window by number.
//!   - `Color → Color Picker…` opens the truecolor picker.

use std::io;

use tvision_rs::{
    Backend, Color, Command, CrosstermBackend, Desktop, EditWindow, Key, KeyEvent, Menu, MenuBar,
    Program, Rect, StatusDef, StatusLine, SystemClock, Theme, View, Window, alt,
};

const CMD_COLOR_PICKER: Command = Command::custom("hello.color_picker");
const CMD_NEW: Command = Command::custom("hello.new");
const CMD_OPEN: Command = Command::custom("hello.open");

// ---------------------------------------------------------------------------
// HelloApp : public TApplication
// ---------------------------------------------------------------------------

/// The application class. In C++ this would derive `TApplication` and override
/// the three `init*` factories; here it wraps the [`Program`] it builds from
/// them via [`Program::new`] (the port's `TProgInit` factory-mixin seam).
struct HelloApp {
    program: Program,
}

impl HelloApp {
    /// `HelloApp::HelloApp` → `TProgInit(initStatusLine, initMenuBar, initDeskTop)`.
    fn new(backend: Box<dyn Backend>) -> Self {
        let program = Program::new(
            backend,
            Box::new(SystemClock::new()),
            Theme::classic_blue(),
            Self::init_desktop,
            Self::init_status_line,
            Self::init_menu_bar,
        );
        // No enable_command registration is needed for the app-minted commands
        // (CMD_COLOR_PICKER / CMD_NEW / CMD_OPEN): every command is enabled by
        // default (D1 denylist) — only the five window-management commands start
        // disabled, until a window grants them on selection.
        HelloApp { program }
    }

    /// `TApplication::initDeskTop` — `r.a.y++; r.b.y--` to inset the desktop one
    /// row below the menu bar and one row above the status line, the patterned
    /// background (`TDeskTop::initBackground`), then a few demo windows so the
    /// window-management commands (zoom / close / next) have something to act on.
    fn init_desktop(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.a.y += 1; // below the menu bar
        r.b.y -= 1; // above the status line
        let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
        // Insert three staggered demo windows numbered 1..=3 (Alt-1..Alt-3 select
        // them; the desktop's cmNext/cmPrev cycle them).
        for num in 1..=3i16 {
            let x = 4 + (num as i32) * 4;
            let y = 1 + (num as i32) * 2;
            let mut win = Window::new(
                Rect::new(x, y, x + 28, y + 8),
                Some(format!("Window {num}")),
                num,
            );
            // TWindow does NOT set ofTileable; the app opts its windows in so
            // Window → Tile / Cascade lay them out.
            win.state_mut().options.tileable = true;
            desktop.insert_view(Box::new(win));
        }
        Some(Box::new(desktop))
    }

    /// `TApplication::initStatusLine` — `r.a.y = r.b.y - 1` (pin to the bottom
    /// row), then the standard line: labelled `Alt-X Exit` (cmQuit) and
    /// `F10 Menu` (cmMenu), plus hidden hotkey bindings for `Alt-F3` close,
    /// `F5` zoom, `F6` next — the shape `initStatusLine` builds.
    fn init_status_line(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.a.y = r.b.y - 1;
        let defs = StatusDef::list()
            .def_all(|d| {
                d.item("~F3~ Open", KeyEvent::from(Key::F(3)), CMD_OPEN)
                    .item("~F4~ New", KeyEvent::from(Key::F(4)), CMD_NEW)
                    .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                    .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
                    .key_item(alt_f3(), Command::CLOSE)
                    .key_item(KeyEvent::from(Key::F(5)), Command::ZOOM)
                    .key_item(KeyEvent::from(Key::F(6)), Command::NEXT)
            })
            .build();
        Some(Box::new(StatusLine::new(r, defs)))
    }

    /// `TApplication::initMenuBar` — `r.b.y = r.a.y + 1` (pin to the top row),
    /// then a File / Window menu. The Window menu now includes **Tile** and
    /// **Cascade** (cmTile/cmCascade route through `program_handle_event` to
    /// `Desktop::tile`/`cascade`); every item wires a command that routes.
    fn init_menu_bar(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.b.y = r.a.y + 1;
        let menu = Menu::builder()
            .submenu("~F~ile", alt('f'), |m| {
                m.command_key("~O~pen…", CMD_OPEN, KeyEvent::from(Key::F(3)), "F3")
                    .command_key("~N~ew", CMD_NEW, KeyEvent::from(Key::F(4)), "F4")
                    .separator()
                    .command_key("~S~ave", Command::SAVE, KeyEvent::from(Key::F(2)), "F2")
                    .command("Save ~A~s…", Command::SAVE_AS)
                    .separator()
                    .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
            })
            .submenu("~W~indow", alt('w'), |m| {
                m.command_key("~N~ext", Command::NEXT, KeyEvent::from(Key::F(6)), "F6")
                    .command_key("~Z~oom", Command::ZOOM, KeyEvent::from(Key::F(5)), "F5")
                    .command_key("~C~lose", Command::CLOSE, alt_f3(), "Alt-F3")
                    .command("~T~ile", Command::TILE)
                    .command("C~a~scade", Command::CASCADE)
            })
            .submenu("~C~olor", alt('c'), |m| {
                m.command("Color ~P~icker…", CMD_COLOR_PICKER)
            })
            .build();
        Some(Box::new(MenuBar::new(r, menu)))
    }

    /// `TApplication::run` — spin the real event loop until a `cmQuit` ends it.
    /// Handles application-level commands (the `TApplication::handleEvent` slot).
    fn run(&mut self) -> Command {
        let mut next_num: i16 = 4; // demo windows 1-3 are pre-inserted; start at 4
        self.program.run_app(move |prog, cmd| {
            if cmd == CMD_NEW {
                let r = prog.desktop_rect();
                let win = EditWindow::new(r, None, next_num);
                prog.desktop_insert(Box::new(win));
                next_num += 1;
            } else if cmd == CMD_OPEN {
                if let Some(path) = prog.open_file_dialog("Open a File", "*.*") {
                    let r = prog.desktop_rect();
                    let win = EditWindow::new(r, Some(path), next_num);
                    prog.desktop_insert(Box::new(win));
                    next_num += 1;
                }
            } else if cmd == CMD_COLOR_PICKER {
                let initial = Color::Rgb(30, 144, 255);
                if let Some(color) = prog.color_dialog(initial) {
                    eprintln!("Color picker returned: {color:?}");
                }
            }
        })
    }
}

/// `Alt-F3` — the classic "close window" accelerator (`kbAltF3`).
fn alt_f3() -> KeyEvent {
    use tvision_rs::KeyModifiers;
    KeyEvent::new(
        Key::F(3),
        KeyModifiers {
            alt: true,
            ..Default::default()
        },
    )
}

// ---------------------------------------------------------------------------
// int main()
// ---------------------------------------------------------------------------

fn main() -> io::Result<()> {
    // CrosstermBackend::new() owns the whole terminal lifecycle (raw mode,
    // alternate screen, mouse capture; restored on drop / panic / signal) —
    // just like the C++ TApplication constructor chain.
    let mut app = HelloApp::new(Box::new(CrosstermBackend::new()?));
    let _result: Command = app.run();
    Ok(())
}

The complete, runnable program, including the desktop/menu/status factories above and the command handler that opens editor windows, is examples/hello.rs.

What's next

The application skeleton

tvision-rs splits the running application into two layers.

Program and Application

Program is the engine. It owns the view tree (the desktop with its windows, the menu bar, the status line), the event loop, the capture stack that drives modal dialogs, and the backend that talks to the terminal (the successor to C++ TProgram). The hello example builds a Program directly and wraps it in its own HelloApp struct.

Application is a thin wrapper over Program. It forwards everything to the embedded Program and adds the application-level commands tile / cascade (desktop window layout) and dosShell (suspend the terminal) (the successor to C++ TApplication). Use Application for those extras, or Program to assemble the engine yourself.

Both are constructed the same way, from a theme and the three factory functions that build the desktop, status line, and menu bar:

// Illustrative sketch — not a standalone program.
let program = Program::new(
    backend,
    clock,
    theme,
    init_desktop,      // FnOnce(Rect) -> Option<Box<dyn View>>
    init_status_line,
    init_menu_bar,
);

Each factory receives the screen rectangle and returns the view to install (insetting itself to the top row, bottom row, or the space between).

Turbo Vision heritage: this factory pattern mirrors the C++ TProgInit(initStatusLine, initMenuBar, initDeskTop) factory-mixin.

The run loop

Calling run spins the event loop until a quit command ends it. For an app that needs to react to its own commands, run_app takes a closure that is called whenever the program handles a command it does not recognise (the successor to overriding C++ TApplication::handleEvent):

//! `hello` — a minimal Turbo Vision application, written in the shape a
//! magiblot/tvision (C++) veteran will recognise on sight: a desktop with a
//! patterned background and a few windows, a menu bar at the top, and a status
//! line at the bottom, all driven by the real `TProgram::run` event loop.
//!
//! The C++ skeleton this mirrors:
//!
//! ```cpp
//! class HelloApp : public TApplication {
//!     static TDeskTop    *initDeskTop(TRect);
//!     static TStatusLine *initStatusLine(TRect);
//!     static TMenuBar    *initMenuBar(TRect);
//! };
//!
//! int main() {
//!     HelloApp app;
//!     app.run();          // spins the event loop until cmQuit
//! }
//! ```
//!
//! Run it:  `cargo run --example hello`
//!   - `F10` enters the menu bar; arrows + Enter navigate it.
//!   - `Alt-F`/`Alt-W` open the File / Window menus by hot-key.
//!   - `Alt-X` (or File → Exit) quits.
//!   - `F3` or File → Open opens a file in an editor window.
//!   - `F4` or File → New opens an untitled editor window.
//!   - `F2` or File → Save saves the current editor file.
//!   - `F5` zooms the current window, `Alt-F3` closes it, `F6` cycles.
//!   - `Alt-1`..`Alt-9` select a window by number.
//!   - `Color → Color Picker…` opens the truecolor picker.

use std::io;

use tvision_rs::{
    Backend, Color, Command, CrosstermBackend, Desktop, EditWindow, Key, KeyEvent, Menu, MenuBar,
    Program, Rect, StatusDef, StatusLine, SystemClock, Theme, View, Window, alt,
};

const CMD_COLOR_PICKER: Command = Command::custom("hello.color_picker");
const CMD_NEW: Command = Command::custom("hello.new");
const CMD_OPEN: Command = Command::custom("hello.open");

// ---------------------------------------------------------------------------
// HelloApp : public TApplication
// ---------------------------------------------------------------------------

/// The application class. In C++ this would derive `TApplication` and override
/// the three `init*` factories; here it wraps the [`Program`] it builds from
/// them via [`Program::new`] (the port's `TProgInit` factory-mixin seam).
struct HelloApp {
    program: Program,
}

impl HelloApp {
    /// `HelloApp::HelloApp` → `TProgInit(initStatusLine, initMenuBar, initDeskTop)`.
    fn new(backend: Box<dyn Backend>) -> Self {
        let program = Program::new(
            backend,
            Box::new(SystemClock::new()),
            Theme::classic_blue(),
            Self::init_desktop,
            Self::init_status_line,
            Self::init_menu_bar,
        );
        // No enable_command registration is needed for the app-minted commands
        // (CMD_COLOR_PICKER / CMD_NEW / CMD_OPEN): every command is enabled by
        // default (D1 denylist) — only the five window-management commands start
        // disabled, until a window grants them on selection.
        HelloApp { program }
    }

    /// `TApplication::initDeskTop` — `r.a.y++; r.b.y--` to inset the desktop one
    /// row below the menu bar and one row above the status line, the patterned
    /// background (`TDeskTop::initBackground`), then a few demo windows so the
    /// window-management commands (zoom / close / next) have something to act on.
    fn init_desktop(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.a.y += 1; // below the menu bar
        r.b.y -= 1; // above the status line
        let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
        // Insert three staggered demo windows numbered 1..=3 (Alt-1..Alt-3 select
        // them; the desktop's cmNext/cmPrev cycle them).
        for num in 1..=3i16 {
            let x = 4 + (num as i32) * 4;
            let y = 1 + (num as i32) * 2;
            let mut win = Window::new(
                Rect::new(x, y, x + 28, y + 8),
                Some(format!("Window {num}")),
                num,
            );
            // TWindow does NOT set ofTileable; the app opts its windows in so
            // Window → Tile / Cascade lay them out.
            win.state_mut().options.tileable = true;
            desktop.insert_view(Box::new(win));
        }
        Some(Box::new(desktop))
    }

    /// `TApplication::initStatusLine` — `r.a.y = r.b.y - 1` (pin to the bottom
    /// row), then the standard line: labelled `Alt-X Exit` (cmQuit) and
    /// `F10 Menu` (cmMenu), plus hidden hotkey bindings for `Alt-F3` close,
    /// `F5` zoom, `F6` next — the shape `initStatusLine` builds.
    fn init_status_line(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.a.y = r.b.y - 1;
        let defs = StatusDef::list()
            .def_all(|d| {
                d.item("~F3~ Open", KeyEvent::from(Key::F(3)), CMD_OPEN)
                    .item("~F4~ New", KeyEvent::from(Key::F(4)), CMD_NEW)
                    .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                    .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
                    .key_item(alt_f3(), Command::CLOSE)
                    .key_item(KeyEvent::from(Key::F(5)), Command::ZOOM)
                    .key_item(KeyEvent::from(Key::F(6)), Command::NEXT)
            })
            .build();
        Some(Box::new(StatusLine::new(r, defs)))
    }

    /// `TApplication::initMenuBar` — `r.b.y = r.a.y + 1` (pin to the top row),
    /// then a File / Window menu. The Window menu now includes **Tile** and
    /// **Cascade** (cmTile/cmCascade route through `program_handle_event` to
    /// `Desktop::tile`/`cascade`); every item wires a command that routes.
    fn init_menu_bar(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.b.y = r.a.y + 1;
        let menu = Menu::builder()
            .submenu("~F~ile", alt('f'), |m| {
                m.command_key("~O~pen…", CMD_OPEN, KeyEvent::from(Key::F(3)), "F3")
                    .command_key("~N~ew", CMD_NEW, KeyEvent::from(Key::F(4)), "F4")
                    .separator()
                    .command_key("~S~ave", Command::SAVE, KeyEvent::from(Key::F(2)), "F2")
                    .command("Save ~A~s…", Command::SAVE_AS)
                    .separator()
                    .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
            })
            .submenu("~W~indow", alt('w'), |m| {
                m.command_key("~N~ext", Command::NEXT, KeyEvent::from(Key::F(6)), "F6")
                    .command_key("~Z~oom", Command::ZOOM, KeyEvent::from(Key::F(5)), "F5")
                    .command_key("~C~lose", Command::CLOSE, alt_f3(), "Alt-F3")
                    .command("~T~ile", Command::TILE)
                    .command("C~a~scade", Command::CASCADE)
            })
            .submenu("~C~olor", alt('c'), |m| {
                m.command("Color ~P~icker…", CMD_COLOR_PICKER)
            })
            .build();
        Some(Box::new(MenuBar::new(r, menu)))
    }

    /// `TApplication::run` — spin the real event loop until a `cmQuit` ends it.
    /// Handles application-level commands (the `TApplication::handleEvent` slot).
    fn run(&mut self) -> Command {
        let mut next_num: i16 = 4; // demo windows 1-3 are pre-inserted; start at 4
        self.program.run_app(move |prog, cmd| {
            if cmd == CMD_NEW {
                let r = prog.desktop_rect();
                let win = EditWindow::new(r, None, next_num);
                prog.desktop_insert(Box::new(win));
                next_num += 1;
            } else if cmd == CMD_OPEN {
                if let Some(path) = prog.open_file_dialog("Open a File", "*.*") {
                    let r = prog.desktop_rect();
                    let win = EditWindow::new(r, Some(path), next_num);
                    prog.desktop_insert(Box::new(win));
                    next_num += 1;
                }
            } else if cmd == CMD_COLOR_PICKER {
                let initial = Color::Rgb(30, 144, 255);
                if let Some(color) = prog.color_dialog(initial) {
                    eprintln!("Color picker returned: {color:?}");
                }
            }
        })
    }
}

/// `Alt-F3` — the classic "close window" accelerator (`kbAltF3`).
fn alt_f3() -> KeyEvent {
    use tvision_rs::KeyModifiers;
    KeyEvent::new(
        Key::F(3),
        KeyModifiers {
            alt: true,
            ..Default::default()
        },
    )
}

// ---------------------------------------------------------------------------
// int main()
// ---------------------------------------------------------------------------

fn main() -> io::Result<()> {
    // CrosstermBackend::new() owns the whole terminal lifecycle (raw mode,
    // alternate screen, mouse capture; restored on drop / panic / signal) —
    // just like the C++ TApplication constructor chain.
    let mut app = HelloApp::new(Box::new(CrosstermBackend::new()?));
    let _result: Command = app.run();
    Ok(())
}

Under the hood, each turn of the loop is one call to pump_once: read the next event, route it through the capture stack and the view tree, apply any deferred effects, then redraw the whole tree and diff it against the back buffer. The event loop in depth chapter walks through what pump_once does and why.

Where to go next

This page covered the factories that build the view tree, the Program/Application layers that own it, and the run loop that drives it. From here:

  • Building Apps: task recipes for windows, dialogs, controls, menus, and more.
  • How It Works: the architecture, ending at writing your own View.

What "faithful" means

Almost everything a C++ Turbo Vision programmer knows still holds in tvision-rs. This part of the guide is written for that reader. It explains the ideas behind the few places where the Rust looks different from the C++, so that each familiar construct can be traced to what it became.

Faithful by default

tvision-rs is a faithful port of magiblot/tvision. Class structure, method names, control flow, algorithms, and observable behaviour are reproduced as-is. The event loop dispatches the same way, modal dialogs nest the same way, the draw model paints the same way, and the widgets behave as Turbo Vision widgets do. handleEvent became handle_event on the View trait, but it is called at the same moments, receives the same events, and is expected to consume them the same way.

The rule the port follows: if a behaviour isn't called out as a deliberate departure, it was translated straight from the C++. The answer to "does it still work like Turbo Vision here?" is yes unless a chapter in this part says otherwise.

Why port faithfully

Turbo Vision's command bus, its modal execView, its desktop/window/dialog layering, and its view-owns-its-children tree were refined over decades and fit together. Re-deriving that design from scratch would gain nothing. Faithfulness also means existing Turbo Vision knowledge, and the magiblot documentation, transfers directly, and the port's behaviour can be checked against the C++ source instead of guessed at.

Where it departs, and why

The places where tvision-rs looks different from the C++ are a small, deliberate set with one root cause. Turbo Vision's T prefixes, bit-packed flag words, raw pointers, and hand-rolled machinery were workarounds for features the language of 1991 lacked and Rust has built in. The approach is the same every time:

Recognize each 1991 workaround, replace it with the language feature, and keep everything around it faithful.

TView becomes the View trait (a namespace C++ approximated with a T prefix). state & sfFocused becomes a boolean field. The TEvent.what union becomes an enum. A raw TView* becomes a ViewId handle. Each time, the Rust construct carries the meaning the workaround approximated, so the surrounding code stays a direct translation.

The chapters that follow

Each of the next chapters covers one of these departures: what the C++ does, what tvision-rs does instead, and how the rest of the faithful port connects to it:

For the mapping in one table see Differences from C++ Turbo Vision. For the one-to-one name lookup, see the symbol map.

Inheritance → trait + composition

C++ Turbo Vision is built on inheritance. TView is the base class; TGroup, TWindow, TButton and every other widget derive from it, override a few virtuals (draw, handleEvent, setState, …), and inherit the rest. Rust has no inheritance, so tvision-rs uses the idiom that replaces it: a trait for behaviour and composition for data.

The View trait + ViewState

The TView class splits into two pieces:

  • View: the trait that carries the virtual methods. draw, handle_event, set_state, calc_bounds and the rest live here. Most have a faithful default body, so a widget overrides only what differs.
  • ViewState: a plain struct holding what were TView's data members: origin, size, cursor, the state/option/grow/drag flag sets, the event mask, the help context, and the view's own id. The flag words become named-boolean structs (State (sf*), Options (of*), GrowMode (gf*), DragMode (dm*)); see Flag words → struct-of-bools.

Every widget embeds a ViewState and exposes it through the trait's two required accessors, state() and state_mut(). Those two, plus draw, which has no sensible base default, are the only methods a widget must write; everything else defaults.

// Illustrative sketch — not a standalone program.
fn state(&self) -> &ViewState { &self.state }
fn state_mut(&mut self) -> &mut ViewState { &mut self.state }

Where C++ writes class TButton : public TView, tvision-rs writes struct Button { state: ViewState, /* … */ } and impl View for Button.

Building on a concrete widget: embed-and-delegate

Subclassing a leaf TView means embedding a ViewState. Turbo Vision code also derives from concrete widgets: an "About" box is class AboutDialog : public TDialog, reusing all of TDialog's behaviour and overriding only draw. Without inheritance, a type cannot extend Dialog; it embeds one:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::Dialog;
#[allow(dead_code)]
struct AboutDialog { dialog: Dialog }
}

Rust then provides none of the inherited methods. To behave like its inner Dialog, the embedder must forward every un-overridden View method to the inner field by hand: more than a dozen one-line forwarders like fn handle_event(&mut self, ev, ctx) { self.dialog.handle_event(ev, ctx) }. That boilerplate is the cost of composition.

#[delegate] removes the boilerplate

The #[delegate] attribute macro (from the tvision-rs-macros crate, re-exported as tv::delegate) generates the forwarders. The impl contains only the methods that differ; the macro injects a forwarder for the rest:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{delegate, Dialog, View, DrawCtx};
#[allow(dead_code)]
struct AboutDialog { dialog: Dialog }
#[delegate(to = dialog)]
impl View for AboutDialog {
    fn draw(&mut self, ctx: &mut DrawCtx) { /* custom paint */ }
    // handle_event, set_state, calc_bounds, … all auto-forward to self.dialog
}
}

It reads the trait name from the impl header, collects the methods written in the impl, looks up the trait's full method set from a hand-maintained table, and emits fn m(args) { self.dialog.m(args) } for each method neither written nor listed in skip(...). A skip(name) leaves that method at the trait's default body instead of forwarding. This is used when forwarding would change behaviour (for example, Window skips calc_bounds so its size floor still applies, instead of deferring to the group's). Skipping a name that isn't a trait method is a hard error, so a typo can't silently turn into a forward. Embedders such as Terminal (#[delegate(to = scroller)]) and Desktop (#[delegate(to = group)]) reuse their inner view this way.

One ViewState. The delegate field owns the view's state, so do not write state/state_mut in a #[delegate] impl. An override that returns a ViewState of the outer type would be a second state that every forwarded method (set_state, change_bounds, calc_bounds, ...) ignores: the focus flag and the geometry would land on the inner view. The macro rejects such an override, and skip(state) / skip(state_mut), with a compile error. It accepts only the plain forwarder self.<field>.state(), which is redundant. Keep the state in the delegate field, or implement View by hand without #[delegate].

When you add a View method, add its forwarder too. The macro keeps a hand-maintained mirror of trait View. A missing required method fails to compile, but a new defaulted one would silently not forward; a behavioural spy test guards every currently known method. The design note docs/design/delegation-macros.md has the full rationale.

For the inverse direction (how a view tree is assembled and walked at runtime) see The view tree.

Pointers & infoPtr → handles

C++ Turbo Vision is held together by raw TView* pointers in every direction: owner points up at the enclosing group, a circular next/prev/last ring threads the siblings, and current/selected cross-link a group to its focused and default child. Capture handlers and message() receivers store bare TView* too. Rust forbids that aliased mutable web. Replacing it with handles is the structural change the rest of the port depends on.

The web splits in two

The handle model cuts the pointer graph along one line: down is ownership, up-and-sideways is identity.

  • Downward is a tree. A Group owns its children as Vec<Box<dyn View>> in Z-order. Recursive dispatch (for c in &mut self.children { … }) walks them without aliasing.
  • Up and sideways are handles. Every link that used to be a TView* pointing up or across (owner, current, selected, a captured view, a broadcast subject) becomes a ViewId: a Copy, lightweight identity that carries no reference into the tree, so it can be stored freely. Identity is ViewId equality.

A ViewId is not an index into an arena. It is a single, process-global, monotonic id, created once when a view is inserted and stored in the view's own ViewState. A view therefore knows its own handle, available through id(), which returns Option<ViewId> (None before the view has been inserted into a group). A stale handle (its view long since removed) resolves to nothing. There is no slot to dangle on, so no generational bookkeeping is needed.

Resolving a handle: the downward Context

A child holds no pointer back at its parent and no &Program. Everything it once reached upward for is handed downward through a borrowed Context: the owner's size, the focused-dispatch phase, the disabled-command set, and the queue for deferred effects. When the framework needs to act on a view it holds only by id (move a window's bounds, flip a state flag, deliver a query), it resolves the id with the find_mut tree-walk: a Group searches its children and recurses, a Group-embedding view delegates inward, a leaf returns None. The same walk powers remove_descendant (self-removal happens in the owner's child vector, since a view cannot remove itself) and focus-by-id.

infoPtr becomes a resolvable subject

Turbo Vision's message(receiver, evBroadcast, cmXxx, infoPtr) round-trips a void* infoPtr, used in practice in three unrelated ways. The dominant one (39 of 42 call sites) is fire-and-forget: the infoPtr carries only which view the message is about. That becomes a posted Event::Broadcast carrying a command and a source: Option<ViewId>, where source is a resolvable handle instead of a pointer. A receiver's C++ test infoPtr == hScrollBar becomes source == self.h_scroll_bar. See Events → enum + match for the broadcast model, and Cross-view brokering & ViewId for how the event loop brokers a read or write between two sibling views that each hold only the other's handle.

// C++:  if (event.message.infoPtr == hScrollBar) …
// Rust: a scrollbar broadcasts about itself; the scroller filters by id.
if source == Some(self.h_scroll_bar) {
    // react to *this* scrollbar's broadcast
}

What did not change

Only two substitutions happen: TView* → ViewId, and "reach upward" → "read from Context." The focus and traversal logic ports verbatim: tab order, the per-group current versus the global focused view, validate-on-focus-leave, and makeFirst raising a window all behave as in Turbo Vision. The downward channels the C++ also had (owner extent, deferred command-enable, deferred capture pushes) remain unchanged, because global identity resolution addresses sideways links, not the parent→program state a child still cannot reach upward.

This pairs with Inheritance → trait + composition: together they replace the TView class hierarchy and its pointer web with a View trait over an owned tree. For the runtime mechanics, see The view tree and The event loop in depth.

Events → enum + match

Turbo Vision packs every event into one TEvent record: a what bitmask that says which kind, plus a union { mouse; keyDown; message; } read according to what. Code decodes an event by masking (if (what & evMouse)) and then reading the matching union arm. The record is compact, but nothing prevents reading the wrong arm, and the void* infoPtr inside the message arm is used in three unrelated ways.

In tvision-rs the record becomes a Rust sum type, Event, which code matches arm-by-arm instead of masking. Each ev* class maps onto one variant, and the variant carries the payload that class uses, so the compiler guarantees that only existing fields are read:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::Event;
#[allow(unused_variables)]
fn _demo(event: Event) {
match event {
    Event::KeyDown(k)         => { /* k.key, k.modifiers */ }
    Event::MouseDown(m)       => { /* m.position, m.buttons */ }
    Event::Command(cmd)       => { /* a command for me */ }
    Event::Broadcast { .. }   => { /* a command for whoever cares */ }
    _ => {}
}
}
}

A handled event is consumed by setting it to Event::Nothing, the clearEvent equivalent, spelled event.clear(). evNothing and a consumed event are the same variant, as in C++.

The split that infoPtr forced

C++ message(receiver, what, command, infoPtr) did two jobs: it delivered a command and returned a result through the event's void* infoPtr. That one pointer field meant three different things across the code base, so it splits into typed mechanisms:

  • Targeted command: Event::Command carries only the Command. The C++ command-target hint on infoPtr is not carried: focused-command routing already delivers the command to the active window, so the hint checked nothing.
  • Broadcast subject: Event::Broadcast { command, source } reinstates the broadcast-subject use of infoPtr as source: Option<ViewId>. It names which view this broadcast is about (for example which scrollbar moved) as a resolvable ViewId handle instead of a raw pointer (see Pointers & infoPtr → handles). A receiver's C++ test infoPtr == hScrollBar becomes source == self.h_scroll_bar. Broadcasts about no particular view pass None.
  • Integer payload: the timer id that C++ passed through infoPtr on a cmTimerExpired broadcast is an integer, not a view, so it gets its own typed variant Event::Timer instead of being forced into source.

The eventMask that survived

TView::eventMask was a bit-word gating which classes a view would receive. Mouse-down/up, key-down, command and broadcast are always delivered, so the only part kept is the opt-in for the expensive classes: continuous mouse-tracking (Event::MouseMove) and auto-repeat (Event::MouseAuto). The bit-word therefore collapses to a two-bool EventMask (a flag-word → struct-of-bools move; see Flag words → struct-of-bools).

The routing is ported faithfully: positional events go to the top-most child under the cursor, focused events through the pre-process / focused / post-process passes. For the mechanics, see The event loop in depth. For the summary see deviation D4.

When no one handles an event

If an event reaches the bottom of the routing chain without any view consuming it, the pump continues to the deferred drain and then redraws. There is no abort, no error handler, and no "event not handled" notification. An unhandled event silently falls out of the dispatch step.

// src/app/program.rs — after dispatch (simplified sketch)
captures.dispatch(&mut ev, &mut ctx);   // capture stack first
if !ev.is_nothing() {
    program_handle_event(group, ..., &mut ev, &mut ctx, ...);
}
// ev may still be Some(something) here — that is fine.
// The pump drains deferred effects and redraws regardless.

The only pump-level filter that drops an event early is the disabled-command gate: if an event is Event::Command(c) and c is in the disabled set, the command is cleared before it reaches any view. All other events, including KeyDown, mouse events, and broadcasts, always enter the routing chain.

While a modal view runs, the chain for keys, commands, pastes and the mouse wheel is the modal view alone. A command it leaves unhandled is cleared there, so it does not reach run_app's command callback after the modal closes. See Modal execView.

This simplifies the C++ TProgram::eventError, which was called when no view consumed an event and could abort the application by default. tvision-rs has no eventError: an unhandled event is a no-op, and the framework keeps running.

Sources: the dispatch step and disabled-command gate in src/app/program.rs.

Turbo Vision heritage: TProgram::eventError (tprogram.cpp) fired on every unconsumed event and terminated the process by default. tvision-rs drops this behaviour: an unhandled event is harmless.

Event masks

By default a view receives every event class that reaches it through routing, except two expensive ones that are off unless the view opts in:

Event classDefaultTo opt in
Event::MouseMovenot deliveredset state.event_mask.mouse_move = true
Event::MouseAutonot deliveredset state.event_mask.mouse_auto = true

All other classes (KeyDown, MouseDown, MouseUp, MouseWheel, Command, Broadcast, Timer) are delivered unconditionally and cannot be masked out.

The gate is applied per child inside the group's delivery step. A child that has not opted into MouseMove never receives it, even if the mouse is moving over it:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::view::{View, ViewState, Context, DrawCtx};
use tv::event::{Event, EventMask};
struct TrackingView { state: ViewState }
impl View for TrackingView {
    fn state(&self) -> &ViewState { &self.state }
    fn state_mut(&mut self) -> &mut ViewState { &mut self.state }
    fn draw(&mut self, _ctx: &mut DrawCtx) {}
}
// Enable mouse-move and mouse-auto tracking for a view.
fn new() -> TrackingView {
    let mut state = ViewState::new(tv::Rect::new(0, 0, 20, 10));
    state.event_mask = EventMask {
        mouse_move: true,
        mouse_auto: true,
    };
    TrackingView { state }
}
}

The disabled-view gate (State::disabled) is separate: a disabled view ignores positional and focused events (mouse clicks, key-down, commands) but still receives broadcasts. This matches C++ behaviour where sfDisabled blocks evMouse | evKeyboard | evCommand but not evBroadcast.

Sources: Group::wants / Group::blocked / Group::deliver in src/view/group.rs; EventMask in src/event/mod.rs.

Turbo Vision heritage: ports TView::eventMask (views.h). The C++ bit-word gating collapses to the two-bool EventMask struct-of-bools because only the two opt-in classes are kept (deviation D5).

Flag words → struct-of-bools

In C++ Turbo Vision, a view's runtime condition is packed into ushort bit words: state holds the sf* flags, options the of* flags, plus growMode (gf*), dragMode (dm*) and eventMask. Code sets a bit with state |= sfFocused and tests one with if (state & sfFocused). This is compact but untyped: the compiler cannot tell that sfFocused belongs to state and not to options.

Memory is no longer that scarce, so tvision-rs turns each flag word into a plain struct of named bool fields. Each bit becomes a field:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::View;
fn _demo(view: &dyn tv::View) {
if view.state().state.focused { /* ... */ }   // was: state & sfFocused
}
}

The four families

Each sf*/of*/gf*/dm* constant maps to one field, and each word maps to one #[derive(Default)] struct. The field's name documents the bit that the old 0x0001-style constant left to a comment:

C++ wordtvision-rs typeExample
stateStatesfFocused → focused
optionsOptionsofSelectable → selectable
growModeGrowModegfGrowAll → grow_all()
dragModeDragModedmLimitLoY → limit_lo_y

A combined constant such as gfGrowAll (four gf* bits OR'd together) becomes a constructor, GrowMode::grow_all(), instead of a single field, since it was never a single bit.

A few flags fell away with their reason for existing: sfExposed and ofBuffered were caches for partial-repaint occlusion, and tvision-rs redraws the whole tree and diffs it (see Drawing & backends), so there is nothing to cache.

Reading vs. flipping

A read is field access on the snapshot returned by state() / options(). Flipping a flag is where Turbo Vision's setState(flag, on) mattered: besides toggling a bit, it fired side effects such as redrawing, broadcasting a focus change, and cascading into children. tvision-rs keeps that verb where the side effects live, as View::set_state over a small StateFlag enum: the named subset of sf* (Active, Selected, Focused, Dragging) that the focus and activation machinery propagates. Flags with no propagation (visibility, cursor shape) are set directly on the struct, never through this hook.

Most application code touches neither directly. It uses the verbs that wrap them: view.show() / view.hide() for visibility, and command enable/disable through the command set (Context::disable_command, which the menus and status line mirror) instead of setting a bit.

Beyond the view: WindowFlags

The wf* decoration word gets the same treatment. A window's WindowFlags carries r#move (can be dragged, wfMove, spelled with a raw identifier because move is a Rust keyword), grow, close and zoom. A default window sets all four, as the C++ ctor does with flags = wfMove | wfGrow | wfClose | wfZoom. Those bools gate behaviour as the bits did: a cmClose acts only when close is set, and dragging is enabled when r#move or grow is.

For the runtime mechanics of how these flags steer dispatch and focus, see The event loop in depth and The view tree.

Constant families → open newtypes

Turbo Vision carried flat families of small integers: cmOK, cmCancel, cmQuit for commands; hcNoContext, hcDragging for help contexts; kbEnter, kbF1 for keys. Each prefix (cm, hc, kb) was hand-rolled namespacing in a language without namespaces, and every value was a number that another library could reuse.

The port keeps the vocabulary and changes the representation. Whether a family becomes an open newtype or a closed enum is decided by one question: can application code legitimately invent a new value?

Commands: an open newtype

Application code defines its own commands all the time, so Command is open: a one-field newtype around a &'static str, with the framework's standard commands exposed as SCREAMING_SNAKE associated constants.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
let _ok     = tv::Command::OK;     // ports cmOK   — value "tv.ok"
let _cancel = tv::Command::CANCEL; // ports cmCancel
let _quit   = tv::Command::QUIT;   // ports cmQuit
}

There is no integer. In C++ those numbers existed only to serialize a view (TStreamable, dropped) and to index a 256-bit TCommandSet. The port needs neither, so a command's value is pure identity: a namespaced string. An application defines its own with Command::custom, using a dotted prefix unique to it:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
const REFRESH: tv::Command = tv::Command::custom("myapp.refresh");
let _ = REFRESH;
}

The dotted prefix is the namespace the cm prefix imitated (tv.* for the framework, myapp.* for the application), so application commands cannot collide with the core's or another extension's. Equality and hashing compare the string contents, so two Commands with the same name are equal wherever the literals live.

Because identity is a string rather than a 0..=255 slot, the old 256-bit TCommandSet becomes a hash-backed CommandSet. Enable/disable, broadcasts and the command bus run on this open command space; see Commands & events.

The framework keeps its shared commands in Command, but view-specific commands live with their view module (the editor's CHAR_LEFT, the file dialog's FILE_OPEN), and external views define theirs the same way. There is no central registry to edit.

Help contexts: the same shape

A context-sensitive help id is equally extensible, so HelpCtx is built like Command: an open newtype around a namespaced string, with HelpCtx::NO_CONTEXT (TV's hcNoContext) as the default and HelpCtx::custom for application ids. See Menus, status line & help.

Keys: a closed enum

The set of physical keys is fixed, and no application invents a new one, so Key is a closed enum (Key::Enter, Key::F(1)). Closed sets become enums so that match is exhaustive; open, app-extensible families become newtypes so the value space stays open. This extensibility test decides every constant family in the port. Keys are covered with the rest of input in Events → enum + match.

Palettes & glyphs → Theme/Role

In C++ Turbo Vision, a view's colors are not stored in one place. Each class exposes a getPalette() that returns a length-prefixed string of byte indices, and getColor(idx) walks the owner chain: a control's palette indexes into its window's palette, which indexes into the application palette, whose final byte is a BIOS attribute (bg << 4 | fg). Drawing glyphs (frame corners, scrollbar arrows, check marks, shadows) are character literals scattered through the widget source. Finding the color of a focused button's shortcut letter means tracing four palette hops by hand.

tvision-rs replaces that machinery with one typed object.

One Theme, two halves

A Theme owns both ends of the old scheme:

  • a flat map from a semantic Role to a Style (a foreground/background Color pair), and
  • a Glyphs holder for every drawing character the framework uses.

A view never walks a palette chain. It asks the theme for the role it wants:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::Role;
fn _demo(ctx: &tv::DrawCtx) {
let _style = ctx.style(Role::FrameActive);
let _corner = ctx.glyphs().frame_tl; // ┌
}
}

Role is the palette index, named

Where the C++ said "the high nibble of cpButton slot 6, two owner hops down", tvision-rs says Role::ButtonDefaultShortcut. Each getColor call site in the original maps to one named Role here, and the state → role decision is made once, in the code that draws the widget, instead of being implicit in a byte string. The enum covers the state matrices the widgets need: active / passive / dragging frames (plus the gray- and cyan-scheme variants), the normal / focused / disabled / pressed quartet, the list-item matrix, the cluster, button, label, input-line, menu and status-line families, and an error / warning / info / success feedback set.

Role is a closed, first-party enum, unlike the open newtype used for Command. The reason is extensibility: a Command crosses the app↔framework boundary and is dispatched by code that never saw it, so it needs open runtime identity. A Role is always resolved at draw time by the code that owns it, so even a custom widget knows its roles at compile time. The closed enum allows a fixed [Style; N] array with a total, panic-free lookup, and the compiler checks exhaustiveness while roles change during the port.

The default theme is the classic blue look

Theme::classic_blue() (also the Default) reproduces the canonical Turbo Vision palette. Every entry is derived from the literal C++ palette chain, and each line in the source carries an inline comment tracing the original hops, for example cpFrame[3] → cpBlueWindow[2] → cpAppColor[9]. The result is stored as one flat Role → Style table. To stay legible on any terminal, the stored colors are pinned to canonical true-color RGB (via Color::bios_rgb) instead of the terminal's own BIOS palette.

Because a theme is data, recoloring the whole app is one call: set_style(role, style) replaces any role's color, and style(role) reads it back. See the Theming & colors recipe for doing this in a running app, and the drawing chapter for how a Style reaches the screen.

Glyphs, not literals

The CP437 box-drawing and marker characters that magiblot's tvtext1.cpp seeds live as named fields on Glyphs: single- and double-line frame pieces (frame_tl, frame_h_d, …), scrollbar arrows and thumb, button-shadow blocks, input-line scroll arrows, and the composite frame-icon strings such as the close box "[~■~]". Defaults match the classic character set; a theme can swap them without touching any widget code.

The draw model → whole-tree redraw + diff

Turbo Vision dates from 1991, when every repainted cell was also a cell written to a slow terminal. The C++ draw model therefore spends a lot of machinery avoiding repaints: per-cell visibility is computed at write time, and drawHide / drawShow / drawUnderView / putInFrontOf plus the buffered group (lock / unlock, ofBuffered) all exist to repaint as little of the screen as possible. This damage tracking is the most intricate part of the original framework.

tvision-rs drops all of it. In-memory work costs next to nothing by 1991 standards, and the one expensive operation left is writing escape sequences to the terminal. Drawing is therefore split into two layers with very different costs.

Two layers

  1. In-memory redraw (cheap). Every update cycle the whole view tree is painted back-to-front into a Buffer, the in-memory screen grid. This touches RAM only and takes microseconds, even for a full screen.
  2. Terminal flush (diff-bounded). The freshly painted buffer is compared against the previous frame with Buffer::diff, which returns only the cells that changed. Only those cells are turned into escape sequences and sent to the terminal.

Because the terminal pays only for cells that changed, a full redraw every frame costs little, and the damage-tracking apparatus is unnecessary.

What this changes for you

  • Occlusion is the painter's algorithm. A higher (later-drawn) view overwrites a lower one. There is no write-time visibility computation: a view paints its content unconditionally, and a covered view is one that a later sibling paints over.
  • Z-order changes and window moves need no extra work. makeFirst / putInFrontOf keep only their reorder role: they shuffle the child order. To bring a window forward, move it, or hide it, mutate the tree and let the next frame redraw and diff. There is nothing to invalidate.
  • No sfExposed, no buffered groups, no draw-under calls. The whole family is gone. When a view's appearance depends on state, change the state; the redraw picks it up.
  • Clip bounds remain, for correctness only. A view must not paint outside its own bounds. Clipping is never used to minimize writes; the diff does that.

How a view paints

Views never touch the Buffer directly. They fill a scratch row, a DrawBuffer (the faithful successor to TDrawBuffer), one display line at a time using Cell values, then blit it into the draw context. Each Cell carries its grapheme and a typed Style (see Palettes & glyphs → Theme/Role) instead of the packed attribute byte of the original.

The redraw step lives in the single event loop: after handling an event, the program sets the cursor and then repaints the whole tree into the buffer in one pass, on every pump cycle, unconditionally. There is no per-view damage rectangle to consult and no redraw-suppression flag; the diff against the previous frame keeps a full repaint cheap.

The runtime mechanics of the buffer pair, the diff, and the Backend trait that emits the escape sequences are covered in Drawing & backends. For the summary see deviation D8.

Draw-on-demand vs whole-tree redraw

In C++ Turbo Vision, TView::drawView checked the sfExposed flag before calling draw. If the view was not exposed (covered by a higher view or scrolled off screen), drawView returned immediately. The framework tracked which views were exposed, maintained per-cell visibility information, and called drawView only for views that contributed visible cells.

tvision-rs has no draw_view. The whole view tree is repainted unconditionally on every pump pass, back-to-front into the in-memory Buffer. The tree walk is cheap (microseconds of RAM writes). The terminal pays only for cells that changed, because Renderer::render diffs the newly painted buffer against the previous frame and emits escape sequences only for the diffed cells:

// src/app/program.rs — end of pump_once (simplified)
renderer.set_cursor(cursor);
renderer.render(|buf| {
    // Paint the ENTIRE tree into buf, unconditionally.
    let bounds = group.state().get_bounds();
    let mut dc = DrawCtx::new(buf, theme, bounds, bounds.a);
    group.draw(&mut dc);
    // Renderer::render then diffs buf against the previous frame
    // and emits only the changed cells.
});

The sfExposed flag, ofBuffered, lock/unlock, drawHide, drawShow, and drawUnderView have no equivalents. There is no notion of "this view needs to be redrawn": everything redraws every time, and the diff handles the rest.

Practical consequences:

  • A view's draw method is called every pump pass, even when nothing visible changed. Keep draw cheap; it runs on the 20 ms frame cadence.
  • There is no invalidate or redraw call to trigger a repaint. Change the state that draw reads and the next frame picks it up.
  • Covered views still have draw called. Later-drawn siblings overwrite their cells before the diff sees them.

Sources: Group::draw (back-to-front tree walk) in src/view/group.rs; Renderer::render (paint → diff → emit) in src/backend/renderer.rs; pump_once (cursor + render step) in src/app/program.rs.

Turbo Vision heritage: C++ TView::drawView short-circuited on !exposed; sfExposed / ofBuffered were maintained by the occlusion tracker. tvision-rs replaces this with whole-tree redraw + buffer diff (deviation D8). The draw method itself is ported faithfully; only the calling convention changes.

Modal execView → one loop

In C++ Turbo Vision, modality is recursion. TGroup::execView spins a nested, blocking getEvent loop inside the already-running one; the outer loop is suspended on the call stack while the inner one runs, and the modal view ends it by calling endModal. The same trick drives dragView and a pressed button's press-and-hold tracking.

Rust does not allow this. A nested loop would have to re-borrow the view tree that the outer loop already holds &mut to; the borrow checker refuses, and there is no &mut self reentrancy to rely on. The nested loops therefore collapse into one non-recursive event loop, and modality becomes a handler on the capture stack instead of a new loop. Event capture is the general mechanism; modality is one use of it.

Modality as a handler

The modal handler is ModalFrame. While it sits on the capture stack, positional (mouse) events are gated by the modal view's bounds: inside, they pass to normal routing; outside, the pump hands them to the modal view alone (in its own coordinates), so views beneath the dialog never see the click. A plain dialog ignores such a click; a history popup closes on it. That gate is what "modal" means here.

Keys, commands, pastes and the mouse wheel pass the frame, but they do not take the root route. The pump hands them to the modal view alone, as C++ TGroup::execute does. The menu bar's hot keys (Alt+F, F3), Alt+1..9 window selection, the Command::QUIT catch, Tile and Cascade, and run_app's command callback do not act while a modal runs. A command the modal does not handle is dropped instead of kept for later (the C++ eventError path). Status-line keys are still converted first, in the pre-route, so Alt+X still posts Command::QUIT, which a dialog ignores, as in C++.

Broadcasts keep the root route and reach the whole tree, including those queued while the modal is open. In C++ a broadcast that a dialog view posts with putEvent reaches only the modal view; tvision-rs queues all broadcasts through one channel and cannot tell them apart, so receivers filter by source. A timer expiry also reaches the whole tree.

exec_view steers the one loop

Program::exec_view is the blocking wrapper that replaces execView. It inserts the view, makes it current, pushes a ModalFrame, then runs the same pump_once loop until the view calls end_modal, setting the end state. Then it pops the frame, removes the view, restores the previous focus and command set, and returns the chosen Command. No new loop is started; exec_view steers the loop that was already running.

See Dialogs & data for the user-facing recipe, Event capture for the mechanism modality shares with drag/resize and press-and-hold, and the event loop in depth for what each pump_once turn does.

Choosing the right launch path

The way to launch a modal depends on what calls it:

CallerLaunch methodResult delivery
A Program / Application methodProgram::exec_view_withreturned by value from the extract closure
A View (inside handle_event)Context::request_exec_viewrecord via View::set_modal_data (not on cancel), then close command via View::set_modal_answer, both to requester; optional then_command re-injected

A view holds only &mut Context, never &mut Program, so it cannot call exec_view_with inline. Calling ctx.request_exec_view(view, requester, then_command) instead queues a Deferred::OpenModal and returns immediately; the pump moves the boxed view into the existing pending_modal slot, runs it via the same single-loop machinery, and on close delivers the result to requester and re-injects then_command. No new loop is spun.

Getting a result back: exec_view_with

C++ execView returns a ushort end command; the caller then reads results out of the still-live dialog with getData before it is destroyed. tvision-rs keeps that shape with Program::exec_view_with: it runs the modal, then, at the pre-drop window while the view is still in the tree, hands the caller's extract closure the modal's &mut dyn View and the end command. Whatever the closure returns is passed back by value:

let chosen: Option<Color> = program.exec_view_with(Box::new(dialog), |modal, cmd| {
    (cmd == Command::OK)
        .then(|| read_the_color_out_of(modal))
        .flatten()
});

The result type R is named by the caller, never by the framework. A single field crosses as a FieldValue via View::value; a richer native value (a Color, a whole Theme) is returned directly from extract; Color/Theme are intentionally not FieldValues.

Launching a modal from a view: Context::request_exec_view

Use request_exec_view when the modal is triggered from inside a handle_event implementation (that is, from any View). The worked example is tcv's Info box: the DirBox list view builds a custom read-only Dialog and launches it when the user presses Enter or double-clicks an entry.

Building the dialog

//! tcv — Tobi's Catalog Vision, a homage re-port of a real 1993 Turbo

//! Pascal / Turbo Vision program (TCV v2.2, a floppy-disk catalog browser by

//! Tobias Oetiker) into idiomatic tvision-rs.

//!

//! The original read a PROGS.TFC text file listing every file on a stack of

//! catalogued floppies; this port embeds a small period-appropriate mock

//! catalog instead. The soul of the program is its search-as-you-type

//! browser (TDirBox): type a word and the list jumps to the next entry whose

//! rendered line contains it (case-insensitive), highlighting the match.

//!

//! Run it: cargo run --example tcv

//! - Up/Down browse the catalog.

//! - Start typing to search; the list jumps to the next matching entry and

//! highlights the matched substring.

//! - In search mode, Up/Down jump to the previous/next match.

//! - Backspace shortens the search; Esc returns to browse mode.

//! - Enter or double-click opens the Info box for the focused entry.

//! - The ~I~nfo / ~A~bout / E~x~it buttons do the obvious things.

//!

//! The C++/Pascal classes this mirrors: TTCV : TApplication, the data window

//! (TDialog), TDirBox : TListBox (the search list), TDiskCol

//! (the catalog collection + DirLine), and TTCVStatLine : TStatusLine (the

//! context-sensitive hint line).

use std::io;

use tvision_rs::widgets::list_viewer;

use tvision_rs::{

Backend, Button, ButtonFlags, Command, Context, CrosstermBackend, Desktop, Dialog, DrawCtx,

Event, GrowMode, HelpCtx, Key, Label, ListViewer, ListViewerState, MessageBoxButtons,

MessageBoxKind, Point, Program, Rect, Role, ScrollBar, StateFlag, StaticText, StatusDef,

StatusLine, SystemClock, Theme, View, ViewId, ViewState, WindowFlags, alt, delegate,

};

// ---------------------------------------------------------------------------

// Commands & help contexts (port of the cm*/hc* constants in TCV.PAS)

// ---------------------------------------------------------------------------

const CMD_INFO: Command = Command::custom("tcv.info");

const CMD_ABOUT: Command = Command::custom("tcv.about");

const HC_BROWSE_MODE: HelpCtx = HelpCtx::custom("tcv.browse_mode");

const HC_SEARCH_MODE: HelpCtx = HelpCtx::custom("tcv.search_mode");

// ---------------------------------------------------------------------------

// Catalog data (replaces reading PROGS.TFC)

// ---------------------------------------------------------------------------

/// One catalogued file, mirroring the six "..."-delimited fields of a

/// PROGS.TFC line (disk, date, file, size, description, scan).

struct Entry {

/// Disk (volume) label.

disk: &'static str,

/// File date (as stamped on the disk).

date: &'static str,

/// File name.

file: &'static str,

/// Size in bytes.

size: u32,

/// Description / comment.

desc: &'static str,

/// Date the disk was scanned into the catalog.

scan: &'static str,

}

/// A charming, period-appropriate early-90s shareware/utility floppy catalog.

static CATALOG: &[Entry] = &[

Entry {

disk: "GAMES01",

date: "10-12-93",

file: "DOOM1_0.ZIP",

size: 2_311_046,

desc: "id Software shareware DOOM v1.0",

scan: "11-03-93",

},

Entry {

disk: "GAMES01",

date: "09-30-93",

file: "WOLF3D.ZIP",

size: 716_800,

desc: "Wolfenstein 3D shareware episode 1",

scan: "11-03-93",

},

Entry {

disk: "GAMES02",

date: "06-15-92",

file: "COMMANDR.ZIP",

size: 458_240,

desc: "Commander Keen 4 shareware",

scan: "11-03-93",

},

Entry {

disk: "GAMES02",

date: "03-21-93",

file: "JAZZJACK.ZIP",

size: 1_204_224,

desc: "Jazz Jackrabbit demo",

scan: "11-03-93",

},

Entry {

disk: "UTILS03",

date: "01-15-93",

file: "PKZIP204.EXE",

size: 199_245,

desc: "PKWARE PKZIP/PKUNZIP v2.04g",

scan: "11-04-93",

},

Entry {

disk: "UTILS03",

date: "08-02-92",

file: "ARJ241.EXE",

size: 121_734,

desc: "ARJ archiver v2.41 by Robert Jung",

scan: "11-04-93",

},

Entry {

disk: "UTILS03",

date: "11-11-91",

file: "LHA213.EXE",

size: 50_018,

desc: "LHA compression utility v2.13",

scan: "11-04-93",

},

Entry {

disk: "UTILS04",

date: "04-04-93",

file: "4DOS502.ZIP",

size: 412_900,

desc: "4DOS command interpreter v5.02",

scan: "11-04-93",

},

Entry {

disk: "UTILS04",

date: "07-19-92",

file: "LIST92.ZIP",

size: 60_416,

desc: "Vernon Buerg's LIST file viewer",

scan: "11-04-93",

},

Entry {

disk: "GRAPHICS",

date: "05-23-93",

file: "FRACTINT.ZIP",

size: 893_120,

desc: "Stone Soup fractal generator v18",

scan: "11-05-93",

},

Entry {

disk: "GRAPHICS",

date: "02-14-93",

file: "VPIC61.ZIP",

size: 147_456,

desc: "VPIC image viewer v6.1",

scan: "11-05-93",

},

Entry {

disk: "GRAPHICS",

date: "12-01-92",

file: "POVRAY10.ZIP",

size: 655_360,

desc: "Persistence of Vision raytracer 1.0",

scan: "11-05-93",

},

Entry {

disk: "SOUND01",

date: "03-30-93",

file: "MODPLAY.ZIP",

size: 73_728,

desc: "ModEdit / MOD music player",

scan: "11-05-93",

},

Entry {

disk: "SOUND01",

date: "06-06-93",

file: "SBOS.ZIP",

size: 98_304,

desc: "Sound Blaster OS drivers",

scan: "11-05-93",

},

Entry {

disk: "COMMS02",

date: "09-09-93",

file: "TELIX321.ZIP",

size: 524_288,

desc: "Telix terminal program v3.21",

scan: "11-06-93",

},

Entry {

disk: "COMMS02",

date: "07-07-92",

file: "QMODEM46.ZIP",

size: 466_944,

desc: "Qmodem modem terminal v4.6",

scan: "11-06-93",

},

Entry {

disk: "PROGRAM",

date: "01-30-93",

file: "TPASCAL7.ZIP",

size: 1_310_720,

desc: "Borland Turbo Pascal 7.0 patches",

scan: "11-06-93",

},

Entry {

disk: "PROGRAM",

date: "10-10-92",

file: "DJGPP.ZIP",

size: 2_097_152,

desc: "DJ Delorie's GCC port for DOS",

scan: "11-06-93",

},

Entry {

disk: "EDITORS",

date: "08-18-93",

file: "QEDIT21.ZIP",

size: 184_320,

desc: "QEdit text editor v2.1",

scan: "11-07-93",

},

Entry {

disk: "EDITORS",

date: "11-25-92",

file: "VDE166.ZIP",

size: 110_592,

desc: "VDE WordStar-style editor v1.66",

scan: "11-07-93",

},

// --- Batch 1: More archivers / compression tools (PKZIP, ARJ, LHA clusters) ---

Entry {

disk: "UTILS03",

date: "02-01-91",

file: "PKZIP110.EXE",

size: 56_312,

desc: "PKWARE PKZIP/PKUNZIP v1.10",

scan: "11-04-93",

},

Entry {

disk: "UTILS03",

date: "10-01-92",

file: "PKZIP193.EXE",

size: 88_455,

desc: "PKWARE PKZIP/PKUNZIP v1.93",

scan: "11-04-93",

},

Entry {

disk: "UTILS05",

date: "11-14-93",

file: "PKLITE15.EXE",

size: 34_276,

desc: "PKLITE executable compressor v1.5",

scan: "11-08-93",

},

Entry {

disk: "UTILS05",

date: "06-30-92",

file: "PKLITE12.EXE",

size: 29_184,

desc: "PKLITE executable compressor v1.2",

scan: "11-08-93",

},

Entry {

disk: "UTILS05",

date: "03-15-91",

file: "ARJ230.EXE",

size: 98_304,

desc: "ARJ archiver v2.30 by Robert Jung",

scan: "11-08-93",

},

Entry {

disk: "UTILS05",

date: "04-22-92",

file: "LHA255.EXE",

size: 52_736,

desc: "LHA compression utility v2.55",

scan: "11-08-93",

},

Entry {

disk: "UTILS06",

date: "09-10-93",

file: "LHA265.EXE",

size: 54_272,

desc: "LHA compression utility v2.65",

scan: "11-08-93",

},

Entry {

disk: "UTILS06",

date: "03-01-93",

file: "ZOO210.EXE",

size: 41_500,

desc: "ZOO archive utility v2.10 by Rahul Dhesi",

scan: "11-08-93",

},

Entry {

disk: "UTILS06",

date: "07-07-93",

file: "STACKER3.ZIP",

size: 812_032,

desc: "Stacker disk compression v3.0 demo",

scan: "11-08-93",

},

Entry {

disk: "UTILS06",

date: "10-18-93",

file: "STACKER4.ZIP",

size: 877_568,

desc: "Stacker disk compression v4.0 demo",

scan: "11-09-93",

},

// --- Batch 2: Games (DOOM/Wolf/Keen/Apogee/Epic cluster) ---

Entry {

disk: "GAMES01",

date: "11-16-93",

file: "DOOM1_2.ZIP",

size: 2_389_114,

desc: "id Software shareware DOOM v1.2",

scan: "11-20-93",

},

Entry {

disk: "GAMES03",

date: "05-05-92",

file: "WOLF3D14.ZIP",

size: 741_376,

desc: "Wolfenstein 3D shareware v1.4 episode 1",

scan: "11-10-93",

},

Entry {

disk: "GAMES03",

date: "12-10-91",

file: "KEEN4E.ZIP",

size: 512_000,

desc: "Commander Keen 4 episode shareware",

scan: "11-10-93",

},

Entry {

disk: "GAMES03",

date: "04-01-93",

file: "DUKE2.ZIP",

size: 684_032,

desc: "Duke Nukem 2 shareware episode 1",

scan: "11-10-93",

},

Entry {

disk: "GAMES04",

date: "07-15-93",

file: "DUKENUKEM.ZIP",

size: 341_248,

desc: "Duke Nukem shareware Apogee v1.0",

scan: "11-10-93",

},

Entry {

disk: "GAMES04",

date: "09-01-93",

file: "RAPTOR.ZIP",

size: 1_024_000,

desc: "Raptor: Call of the Shadows shareware demo",

scan: "11-10-93",

},

Entry {

disk: "GAMES04",

date: "01-18-93",

file: "EPIC_P.ZIP",

size: 786_432,

desc: "Epic Pinball shareware v1.0 demo",

scan: "11-10-93",

},

Entry {

disk: "GAMES04",

date: "11-01-92",

file: "ZONE66.ZIP",

size: 632_320,

desc: "Zone 66 shareware episode demo",

scan: "11-10-93",

},

// --- Batch 3: More games + BBS/comms tools ---

Entry {

disk: "GAMES05",

date: "08-20-93",

file: "HERETIC.ZIP",

size: 2_097_152,

desc: "Heretic shareware episode 1 demo",

scan: "11-21-93",

},

Entry {

disk: "GAMES05",

date: "06-03-93",

file: "BLAKE2.ZIP",

size: 918_528,

desc: "Blake Stone shareware Apogee demo",

scan: "11-11-93",

},

Entry {

disk: "GAMES05",

date: "02-28-93",

file: "COSMO1.ZIP",

size: 449_024,

desc: "Cosmo's Cosmic Adventure episode 1 shareware",

scan: "11-11-93",

},

Entry {

disk: "DEMOS01",

date: "10-15-93",

file: "FUTURE.ZIP",

size: 1_384_448,

desc: "Future Crew Second Reality demo v1.0",

scan: "11-11-93",

},

Entry {

disk: "DEMOS01",

date: "07-22-93",

file: "UNREAL.ZIP",

size: 1_245_184,

desc: "Second Reality Unreal demo fractal engine",

scan: "11-11-93",

},

Entry {

disk: "BBS01",

date: "09-01-93",

file: "RBBS25.ZIP",

size: 512_000,

desc: "RBBS-PC BBS software v25.0",

scan: "11-12-93",

},

Entry {

disk: "BBS01",

date: "08-15-93",

file: "SPITFIRE.ZIP",

size: 368_640,

desc: "Spitfire BBS v3.5 bulletin board system",

scan: "11-12-93",

},

Entry {

disk: "BBS01",

date: "05-10-93",

file: "WILDCAT.ZIP",

size: 614_400,

desc: "Wildcat! BBS v4.01 multi-line bulletin board",

scan: "11-12-93",

},

// --- Batch 4: Modem/comms, viewers, editors ---

Entry {

disk: "MODEM01",

date: "04-19-93",

file: "PROCOMM.ZIP",

size: 438_272,

desc: "ProComm Plus modem terminal demo",

scan: "11-13-93",

},

Entry {

disk: "MODEM01",

date: "11-03-92",

file: "XMODEM.ZIP",

size: 22_528,

desc: "XMODEM/YMODEM/ZMODEM file transfer util",

scan: "11-13-93",

},

Entry {

disk: "MODEM01",

date: "02-20-93",

file: "ZMODEM.ZIP",

size: 31_744,

desc: "ZMODEM fast modem file transfer protocol",

scan: "11-13-93",

},

Entry {

disk: "UTILS07",

date: "06-17-93",

file: "LIST91.ZIP",

size: 59_392,

desc: "Vernon Buerg's LIST file viewer v9.1",

scan: "11-13-93",

},

Entry {

disk: "UTILS07",

date: "10-05-93",

file: "LIST92B.ZIP",

size: 61_440,

desc: "Vernon Buerg's LIST file viewer v9.2b",

scan: "11-13-93",

},

Entry {

disk: "UTILS07",

date: "03-10-93",

file: "AVIEW10.ZIP",

size: 88_064,

desc: "ASCII art viewer v1.0 ANSI/RIP viewer",

scan: "11-13-93",

},

Entry {

disk: "EDITORS",

date: "04-12-92",

file: "QEDIT18.ZIP",

size: 151_552,

desc: "QEdit text editor v1.8 for DOS",

scan: "11-14-93",

},

Entry {

disk: "EDITORS",

date: "09-21-93",

file: "ELVIS2.ZIP",

size: 209_920,

desc: "Elvis vi-clone editor v2.0 for DOS",

scan: "11-14-93",

},

// --- Batch 5: Graphics, sound, screen savers, benchmarks ---

Entry {

disk: "GRAPHICS",

date: "07-30-93",

file: "FRACTINT2.ZIP",

size: 921_600,

desc: "Stone Soup fractal generator v19.2",

scan: "11-14-93",

},

Entry {

disk: "GRAPHICS",

date: "01-08-93",

file: "VPIC52.ZIP",

size: 128_000,

desc: "VPIC image viewer v5.2 GIF/PCX/TIFF",

scan: "11-14-93",

},

Entry {

disk: "GRAPHICS",

date: "11-10-92",

file: "POVRAY20.ZIP",

size: 713_728,

desc: "Persistence of Vision raytracer 2.0",

scan: "11-14-93",

},

Entry {

disk: "SOUND01",

date: "08-01-93",

file: "MPPLAY.ZIP",

size: 56_320,

desc: "MPPlay MOD player for Sound Blaster",

scan: "11-15-93",

},

Entry {

disk: "SOUND02",

date: "10-25-93",

file: "ST3DEMO.ZIP",

size: 1_572_864,

desc: "Scream Tracker 3 MOD player demo",

scan: "11-15-93",

},

Entry {

disk: "SOUND02",

date: "06-11-93",

file: "SBPLAY.ZIP",

size: 44_032,

desc: "Sound Blaster SB player VOC/WAV util",

scan: "11-15-93",

},

Entry {

disk: "UTILS08",

date: "05-15-93",

file: "SCRNSAV3.ZIP",

size: 67_584,

desc: "Screen Saver 3 ANSI blanker with stars",

scan: "11-15-93",

},

Entry {

disk: "UTILS08",

date: "03-28-93",

file: "SCRNSAV2.ZIP",

size: 61_440,

desc: "Screen Saver 2 blank/protect DOS screen",

scan: "11-15-93",

},

Entry {

disk: "UTILS08",

date: "08-30-93",

file: "SPEEDIT.ZIP",

size: 38_912,

desc: "SpeedIT benchmark CPU/disk benchmark",

scan: "11-15-93",

},

Entry {

disk: "UTILS08",

date: "11-01-93",

file: "SYSCHK.ZIP",

size: 47_104,

desc: "SysCheck system benchmark v3.1",

scan: "11-15-93",

},

// --- Batch 6: Programming tools, extra utils ---

Entry {

disk: "PROGRAM01",

date: "06-22-93",

file: "TASM30.ZIP",

size: 524_288,

desc: "Borland Turbo Assembler v3.0 patches",

scan: "11-16-93",

},

Entry {

disk: "PROGRAM01",

date: "03-05-92",

file: "NASM08.ZIP",

size: 118_784,

desc: "NASM x86 assembler v0.8 free",

scan: "11-16-93",

},

Entry {

disk: "PROGRAM01",

date: "09-18-93",

file: "RHIDE.ZIP",

size: 346_112,

desc: "RHIDE IDE for DJGPP GCC port DOS editor",

scan: "11-16-93",

},

Entry {

disk: "PROGRAM02",

date: "01-12-94",

file: "DJGPP2.ZIP",

size: 2_228_224,

desc: "DJ Delorie's GCC port for DOS v2.0",

scan: "01-20-94",

},

Entry {

disk: "UTILS09",

date: "10-01-93",

file: "4DOS55.ZIP",

size: 421_888,

desc: "4DOS command interpreter v5.5",

scan: "11-16-93",

},

Entry {

disk: "UTILS09",

date: "07-04-93",

file: "NORTON7.ZIP",

size: 892_928,

desc: "Norton Utilities v7.0 demo disk toolkit",

scan: "11-17-93",

},

Entry {

disk: "UTILS09",

date: "04-20-93",

file: "PCSHELL.ZIP",

size: 789_504,

desc: "PC Shell file manager v6.0 viewer",

scan: "11-17-93",

},

Entry {

disk: "UTILS10",

date: "12-20-93",

file: "PKZIP204C.EXE",

size: 201_843,

desc: "PKWARE PKZIP/PKUNZIP v2.04c beta",

scan: "01-05-94",

},

];

/// Format a catalog entry as one browser line — TDiskCol.DirLine: a leading

/// space, the disk label padded to 14, the file name padded to 15, then the

/// description.

fn dir_line(e: &Entry) -> String {

format!(" {:<14}{:<15}{}", e.disk, e.file, e.desc)

}

/// The Info box body for entry e — the six labelled fields the original

/// InfoBox showed as static text lines (TDirBox.HandleEvent.InfoBox).

fn info_text(e: &Entry) -> String {

format!(

"Disk Label: {}\nFile Name: {}\nFile Date: {}\n\

Space Used: {} Bytes\nDescription: {}\nScan Date: {}",

e.disk, e.file, e.date, e.size, e.desc, e.scan

)

}

/// The cmAbout MessageBox body — the author's address homage, plus a re-port

/// note. \x03 centers a line (the C++ #3 center marker).

const ABOUT_TEXT: &str = "\x03CREATED in Nov '93 BY\n\n\

\x03Tobias Oetiker\n\

\x03Gallusstrasse 25\n\

\x03CH-4600 Olten\n\

\x03Switzerland\n\n\

\x03eMail oetiker@stud.ee.ethz.ch\n\n\

\x03USING Turbo Pascal 7.0 and Turbo Vision\n\n\

\x03Re-ported to Rust with tvision-rs, 2026.";

/// Case-insensitive substring search — NoCasePos. Returns the byte position

/// (1-based, like Pascal's Pos) of needle in haystack, or 0 if absent. We

/// work in chars for the highlight math; here char index + 1.

fn no_case_pos(needle: &str, haystack: &str) -> usize {

if needle.is_empty() {

return 0;

}

let h: Vec = haystack.chars().map(|c| c.to_ascii_uppercase()).collect();

let n: Vec = needle.chars().map(|c| c.to_ascii_uppercase()).collect();

if n.len() > h.len() {

return 0;

}

for start in 0..=(h.len() - n.len()) {

if h[start..start + n.len()] == n[..] {

return start + 1;

}

}

0

}

/// Build the Info dialog for entry e — the original TDirBox.HandleEvent /// InfoBox, now a real custom Dialog launched via request_exec_view /// (consumer-API gap #2 closed). /// /// The dialog is titled "Information", sized 62 × 10, and shows the entry's /// six fields as static text rows (one StaticText spanning all six lines). /// An OK Button whose command is Command::CANCEL closes the modal /// (read-only-info convention: cmCancel means "dismiss", nothing is read back). /// /// Width is chosen so the longest description in the catalog /// ("Description: Cosmo's Cosmic Adventure episode 1 shareware", 57 chars) /// fits on one row without wrapping: content width = w - 4 = 58 >= 57. fn build_info_dialog(e: &Entry) -> Dialog { // Inner content width: 62 - 2 (frame) - 2 (margin each side) = 58 chars. // Inner content height: 10 - 2 (top/bottom frame) = 8 usable rows. // Layout: rows 1-6 = static text, row 7 = spacer, row 8-9 = button (h=2). let w: i32 = 62; let h: i32 = 10; let mut dialog = Dialog::new(Rect::new(0, 0, w, h), Some("Information".to_string()));

// Six-line static text block: all six labelled fields from `info_text`.
dialog.insert_child(Box::new(StaticText::new(
    Rect::new(2, 1, w - 2, 7),
    info_text(e),
)));

// OK button centered in the bottom row (row 8, height 2).
let btn_w: i32 = 8;
let btn_x = (w - btn_w) / 2;
dialog.insert_child(Box::new(Button::new(
    Rect::new(btn_x, 7, btn_x + btn_w, 9),
    "~O~K",
    Command::CANCEL, // read-only-info convention: OK = cmCancel (just dismiss)
    ButtonFlags::new(),
)));

dialog

}

// ---------------------------------------------------------------------------

// DirBox — port of TDirBox : TListBox, the search-as-you-type catalog list.

//

// A TListViewer subtype (here implemented over ListViewerState + the

// list_viewer free functions, the trait realisation of the C++ abstract

// base). It overrides draw (to highlight the search match) and handle_event

// (the incremental substring search), keeping the base list nav for browse

// mode.

// ---------------------------------------------------------------------------

struct DirBox {

lv: ListViewerState,

/// The accumulated search string (TDirBox.Search). Empty = browse mode.

search: String,

/// One-shot guard for the post-insert scrollbar wiring (see ensure_inited).

inited: bool,

}

impl DirBox {

fn new(bounds: Rect, h: Option, v: Option) -> Self {

let mut lv = ListViewerState::new(bounds, 1, h, v);

lv.range = CATALOG.len() as i32;

lv.state.help_ctx = HC_BROWSE_MODE;

DirBox {

lv,

search: String::new(),

inited: false,

}

}

/// Publish the vertical scrollbar's range + page/arrow steps.

///

/// ListViewerState::new cannot reach the sibling scrollbar (no Context),

/// so it leaves the bar at its default max = 0 — a zero-range bar whose

/// thumb is pinned and never moves. The scrollbar must be told the list

/// length (set_range → bar max = range - 1) and its page/arrow steps

/// (update_steps) after insertion, with a Context. ListBox does this

/// via its new_list consumer; DirBox populates from a static CATALOG

/// in the constructor, so it runs the same publish lazily on the first

/// handle_event (the earliest point a Context and a resolvable bar id

/// are both available). Idempotent via self.inited.

fn ensure_inited(&mut self, ctx: &mut Context) {

if self.inited {

return;

}

self.inited = true;

let range = self.lv.range;

list_viewer::set_range(self, range, ctx);

list_viewer::update_steps(self, ctx);

}

/// TDiskCol.FindNext — first index >= start whose line contains key

/// (case-insensitive), or start if none.

fn find_next(&self, start: i32, key: &str) -> i32 {

let range = self.lv.range;

if start >= 0 && start < range && !key.is_empty() {

let mut i = start;

while i < range {

if no_case_pos(key, &self.get_text(i)) != 0 {

return i;

}

i += 1;

}

start

} else {

0

}

}

/// TDiskCol.FindPrev — last index < start whose line contains key

/// (case-insensitive), walking downwards; start if none / no key.

fn find_prev(&self, start: i32, key: &str) -> i32 {

if start >= 1 && !key.is_empty() {

let mut i = start;

while i >= 1 {

i -= 1;

if no_case_pos(key, &self.get_text(i)) != 0 {

return i;

}

}

i

} else {

start

}

}

/// Switch help context to match the current mode and refresh the status line

/// (the window forwards our context via get_help_ctx).

fn sync_mode(&mut self) {

self.lv.state.help_ctx = if self.search.is_empty() {

HC_BROWSE_MODE

} else {

HC_SEARCH_MODE

};

}

/// Whether this view is the active/focused leaf (so search keys apply) —

/// the port of the original's Owner^.Phase = phFocused guard.

fn is_focused(&self) -> bool {

self.lv.state.state.selected && self.lv.state.state.active

}

/// Open the Info dialog for the focused entry (the original InfoBox),

/// built via build_info_dialog and launched as a real custom Dialog

/// through request_exec_view (consumer-API gap #2 closed).

fn open_info(&mut self, ctx: &mut Context) {

if let Some(e) = CATALOG.get(self.lv.focused as usize) {

let dialog = build_info_dialog(e);

if let Some(id) = self.state().id() {

ctx.request_exec_view(Box::new(dialog), id, None);

}

}

}

}

impl ListViewer for DirBox {

fn lv(&self) -> &ListViewerState {

&self.lv

}

fn lv_mut(&mut self) -> &mut ListViewerState {

&mut self.lv

}

fn get_text(&self, item: i32) -> String {

CATALOG.get(item as usize).map(dir_line).unwrap_or_default()

}

}

impl View for DirBox {

fn state(&self) -> &ViewState {

&self.lv.state

}

fn state_mut(&mut self) -> &mut ViewState {

&mut self.lv.state

}

fn draw(&mut self, ctx: &mut DrawCtx) {

// Without an active search this is just the base list draw.

if self.search.is_empty() {

list_viewer::draw(self, ctx);

return;

}

// Search mode: base draw first (colors every row + the focused cell),

// then overlay the matched substring of the focused row in a contrasting

// style — the C++ TDirBox.Draw mark color (GetColor(5) == ListSelected).

list_viewer::draw(self, ctx);

let focused = self.lv.focused;

let top = self.lv.top_item;

let size = self.lv.state.size;

let row = focused - top;

if row < 0 || row >= size.y {

return;

}

let line = self.get_text(focused);

let pos = no_case_pos(&self.search, &line); // 1-based char index

if pos == 0 {

return;

}

let match_len = self.search.chars().count();

let start = pos - 1;

let active = self.is_focused();

let base = ctx.style(if active {

Role::ListFocused

} else {

Role::ListInactive

});

let mark = ctx.style(Role::ListSelected);

// The list draw renders text starting one column in (col 0 is the

// cell's left pad); re-render the focused row in three styled spans so

// the matched chars stand out.

let pre: String = line.chars().take(start).collect();

let hit: String = line.chars().skip(start).take(match_len).collect();

let rest: String = line.chars().skip(start + match_len).collect();

// put_str returns the width it drew (columns advanced), not the next

// absolute column — so accumulate onto x to keep the three spans

// contiguous (the base list draw starts text at column 1).

let mut x = 1;

x += ctx.put_str(x, row, &pre, base);

x += ctx.put_str(x, row, &hit, mark);

ctx.put_str(x, row, &rest, base);

// The cursor lands just past the matched text via cursor_request.

}

fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {

// Publish the scrollbar range/steps on the first event we see (the

// earliest point we hold a Context and the sibling bar id resolves).

self.ensure_inited(ctx);

// Info / About commands (from the buttons, broadcast) — open the

// matching modal. The list is the natural handler for Info because it

// owns the focused entry. (TDirBox.HandleEvent did the same via the

// ofPostProcess command path.)

if let Event::Broadcast { command, .. } = *ev {

if command == CMD_INFO {

self.open_info(ctx);

ev.clear();

return;

} else if command == CMD_ABOUT {

ctx.request_message_box(

ABOUT_TEXT.to_string(),

MessageBoxKind::Information,

MessageBoxButtons::ok(),

None,

None,

);

ev.clear();

return;

}

}

// Mouse: a double-click opens the Info box for the clicked entry.

if let Event::MouseDown(me) = *ev

&& me.flags.double_click

{

let item = me.position.y + self.lv.top_item;

if item >= 0 && item < self.lv.range {

if item != self.lv.focused {

self.search.clear();

list_viewer::focus_item(self, item, ctx);

}

self.open_info(ctx);

ev.clear();

self.sync_mode();

return;

}

}

// Only run the search state machine when we are the focused leaf.

if self.is_focused()

&& let Event::KeyDown(ke) = *ev

{

match ke.key {

// Printable character: extend the search and jump to the next match.

Key::Char(c) if !ke.modifiers.ctrl && !ke.modifiers.alt => {

let from = if self.search.is_empty() {

0

} else {

self.lv.focused

};

let mut probe = self.search.clone();

probe.push(c);

let found = self.find_next(from, &probe);

if no_case_pos(&probe, &self.get_text(found)) != 0 {

self.search = probe;

if found != self.lv.focused {

list_viewer::focus_item(self, found, ctx);

}

}

// No match: keep the old search and stay put (a gentle no-op,

// tidier than the original's error message box per keystroke).

ev.clear();

self.sync_mode();

return;

}

// Backspace: shorten the search, re-find from the top.

Key::Backspace => {

if !self.search.is_empty() {

self.search.pop();

if !self.search.is_empty() {

let found = self.find_next(0, &self.search);

if found != self.lv.focused {

list_viewer::focus_item(self, found, ctx);

}

}

}

ev.clear();

self.sync_mode();

return;

}

// Enter: open the Info box for the focused entry.

Key::Enter => {

self.open_info(ctx);

ev.clear();

return;

}

// Up/Down while searching: jump to the previous/next match.

Key::Up if !self.search.is_empty() && self.lv.focused > 0 => {

let found = self.find_prev(self.lv.focused, &self.search.clone());

list_viewer::focus_item(self, found, ctx);

ev.clear();

self.sync_mode();

return;

}

Key::Down if !self.search.is_empty() && self.lv.focused < self.lv.range - 1 => {

let found = self.find_next(self.lv.focused + 1, &self.search.clone());

list_viewer::focus_item(self, found, ctx);

ev.clear();

self.sync_mode();

return;

}

// Esc, or any other navigation: leave search / browse mode.

_ => {

if !self.search.is_empty() {

self.search.clear();

self.sync_mode();

if matches!(ke.key, Key::Esc) {

ev.clear();

return;

}

}

}

}

}

// Browse mode (or unconsumed keys): the base list nav + scrollbar sync.

list_viewer::handle_event(self, ev, ctx);

}

fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {

list_viewer::set_state(self, flag, enable, ctx);

}

fn cursor_request(&self) -> Option {

let base = list_viewer::focused_cursor(self)?;

if self.search.is_empty() {

return Some(base);

}

// In search mode, place the cursor just past the matched substring.

let line = self.get_text(self.lv.focused);

let pos = no_case_pos(&self.search, &line);

if pos == 0 {

return Some(base);

}

let end = (pos - 1) + self.search.chars().count();

Some(Point::new(base.x - 1 + end as i32, base.y))

}

fn apply_scroll_sync(&mut self, h: Option, v: Option, ctx: &mut Context) {

list_viewer::apply_scroll(self, h, v, ctx);

}

fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {

Some(self)

}

}

// ---------------------------------------------------------------------------

// DataWindow — port of TDataWin : TDialog, the full-desktop catalog window.

//

// Holds the header label, the search list, its scrollbar, and the three

// buttons. It forwards the list's help context (browse/search) up to the status

// line via get_help_ctx, and turns a CMD_INFO broadcast into an Info box.

//

// The original TCV.PAS set Window^.Flags := $00; GrowMode := $00 to make

// this a fixed, icon-less panel (no close/zoom icons, not movable). This is

// now faithful via with_flags(WindowFlags::default()) for the flags.

//

// DEVIATION: The original GrowMode := $00 was faithful to DOS's fixed 80×25

// screen where resizing was impossible. We deliberately deviate here by

// assigning grow-modes so the catalog and all its children follow modern

// terminal resizes: the window tracks both hi edges, children scale their

// respective edges to fill the new geometry.

// ---------------------------------------------------------------------------

struct DataWindow {

dialog: Dialog,

}

impl DataWindow {

fn new(bounds: Rect) -> Self {

let mut dialog = Dialog::new(bounds, Some("Tobis Catalog Vision Version 2.2".to_string()))

.with_flags(WindowFlags::default()) // TCV: Flags := $00 (fixed, no icons)

// DEVIATION from TCV.PAS GrowMode := $00: track both hi edges so

// the window stretches to fill the terminal on resize.

.with_grow_mode(GrowMode {

hi_x: true,

hi_y: true,

..Default::default()

});

let inner = bounds; // dialog-local coords start at (0,0)

let w = inner.b.x - inner.a.x;

let h = inner.b.y - inner.a.y;

// Buttons along the bottom row, mirroring the original layout.

let btn_y = h - 3;

let mut btn_info = Button::new(

Rect::new(w - 45, btn_y, w - 33, btn_y + 2),

"~I~nfo",

CMD_INFO,

ButtonFlags {

broadcast: true,

..ButtonFlags::new()

},

);

btn_info.state_mut().grow_mode = GrowMode::grow_all();

dialog.insert_child(Box::new(btn_info));

let mut btn_about = Button::new(

Rect::new(w - 30, btn_y, w - 18, btn_y + 2),

"~A~bout",

CMD_ABOUT,

ButtonFlags {

broadcast: true,

..ButtonFlags::new()

},

);

btn_about.state_mut().grow_mode = GrowMode::grow_all();

dialog.insert_child(Box::new(btn_about));

let mut btn_exit = Button::new(

Rect::new(w - 15, btn_y, w - 3, btn_y + 2),

"E~x~it",

Command::QUIT,

ButtonFlags::new(),

);

btn_exit.state_mut().grow_mode = GrowMode::grow_all();

dialog.insert_child(Box::new(btn_exit));

// The scrollbar lives on the right edge of the list area.

let list_rect = Rect::new(2, 2, w - 2, h - 4);

let mut sb = ScrollBar::new(Rect::new(w - 2, 2, w - 1, h - 4));

sb.state_mut().grow_mode = GrowMode {

lo_x: true,

hi_x: true,

hi_y: true,

..Default::default()

};

let sb_id = dialog.insert_child(Box::new(sb));

let mut list = DirBox::new(list_rect, None, Some(sb_id));

list.state_mut().grow_mode = GrowMode {

hi_x: true,

hi_y: true,

..Default::default()

};

let list_id = dialog.insert_child(Box::new(list));

// Header label, linked to the list (Alt-D focuses it).

let mut label = Label::new(

Rect::new(3, 1, w - 2, 2),

"~D~isk File Name Comment",

Some(list_id),

);

label.state_mut().grow_mode = GrowMode {

hi_x: true,

..Default::default()

};

dialog.insert_child(Box::new(label));

DataWindow

}

}

#[delegate(to = dialog)]

impl View for DataWindow {

fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {

Some(self)

}

// handle_event is forwarded by #[delegate(to = dialog)].

// Axis C.1 (Group::get_help_ctx bubble + program idle-path) means the

// focused DirBox's help_ctx now reaches the status line automatically —

// no manual cache into the dialog's state is needed.

}

// ---------------------------------------------------------------------------

// TcvApp — port of TTCV : TApplication.

// ---------------------------------------------------------------------------

struct TcvApp {

program: Program,

}

impl TcvApp {

fn new(backend: Box) -> Self {

let mut program = Program::new(

backend,

Box::new(SystemClock::new()),

Theme::classic_blue(),

Self::init_desktop,

Self::init_status_line,

|r| {

// No menu bar (the original's InitMenuBar is empty); pin a

// zero-height bar so the desktop fills from the top.

let mut r = r;

r.b.y = r.a.y;

let _ = r;

None

},

);

let r = program.desktop_rect();

program.desktop_insert(Box::new(DataWindow::new(r)));

TcvApp

}

fn init_desktop(r: Rect) -> Option<Box> {

let mut r = r;

r.b.y -= 1; // above the status line

Some(Box::new(Desktop::new(r, |br| {

Some(Desktop::init_background(br))

})))

}

/// TTCVStatLine — context-sensitive hints keyed on the browse/search mode.

fn init_status_line(r: Rect) -> Option<Box> {

let mut r = r;

r.a.y = r.b.y - 1;

let defs = StatusDef::list()

.def_all(|d| d.item("Alt-X Exit", alt('x'), Command::QUIT))

.build();

let line = StatusLine::new(r, defs).with_hint(|ctx| {

if ctx == HC_SEARCH_MODE {

Some(

"SEARCH MODE: [UP],[DOWN] for Next Match; Continue typing; [ESC] to Browse Mode"

.to_string(),

)

} else {

Some(

"BROWSE MODE: Use [UP],[DOWN] to Browse or Enter a Word you are looking for."

.to_string(),

)

}

});

Some(Box::new(line))

}

fn run(&mut self) {

// The Info / About modals and Exit are all handled within the view tree

// (the buttons broadcast their commands; the list opens the boxes via

// the async-modal-from-a-view seam, and Exit is the standard cmQuit), so

// the application-level command hook is empty.

self.program.run_app(|_prog, _cmd| {});

}

}

fn main() -> io::Result<()> {

let mut app = TcvApp::new(Box::new(CrosstermBackend::new()?));

app.run();

Ok(())

}

#[cfg(test)]

mod tests {

use super::*;

use tvision_rs::HeadlessBackend;

use tvision_rs::KeyModifiers;

/// Smoke test: the whole app constructs on a headless backend, renders a

/// frame, accepts a search keystroke, and pumps several frames without

/// panicking. Also checks the dir-line / search helpers directly.

#[test]

fn constructs_and_renders_without_panic() {

let (backend, screen) = HeadlessBackend::new(80, 25);

let mut app = TcvApp::new(Box::new(backend));

// One frame: the catalog window draws.

app.program.pump_once();

let frame = screen.snapshot();

assert!(

frame.contains("Tobis Catalog Vision"),

"title should render; got:\n{frame}"

);

// Type a search and pump it through — must not panic and should jump to

// a matching entry.

for c in "doom".chars() {

screen.push_key(Key::Char(c), KeyModifiers::default());

app.program.pump_once();

}

let frame = screen.snapshot();

assert!(

frame.to_lowercase().contains("doom"),

"search should surface the DOOM entry; got:\n{frame}"

);

// Backspace + Esc must also pump cleanly.

screen.push_key(Key::Backspace, KeyModifiers::default());

app.program.pump_once();

screen.push_key(Key::Esc, KeyModifiers::default());

app.program.pump_once();

}

/// Regression guard for the dead scrollbar: ListViewerState::new leaves the

/// sibling vertical bar at its default max = 0, so without the post-insert

/// set_range + update_steps publish (DirBox::ensure_inited) the bar is a

/// zero-range column (all ▓, the sb_page_no_range glyph) whose thumb never

/// moves. After the fix the bar shows a ■ thumb that walks down the column as

/// the focus moves. We focus the list, page down, and assert the thumb glyph

/// appears and is not pinned at the top arrow row.

#[test]

fn scrollbar_thumb_moves_with_focus() {

use tvision_rs::{MouseButtons, MouseEvent};

let (backend, screen) = HeadlessBackend::new(80, 25);

let mut app = TcvApp::new(Box::new(backend));

app.program.pump_once();

// Glyphs: thumb '■' (U+25A0), no-range fill '▓' (U+2593).

let thumb = '\u{25A0}';

let no_range = '\u{2593}';

// Focus the list (and run its lazy scrollbar init) by clicking a row,

// releasing the mouse-track capture so subsequent keys reach the DirBox.

screen.push_event(Event::MouseDown(MouseEvent {

position: Point::new(10, 5),

buttons: MouseButtons {

left: true,

..Default::default()

},

..Default::default()

}));

app.program.pump_once();

screen.push_event(Event::MouseUp(MouseEvent {

position: Point::new(10, 5),

buttons: MouseButtons::default(),

..Default::default()

}));

app.program.pump_once();

// The bar must not be a dead no-range column: a real thumb glyph exists.

let before = screen.snapshot();

assert!(

before.contains(thumb),

"scrollbar should show a movable thumb (■), not a dead no-range bar; got:\n{before}"

);

assert!(

!before.lines().any(|l| l.matches(no_range).count() > 1),

"scrollbar must not render as an all-▓ no-range column; got:\n{before}"

);

// Find the thumb's row in the rightmost-ish columns before scrolling.

let row_of_thumb =

|frame: &str| -> Option { frame.lines().position(|l| l.contains(thumb)) };

let top_row = row_of_thumb(&before);

// Drive the focus to the end of the catalog; the thumb must

// travel downward.

for _ in 0..CATALOG.len() {

screen.push_key(Key::Down, KeyModifiers::default());

app.program.pump_once();

}

let after = screen.snapshot();

let bottom_row = row_of_thumb(&after);

assert!(

after.contains(thumb),

"thumb should still render after scrolling to the end; got:\n{after}"

);

assert!(

bottom_row > top_row,

"scrollbar thumb should move DOWN as focus moves to the catalog end \

(top_row={top_row:?}, bottom_row={bottom_row:?});\nbefore:\n{before}\nafter:\n{after}"

);

}

/// Regression guard for the search-overlay column bug: put_str returns the

/// width it drew (not the next absolute column), so the highlight overlay

/// must accumulate x (x += put_str(...)). When it used x = put_str(...)

/// the focused row was mangled (the rest span landed ~14 columns left). We

/// focus the list, type a search, and assert the matched row still renders

/// its full, contiguous text.

#[test]

fn search_does_not_corrupt_focused_row() {

use tvision_rs::{MouseButtons, MouseEvent};

let (backend, screen) = HeadlessBackend::new(80, 25);

let mut app = TcvApp::new(Box::new(backend));

app.program.pump_once();

// The WOLF3D row, rendered verbatim (file padded to 15, then the comment).

let intact = "WOLF3D.ZIP Wolfenstein 3D shareware episode 1";

assert!(

screen.snapshot().contains(intact),

"row should render intact in browse mode"

);

// Click a list row to focus the list. Send MouseDown + MouseUp to

// release the mouse-track capture before typing; while the capture is

// live (between Down and Up) keyboard events are swallowed by the

// hold handler.

screen.push_event(Event::MouseDown(MouseEvent {

position: Point::new(10, 5),

buttons: MouseButtons {

left: true,

..Default::default()

},

..Default::default()

}));

app.program.pump_once();

screen.push_event(Event::MouseUp(MouseEvent {

position: Point::new(10, 5),

buttons: MouseButtons::default(),

..Default::default()

}));

app.program.pump_once();

// After focusing the list the DirBox is in browse mode; the bubble

// (DirBox.help_ctx → Group::get_help_ctx → status-line idle path)

// must surface "BROWSE MODE" on the status line.

{

let frame = screen.snapshot();

assert!(

frame.contains("BROWSE MODE"),

"status line should show BROWSE MODE after focusing the list; got:\n{frame}"

);

}

// Type a search for "wolf" — now that the hold is released, keys reach

// the DirBox and activate search mode.

for c in "wolf".chars() {

screen.push_key(Key::Char(c), KeyModifiers::default());

app.program.pump_once();

}

// Drain deferred broadcasts (RECEIVED_FOCUS etc.) then get one true

// idle pump: the status-line idle arm reads group.get_help_ctx() only

// when out_events is empty. Each key pump may leave 1-2 broadcasts;

// 8 extra pumps is conservative.

for _ in 0..8 {

app.program.pump_once();

}

// Search is active: status line must now show SEARCH MODE.

{

let frame = screen.snapshot();

assert!(

frame.contains("SEARCH MODE"),

"status line should show SEARCH MODE while searching; got:\n{frame}"

);

}

// The focused row's text is still contiguous — not shifted/duplicated.

assert!(

screen.snapshot().contains(intact),

"search overlay must not corrupt the focused row; got:\n{}",

screen.snapshot()

);

}

#[test]

fn dir_line_and_search_helpers() {

let e = &CATALOG[0];

let line = dir_line(e);

assert!(line.starts_with(' '));

assert!(line.contains(e.disk) && line.contains(e.file) && line.contains(e.desc));

// Case-insensitive substring search (NoCasePos), 1-based.

assert_eq!(no_case_pos("doom", " DOOM1_0.ZIP"), 3);

assert_eq!(no_case_pos("zzz", "abc"), 0);

assert_eq!(no_case_pos("", "abc"), 0);

}

/// Builder test (content): build_info_dialog produces a dialog that renders

/// the entry's six fields and an OK button. Rendered standalone via

/// Renderer on a HeadlessBackend — no app pump needed.

#[test]

fn build_info_dialog_renders_entry_fields_and_ok_button() {

use tvision_rs::{Buffer, DrawCtx, Renderer};

let entry = &CATALOG[0]; // DOOM1_0.ZIP on GAMES01

let mut dialog = build_info_dialog(entry);

let (backend, screen) = HeadlessBackend::new(52, 10);

let mut r = Renderer::new(Box::new(backend));

let theme = Theme::classic_blue();

r.render(|buf: &mut Buffer| {

let bounds = dialog.state().get_bounds();

let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);

dialog.draw(&mut dc);

});

let frame = screen.snapshot();

assert!(

frame.contains(entry.disk),

"frame should contain disk label '{}'; got:\n{frame}",

entry.disk

);

assert!(

frame.contains(entry.file),

"frame should contain file name '{}'; got:\n{frame}",

entry.file

);

assert!(

frame.contains(entry.desc),

"frame should contain description '{}'; got:\n{frame}",

entry.desc

);

assert!(

frame.contains("OK"),

"frame should contain 'OK' button; got:\n{frame}"

);

assert!(

frame.contains("Information"),

"frame should contain the dialog title 'Information'; got:\n{frame}"

);

}

/// Extended builder test: build_info_dialog for the entry with the LONGEST

/// description renders all six labelled fields (disk, file, date, size,

/// description, scan date) without clipping. This is the regression guard

/// for Fix 1 — the dialog must be wide enough that the "Description:" line

/// does NOT wrap and push "Scan Date" off the bottom of the text box.

///

/// Entry used: COSMO1.ZIP on GAMES05 — "Cosmo's Cosmic Adventure episode 1

/// shareware" (57-char "Description: ..." line, the longest in the catalog).

///

/// The test intentionally renders standalone on a [HeadlessBackend] sized

/// to the dialog's own dimensions (no app pump needed), exactly like the

/// existing build_info_dialog_renders_entry_fields_and_ok_button test.

#[test]

fn build_info_dialog_long_desc_renders_all_six_fields() {

use tvision_rs::{Buffer, DrawCtx, Renderer};

// CATALOG[40] = COSMO1.ZIP — the longest "Description: ..." line (57 chars).

let entry = &CATALOG[40];

assert_eq!(

entry.file, "COSMO1.ZIP",

"index 40 must be the COSMO1 entry"

);

let mut dialog = build_info_dialog(entry);

let bounds = dialog.state().get_bounds();

let w = bounds.b.x as u16;

let h = bounds.b.y as u16;

let (backend, screen) = HeadlessBackend::new(w, h);

let mut r = Renderer::new(Box::new(backend));

let theme = Theme::classic_blue();

r.render(|buf: &mut Buffer| {

let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);

dialog.draw(&mut dc);

});

let frame = screen.snapshot();

// All six labelled fields must appear in the rendered frame.

assert!(

frame.contains(entry.disk),

"frame should contain disk label '{}'; got:\n{frame}",

entry.disk

);

assert!(

frame.contains(entry.file),

"frame should contain file name '{}'; got:\n{frame}",

entry.file

);

assert!(

frame.contains(entry.date),

"frame should contain file date '{}'; got:\n{frame}",

entry.date

);

assert!(

frame.contains("449024"),

"frame should contain size '449024'; got:\n{frame}"

);

assert!(

frame.contains(entry.desc),

"frame should contain description '{}'; got:\n{frame}",

entry.desc

);

// Scan date is the sixth field — this assertion fails if the description

// wraps and pushes scan date off the bottom of the text box.

assert!(

frame.contains(entry.scan),

"frame should contain scan date '{}' (Fix 1 guard: clipped if dialog too narrow); got:\n{frame}",

entry.scan

);

assert!(

frame.contains("OK"),

"frame should contain 'OK' button; got:\n{frame}"

);

assert!(

frame.contains("Information"),

"frame should contain the dialog title 'Information'; got:\n{frame}"

);

}

/// Integration test (wiring): pressing Enter on a focused entry triggers

/// CMD_INFO → open_info → request_exec_view. We pre-queue the event

/// sequence so TcvApp::run() drives the full pump-and-drive loop without

/// hanging:

/// 1. Enter → DirBox queues Deferred::OpenModal (the Info dialog).

/// 2. Command::CANCEL → the modal's inner loop picks it up and closes

/// the Info dialog (the OK button emits Command::CANCEL).

/// 3. Command::QUIT → the outer app loop exits.

/// The headless backend's poll_event queue is shared with the modal's

/// inner loop, so the pre-queued events are consumed in the right order.

#[test]

fn enter_on_focused_entry_opens_and_closes_info_dialog_modal() {

use tvision_rs::{MouseButtons, MouseEvent};

let (backend, screen) = HeadlessBackend::new(80, 25);

let mut app = TcvApp::new(Box::new(backend));

// Initial render so the view tree is built.

app.program.pump_once();

// Click the list to focus the DirBox (so keyboard events reach it).

// MouseDown + MouseUp to release capture before typing.

screen.push_event(Event::MouseDown(MouseEvent {

position: Point::new(10, 5),

buttons: MouseButtons {

left: true,

..Default::default()

},

..Default::default()

}));

app.program.pump_once();

screen.push_event(Event::MouseUp(MouseEvent {

position: Point::new(10, 5),

buttons: MouseButtons::default(),

..Default::default()

}));

app.program.pump_once();

// Pre-queue the full sequence for TcvApp::run():

// Enter — DirBox.handle_event calls open_info → request_exec_view

// → queues Deferred::OpenModal.

// CANCEL — the Info dialog's modal loop picks this up; the OK

// button emits Command::CANCEL, so any Command::CANCEL

// closes the modal (it is the end-modal command).

// QUIT — terminates the outer run_app loop so the test returns.

screen.push_key(Key::Enter, KeyModifiers::default());

screen.push_event(Event::Command(Command::CANCEL));

screen.push_event(Event::Command(Command::QUIT));

// Run the full app loop. The pre-queued events drive it to completion

// without blocking (headless backend never blocks on poll_event).

app.run();

// After run() returns the catalog window should still be renderable

// (the desktop is intact after the modal closed cleanly).

let frame = screen.snapshot();

assert!(

frame.contains("Tobis Catalog Vision"),

"catalog window should still be visible after modal closes; got:\n{frame}"

);

}

/// End-to-end resize test: after HeadlessHandle::resize + pump_once the

/// catalog window and all its children grow to fill the new terminal size.

///

/// Verifies:

/// - Before resize: right frame border (║) at column 79 (last column of

/// 80-wide terminal), NOT at column 99.

/// - After resize to 100×30: right frame border at column 99, and the old

/// right-border column (79) is no longer ║ (it is interior content now).

#[test]

fn window_grows_on_terminal_resize() {

let (backend, screen) = HeadlessBackend::new(80, 25);

let mut app = TcvApp::new(Box::new(backend));

// Initial layout pass.

app.program.pump_once();

// Box-drawing right-border glyph used by the Dialog/Window frame.

let right_border = "\u{2551}"; // ║

// At 80 wide: the dialog fills the desktop (0..80). The right edge of

// the frame is at column 79 (0-indexed). Row 5 is well within the

// interior rows so should be the ║ side border.

let before_frame = screen.snapshot();

{

let buf = screen.buffer();

let cell_at_79 = buf.get(79, 5).symbol();

assert_eq!(

cell_at_79, right_border,

"before resize: expected '║' at col 79, row 5; got {:?}\nframe:\n{before_frame}",

cell_at_79

);

// Column 99 doesn't exist on the 80-wide screen — we just verify

// the right border is at 79, not wider.

}

// Simulate a terminal resize to 100×30.

screen.resize(100, 30);

app.program.pump_once();

// After resize: the dialog should have grown to fill 100 columns ×

// 29 desktop rows (status line still takes 1 row). Right border moves

// to column 99, and column 79 is now interior (not ║).

let after_frame = screen.snapshot();

{

let buf = screen.buffer();

let cell_at_99 = buf.get(99, 5).symbol();

assert_eq!(

cell_at_99, right_border,

"after resize: expected '║' at col 99, row 5; got {:?}\nframe:\n{after_frame}",

cell_at_99

);

let cell_at_79 = buf.get(79, 5).symbol();

assert_ne!(

cell_at_79, right_border,

"after resize: col 79 should be interior (not '║'); got {:?}\nframe:\n{after_frame}",

cell_at_79

);

}

}

}

Launching it

Inside DirBox::handle_event (which receives &mut Context, not &mut Program):

// Illustrative sketch — the real code lives in examples/tcv.rs (DirBox::open_info).
fn open_info(&mut self, ctx: &mut Context) {
    if let Some(e) = CATALOG.get(self.lv.focused as usize) {
        let dialog = build_info_dialog(e);
        if let Some(id) = self.state().id() {
            ctx.request_exec_view(Box::new(dialog), id, None);
        }
    }
}

request_exec_view queues Deferred::OpenModal. The pump picks it up at the bottom of the same turn, stashes the boxed Dialog into pending_modal with a RouteModalAnswer { answer_to: id, then_command: None, deliver_data: true } completion, and runs it via the existing single-loop machinery. When the user presses OK (which posts Command::CANCEL, following the read-only-info convention dismiss = cmCancel) the pump delivers that command to DirBox via set_modal_answer. The base default for set_modal_answer silently discards the command, which is correct here: the Info box is read-only and then_command is None, so no follow-up action is needed.

Getting the data back

C++ reads an input dialog's record after the modal returns: if (deskTop->execView(d) != cmCancel) d->getData(&rec);. request_exec_view does the same split across two hooks on the requester. When the modal closes with command c, the pump, while the modal is still in the tree:

  1. if c != Command::CANCEL and the modal's View::value() is Some(record), calls requester.set_modal_data(record). A Dialog (and any type that delegates value to one) returns its gather_list(): the ordered FieldValue::List of its data-bearing controls, the typed image of getData;
  2. calls requester.set_modal_answer(c);
  3. re-posts then_command.

The hooks carry no Context, so the requester caches what it receives and acts when then_command arrives in its handle_event. A requester that was removed while the modal ran receives nothing.

fn set_modal_data(&mut self, data: FieldValue) {
    if let FieldValue::List(fields) = data
        && let Some(FieldValue::Text(name)) = fields.into_iter().next()
    {
        self.pending_name = Some(name); // used on the then_command
    }
}

Ending a modal (execView)

The full lifecycle of exec_view maps each C++ step to a tvision-rs equivalent:

C++ execView steptvision-rs
Save and clear command setSave disabled_commands; the modal starts with its own restrictions
saveOwner; insert into desktopRoot-insert into the program's group (not the desktop); own the view
setState(sfModal, True)state.state.modal = true (direct field write)
setCurrent(p, enterSelect)group.set_current(id, SelectMode::Enter, &mut ctx)
Push capture (none in C++)Push a ModalFrame onto the capture stack
p->execute(), a nested loopSteer the same pump loop; no new loop
p->handleEvent on every event; eventError drops the restKeys, commands, pastes and the wheel go to the modal view alone; an unhandled command is dropped; outside-bounds mouse events go to the modal view
Pop capture (none in C++)Pop the ModalFrame
remove(p); restore focusgroup.remove(id, &mut ctx); restore previous current
Restore command setRestore disabled_commands
Return endStateReturn the Command that was passed to end_modal

The capture-stack push and pop are the main addition over the C++ design: they replace the nested loop's ability to intercept all events while the dialog runs. Because the push is immediate (not deferred, since exec_view holds &mut self directly), the ModalFrame is live from the first pump pass inside the modal.

Sources: exec_view_with_completion in src/app/program.rs; ModalFrame in src/app/program.rs; CaptureStack in src/capture.rs.

Turbo Vision heritage: ports TGroup::execView (tgroup.cpp). The C++ version spun a nested getEvent loop; in tvision-rs the nested loop is replaced by ModalFrame on the capture stack plus the shared pump_once loop (deviation D9).

The modal loop (Execute)

tvision-rs has one event loop. The Program::run skeleton is:

// src/app/program.rs — Program::run (simplified)
loop {
    self.end_state = None;
    while self.end_state.is_none() {
        self.pump_and_drive();    // one pump pass: event → dispatch → redraw
    }
    let es = self.end_state.unwrap();
    if self.valid_end(es) {
        return es;
    }
}

exec_view runs the same pump_and_drive loop in a fresh while block with its own end_state:

// src/app/program.rs — exec_view_with_completion (simplified inner loop)
loop {
    self.end_state = None;
    while self.end_state.is_none() {
        self.pump_and_drive();  // exactly the same pump
    }
    let es = self.end_state.unwrap();
    if self.validate_modal_close(id, es) {
        break es;
    }
}

There is no new thread, no async runtime, no re-borrow. The difference between the outer run loop and the inner exec_view loop is only which end-state terminates them: the outer loop ends when the whole application quits; the inner loop ends when a view inside the dialog calls end_modal. When the inner loop exits it restores end_state to its pre-modal value, so the outer loop does not see the modal's end command.

A modal that opens another modal (for example a file dialog opening a history popup) adds a second exec_view frame on top; this is safe because each frame owns its own end_state snapshot and its own ModalFrame on the capture stack.

Sources: Program::run and exec_view_with_completion in src/app/program.rs.

Turbo Vision heritage: ports TGroup::execute (tgroup.cpp). C++ had one execute per active modal, each with its own getEvent loop. tvision-rs has one pump_and_drive loop shared by all levels; modality is a stack of ModalFrame capture handlers and end_state save/restore frames.

endModal

A view signals "close this modal and return result cmd" by calling ctx.end_modal(cmd) on its Context. This queues Deferred::EndModal(cmd) rather than acting immediately, because a view's handle_event runs inside the dispatch borrow and cannot reach the loop-owned end_state directly:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::event::Event;
use tv::view::{View, ViewState, Context, DrawCtx};
struct OkButton { state: ViewState }
impl View for OkButton {
    fn state(&self) -> &ViewState { &self.state }
    fn state_mut(&mut self) -> &mut ViewState { &mut self.state }
    fn draw(&mut self, _ctx: &mut DrawCtx) {}
fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
    if let Event::Command(cmd) = ev {
        if *cmd == tv::command::Command::OK {
            ctx.end_modal(tv::command::Command::OK);
            ev.clear();
        }
    }
}
}
}

The deferred drain, which runs every pump pass after dispatch, picks up the EndModal effect and writes end_state = Some(cmd). On the next iteration of exec_view's while end_state.is_none() loop, the condition becomes false and the loop exits.

Top-level code (outside a view, holding &mut Program) can call Program::end_modal directly. It sets end_state without the deferred queue, which is useful in tests that terminate a headless modal after pre-queuing events.

Rule of thumb: view code → ctx.end_modal; program-level code → Program::end_modal.

Sources: Context::end_modal (queues Deferred::EndModal) in src/view/context.rs; Deferred::EndModal application in src/app/program.rs.

Turbo Vision heritage: ports TView::endModal (tview.cpp). The C++ version wrote endState directly from inside the nested loop's stack frame; in tvision-rs the write is deferred via Deferred::EndModal because the view cannot reach the loop-owned end_state during dispatch.

Event capture

Several Turbo Vision behaviours share one mechanism in tvision-rs, the capture stack: a modal dialog that locks out the windows behind it, a window dragged by its title bar or resized from a corner, and a scrollbar arrow that keeps firing while the mouse button is held down.

A capture is a handler that sees every event before the normal view-tree routing. It can read the event, act on it, swallow it, or let it through. A few of these on a stack give modality, mouse tracking, drag/resize and press-and-hold without any nested event loop. The code lives in src/capture.rs and is driven by the one event loop in Program.

The stack

The event loop owns a single CaptureStack, a LIFO stack of handlers. When an event arrives, the loop offers it to the handlers top-down (most recently pushed first) before any view sees it. Each handler implements CaptureHandler and answers with a CaptureFlow:

CaptureFlowMeaning
PassI did not handle it. Offer it to the next lower handler, then to normal routing.
ConsumedI handled it; stop routing. I stay on the stack.
ConsumedPopI handled it and I am done. Remove me from the stack (for example a modal dialog closing, a mouse button released).

A handler holds a ViewId for the view it speaks for, never a view reference (see Pointers & infoPtr → handles). A handler that consumes every otherwise-unhandled event behaves like a blocking loop, so no code needs to write one.

Pushing is cooperative

A handler runs while the loop is holding the stack, so it cannot push another handler inline. It requests the push via Context::push_capture or the higher-level helpers, and the loop performs the push after dispatch, through the Deferred channel. As a result, a freshly pushed capture first sees the next event, never the one that pushed it.

What rides on it

The capture stack carries several features:

  • Modal dialogs. A modal dialog pushes a ModalFrame. While it is on the stack, mouse events are gated by the dialog's bounds: inside, they pass; outside, the pump hands them to the dialog alone, so the windows beneath never see the click. That gate is what "modal" means here. Keys, commands, pastes and the mouse wheel pass the frame and then go to the dialog alone; broadcasts pass and reach the whole tree. See Modal execView.

  • Window drag and resize. Grabbing a window's title bar or a resize corner in the Frame pushes a drag handler that owns the mouse until the button is released, translating each move into a new window position or size. The drag handler, the keyboard-resize handler and an open menu consume every other event while they hold the input, broadcasts included.

  • Press-and-hold across the widgets. A press and hold on a control makes the widget push a mouse-tracking capture that forwards masked move/auto-repeat events to that one view and discards everything else until the button comes up. Roughly ten widgets use this: Button, Cluster, Editor, InputLine, ScrollBar, ListViewer, Outline, the status line, the menus, and the window Frame. Each uses it for its own gesture (autoscroll, rubber-band selection, repeating arrows, drag-select), all over the same MouseTrackCapture.

Because a capture forwards events by ViewId rather than by reference, the loop performs the actual delivery on the widget's behalf. The cross-view plumbing for this (and for scrollbar↔scroller traffic) is the cross-view brokering seam. For the step-by-step path of each event through the stack and then the tree, see the event loop in depth.

The Deferred channel

In C++ Turbo Vision a view acts on anything at any time. While handling an event it can call endModal up its owner chain, enableCommand on the application, close() on itself, or reach across to a sibling scrollbar, all inline, because every object holds raw pointers to everything around it.

A Rust port cannot work that way, and this constraint shapes one of the framework's central seams.

Why a leaf can't act directly

While tvision-rs dispatches an event, the view tree is a live &mut borrow stack: root → desktop → window → frame → the focused control. Each ancestor is already borrowed mutably above the view on the stack. So the view being handled cannot reach up (its parents are borrowed) or sideways (a fresh root.find_mut(id) would alias a borrow already held higher up). It also does not hold the loop-owned state a C++ view could reach: the capture stack that drives modal dialogs, or the program's command set.

The view therefore does not act immediately. It records a request, and the event loop carries it out after dispatch unwinds and the tree is free again. That request is one variant of Deferred.

The shape of it

A view never constructs a Deferred itself. It calls a method on the Context it was handed (the downward context from pointers → handles, where there are no up-pointers), and that method pushes the variant onto a single queue. The loop drains the queue once per pump, in insertion order, and applies each effect against the state it owns.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(ctx: &mut tv::Context, id: tv::ViewId) {
// inside a view's handle_event: "close me" — recorded, not performed.
ctx.request_close(id);
}
}

Each variant names an effect on loop-owned state that the view could not perform inline. They fall into four disjoint families by what they touch:

FamilyEffectsC++ equivalent
Capture stackpush a capture handler (drives modal input)TGroup mouse capture
Command setenable / disable a commandenableCommand / disableCommand
View treechange bounds, set a state flag, close, focus, sync scrollbars, launch a view-triggered modal (OpenModal)setState, close, sibling pointers, execView from a view
Loop stateend the (modal) loop with a commandendModal

Because the families are disjoint, the order in which the loop applies effects across families never changes the result; effects within one family keep the order in which they were requested.

Why this shape

The alternative, giving every view a back-reference to the program, is the raw-pointer aliasing the port set out to remove. Deferring satisfies the borrow checker and keeps the rule short: a view describes what it wants; the one place that owns the tree decides when and how. A new capability costs a new variant, not a new parameter threaded through every view.

A deferred effect lands after the current event finishes. A pushed capture handler, for instance, sees the next event, never the one being handled. Other parts of the framework depend on this timing.

Going deeper

This page covers the reasons. For the mechanics (how the loop drains the queue, how the cross-view broker resolves sibling scrollbars, and how to add a new effect) see Deferred effects and The event loop in depth.

Dropped & changed

Most of the differences in this part transform a Turbo Vision concept into an idiomatic Rust shape. A few drop machinery outright, or keep something unchanged where a rewrite might be expected. This page collects those.

Streaming & persistence: dropped

Turbo Vision shipped its own object-serialization framework: TStreamable, the ipstream/opstream byte streams, a TStreamableClass type registry with factory functions, and TResourceFile resource files built on top. All of it existed because 1991 C++ had no reflection and no standard serialization, so Turbo Vision built both itself.

The port does not carry the machinery forward: there is no read/write/build on views, no streamableName, no class registry. Nothing in the core depends on it, so dropping it cost nothing.

If persistence is wanted later, the plan is serde (plus typetag for trait objects) on the specific data worth saving, without a framework-wide streaming layer. Resource files, if revived, become serde config or embedded assets, scoped to the actual need.

This has one visible effect elsewhere in the port: because command identities no longer need a stable integer for a stream format, they are namespaced strings instead of small integers; see Constant families → open newtypes.

Looking for getData/setData? That is not dropped. It became the typed value protocol. See Dialogs & data.

Damage tracking & buffered drawing: dropped

Turbo Vision's drawHide/drawShow/drawUnder* calls and its group-buffered, occlusion-aware writes were an optimization for slow hardware: avoid touching cells that need no change. The port replaces that scheme with whole-tree redraw plus a back-buffer diff: draw everything into a buffer, compare it to the last frame, and emit only the cells that changed. The optimization moves from per-write bookkeeping to one diff at the end.

Views never call lock/unlock or reason about what is occluded; they draw. The mechanics are in Drawing & backends; the rationale is The draw model.

TColorDialog: replaced by ColorPicker

Turbo Vision's TColorDialog, with its TColorSelector, TMonoSelector, TColorDisplay, TColorGroupList and TColorItemList helpers, edited the application's TPalette in place: each entry is a foreground/background attribute, picked from 16 BIOS colors for the foreground and 8 for the background. tvision-rs has no such palette: colors live in a role-based Theme and can be truecolor, so the cluster is not ported.

Its place is taken by ColorPicker, a truecolor picker view, and Program::color_dialog, which runs it as a modal and returns the chosen color. Editing a whole theme goes through Program::theme_editor. Both are listed on Extensions beyond Turbo Vision.

Coordinates stay i32 (unchanged)

magiblot's coordinates are plain C++ int. The port keeps them as i32 instead of usize or u16, for faithfulness.

Turbo Vision routinely computes negative and off-screen coordinates: a view scrolled partly above its owner, a delta that goes negative mid-calculation, a rectangle intersected down to nothing. An unsigned type would underflow on the arithmetic Turbo Vision does every frame. With the signed width, the geometry math in Point and Rect ports line-for-line from the C++ and behaves identically at the edges.

An i32 on a bounds calculation is intentional; changing it to usize would break the negative cases above.


The list of every difference lives in Differences from C++ Turbo Vision, and the C++→Rust name lookup is the symbol map.

Extensions beyond Turbo Vision

This page lists the widgets, options and subsystems tvision-rs adds to what magiblot/tvision offers. Convenience methods that wrap what a Turbo Vision program does by hand, such as Program::open_file_dialog, are not listed. Where the guide describes one of these features, a tvision-rs extension callout at the start of the section points back here.

New widgets

These have no Turbo Vision counterpart.

  • Table: a sortable multi-column list with a click-to-sort header, columns the user can resize, move and hide, and in-place cell editing. See the gallery and Controls.
  • Splitter: a resizable multi-pane layout with draggable dividers, a keyboard resize mode and divider lines that can join the window frame (junction). See Windows & the desktop and the gallery.
  • ColorPicker and Program::color_dialog: a truecolor picker with Presets, RGB, Hue/Sat and Xterm tabs, either embedded in a dialog or run as a ready-made modal that returns the chosen color. See the gallery.
  • MaskedInput and RevealEye: a password field that shows bullets, with a one-cell eye that reveals the text while held or for a timed peek. See the gallery.
  • TabBar and PageStack: a one-row tab selector and a container that shows one page at a time, coupled so the bar switches the page. The color picker is built from them.
  • Program::theme_editor: a dialog that lists every theme role, edits its colors with the color picker and installs the result on OK. See Theming & colors.
  • RegexValidator: an input-line validator driven by a regular expression, with the same type-as-you-go checking as the picture-mask validator. See Controls.

TColorDialog and its helper classes are not ported: they edited the application's TPalette, each entry a foreground/background attribute built from the BIOS colors, which tvision-rs replaces with a role-based theme. ColorPicker takes their place; see Dropped & changed.

New options on ported widgets

These extend a ported Turbo Vision class.

New subsystems

  • Keymap: the keys of the editor and the input line are a configurable table of chords, with WordStar, CUA and Emacs presets. See Keyboard & key mapping and Text editing.
  • Backend::get_primary and set_primary: middle-click pastes the X11 or Wayland PRIMARY selection into an input line or the editor, and a mouse selection in an input line becomes the PRIMARY selection for other programs.
  • HeadlessBackend and screen::snapshot: an in-memory terminal with injected input and an inspectable screen, and a stable text format of that screen for snapshot tests, for testing an application without a terminal.
  • CrosstermBackend wraps every frame in synchronized output (DEC mode 2026), so terminals that support it show each frame whole.

Windows & the desktop

Desktop and Window are the two core structural views of every tvision-rs program: a full-screen container that holds a patterned background and any number of overlapping windows. Both embed a Group and delegate the View trait to it (the embed-and-delegate pattern; see Inheritance → trait + composition), so a desktop is a view and a window is a view: you insert windows into a desktop, and child controls into a window (these are the tvision-rs equivalents of the C++ TDeskTop/TWindow pair).

The desktop

You rarely build a Desktop by hand at runtime; the application skeleton's init_desktop factory does it for you. In the hello example that factory insets the bounds one row below the menu bar and one above the status line, then calls Desktop::new with a background factory. Pass Desktop::init_background for the classic light-shade (░) fill, which builds a Background. The skeleton wires all three factories into the program at construction:

//! `hello` — a minimal Turbo Vision application, written in the shape a
//! magiblot/tvision (C++) veteran will recognise on sight: a desktop with a
//! patterned background and a few windows, a menu bar at the top, and a status
//! line at the bottom, all driven by the real `TProgram::run` event loop.
//!
//! The C++ skeleton this mirrors:
//!
//! ```cpp
//! class HelloApp : public TApplication {
//!     static TDeskTop    *initDeskTop(TRect);
//!     static TStatusLine *initStatusLine(TRect);
//!     static TMenuBar    *initMenuBar(TRect);
//! };
//!
//! int main() {
//!     HelloApp app;
//!     app.run();          // spins the event loop until cmQuit
//! }
//! ```
//!
//! Run it:  `cargo run --example hello`
//!   - `F10` enters the menu bar; arrows + Enter navigate it.
//!   - `Alt-F`/`Alt-W` open the File / Window menus by hot-key.
//!   - `Alt-X` (or File → Exit) quits.
//!   - `F3` or File → Open opens a file in an editor window.
//!   - `F4` or File → New opens an untitled editor window.
//!   - `F2` or File → Save saves the current editor file.
//!   - `F5` zooms the current window, `Alt-F3` closes it, `F6` cycles.
//!   - `Alt-1`..`Alt-9` select a window by number.
//!   - `Color → Color Picker…` opens the truecolor picker.

use std::io;

use tvision_rs::{
    Backend, Color, Command, CrosstermBackend, Desktop, EditWindow, Key, KeyEvent, Menu, MenuBar,
    Program, Rect, StatusDef, StatusLine, SystemClock, Theme, View, Window, alt,
};

const CMD_COLOR_PICKER: Command = Command::custom("hello.color_picker");
const CMD_NEW: Command = Command::custom("hello.new");
const CMD_OPEN: Command = Command::custom("hello.open");

// ---------------------------------------------------------------------------
// HelloApp : public TApplication
// ---------------------------------------------------------------------------

/// The application class. In C++ this would derive `TApplication` and override
/// the three `init*` factories; here it wraps the [`Program`] it builds from
/// them via [`Program::new`] (the port's `TProgInit` factory-mixin seam).
struct HelloApp {
    program: Program,
}

impl HelloApp {
    /// `HelloApp::HelloApp` → `TProgInit(initStatusLine, initMenuBar, initDeskTop)`.
    fn new(backend: Box<dyn Backend>) -> Self {
        let program = Program::new(
            backend,
            Box::new(SystemClock::new()),
            Theme::classic_blue(),
            Self::init_desktop,
            Self::init_status_line,
            Self::init_menu_bar,
        );
        // No enable_command registration is needed for the app-minted commands
        // (CMD_COLOR_PICKER / CMD_NEW / CMD_OPEN): every command is enabled by
        // default (D1 denylist) — only the five window-management commands start
        // disabled, until a window grants them on selection.
        HelloApp { program }
    }

    /// `TApplication::initDeskTop` — `r.a.y++; r.b.y--` to inset the desktop one
    /// row below the menu bar and one row above the status line, the patterned
    /// background (`TDeskTop::initBackground`), then a few demo windows so the
    /// window-management commands (zoom / close / next) have something to act on.
    fn init_desktop(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.a.y += 1; // below the menu bar
        r.b.y -= 1; // above the status line
        let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
        // Insert three staggered demo windows numbered 1..=3 (Alt-1..Alt-3 select
        // them; the desktop's cmNext/cmPrev cycle them).
        for num in 1..=3i16 {
            let x = 4 + (num as i32) * 4;
            let y = 1 + (num as i32) * 2;
            let mut win = Window::new(
                Rect::new(x, y, x + 28, y + 8),
                Some(format!("Window {num}")),
                num,
            );
            // TWindow does NOT set ofTileable; the app opts its windows in so
            // Window → Tile / Cascade lay them out.
            win.state_mut().options.tileable = true;
            desktop.insert_view(Box::new(win));
        }
        Some(Box::new(desktop))
    }

    /// `TApplication::initStatusLine` — `r.a.y = r.b.y - 1` (pin to the bottom
    /// row), then the standard line: labelled `Alt-X Exit` (cmQuit) and
    /// `F10 Menu` (cmMenu), plus hidden hotkey bindings for `Alt-F3` close,
    /// `F5` zoom, `F6` next — the shape `initStatusLine` builds.
    fn init_status_line(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.a.y = r.b.y - 1;
        let defs = StatusDef::list()
            .def_all(|d| {
                d.item("~F3~ Open", KeyEvent::from(Key::F(3)), CMD_OPEN)
                    .item("~F4~ New", KeyEvent::from(Key::F(4)), CMD_NEW)
                    .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                    .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
                    .key_item(alt_f3(), Command::CLOSE)
                    .key_item(KeyEvent::from(Key::F(5)), Command::ZOOM)
                    .key_item(KeyEvent::from(Key::F(6)), Command::NEXT)
            })
            .build();
        Some(Box::new(StatusLine::new(r, defs)))
    }

    /// `TApplication::initMenuBar` — `r.b.y = r.a.y + 1` (pin to the top row),
    /// then a File / Window menu. The Window menu now includes **Tile** and
    /// **Cascade** (cmTile/cmCascade route through `program_handle_event` to
    /// `Desktop::tile`/`cascade`); every item wires a command that routes.
    fn init_menu_bar(r: Rect) -> Option<Box<dyn View>> {
        let mut r = r;
        r.b.y = r.a.y + 1;
        let menu = Menu::builder()
            .submenu("~F~ile", alt('f'), |m| {
                m.command_key("~O~pen…", CMD_OPEN, KeyEvent::from(Key::F(3)), "F3")
                    .command_key("~N~ew", CMD_NEW, KeyEvent::from(Key::F(4)), "F4")
                    .separator()
                    .command_key("~S~ave", Command::SAVE, KeyEvent::from(Key::F(2)), "F2")
                    .command("Save ~A~s…", Command::SAVE_AS)
                    .separator()
                    .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
            })
            .submenu("~W~indow", alt('w'), |m| {
                m.command_key("~N~ext", Command::NEXT, KeyEvent::from(Key::F(6)), "F6")
                    .command_key("~Z~oom", Command::ZOOM, KeyEvent::from(Key::F(5)), "F5")
                    .command_key("~C~lose", Command::CLOSE, alt_f3(), "Alt-F3")
                    .command("~T~ile", Command::TILE)
                    .command("C~a~scade", Command::CASCADE)
            })
            .submenu("~C~olor", alt('c'), |m| {
                m.command("Color ~P~icker…", CMD_COLOR_PICKER)
            })
            .build();
        Some(Box::new(MenuBar::new(r, menu)))
    }

    /// `TApplication::run` — spin the real event loop until a `cmQuit` ends it.
    /// Handles application-level commands (the `TApplication::handleEvent` slot).
    fn run(&mut self) -> Command {
        let mut next_num: i16 = 4; // demo windows 1-3 are pre-inserted; start at 4
        self.program.run_app(move |prog, cmd| {
            if cmd == CMD_NEW {
                let r = prog.desktop_rect();
                let win = EditWindow::new(r, None, next_num);
                prog.desktop_insert(Box::new(win));
                next_num += 1;
            } else if cmd == CMD_OPEN {
                if let Some(path) = prog.open_file_dialog("Open a File", "*.*") {
                    let r = prog.desktop_rect();
                    let win = EditWindow::new(r, Some(path), next_num);
                    prog.desktop_insert(Box::new(win));
                    next_num += 1;
                }
            } else if cmd == CMD_COLOR_PICKER {
                let initial = Color::Rgb(30, 144, 255);
                if let Some(color) = prog.color_dialog(initial) {
                    eprintln!("Color picker returned: {color:?}");
                }
            }
        })
    }
}

/// `Alt-F3` — the classic "close window" accelerator (`kbAltF3`).
fn alt_f3() -> KeyEvent {
    use tvision_rs::KeyModifiers;
    KeyEvent::new(
        Key::F(3),
        KeyModifiers {
            alt: true,
            ..Default::default()
        },
    )
}

// ---------------------------------------------------------------------------
// int main()
// ---------------------------------------------------------------------------

fn main() -> io::Result<()> {
    // CrosstermBackend::new() owns the whole terminal lifecycle (raw mode,
    // alternate screen, mouse capture; restored on drop / panic / signal) —
    // just like the C++ TApplication constructor chain.
    let mut app = HelloApp::new(Box::new(CrosstermBackend::new()?));
    let _result: Command = app.run();
    Ok(())
}

Opening windows

A Window is constructed with its bounds, an optional title, and a window number (1–9 become the Alt-1…Alt-9 selectors; 0 means "no number"). By default it is movable, resizable, closable and zoomable: all four WindowFlags start true (corresponding to the C++ wfMove | wfGrow | wfClose | wfZoom flags).

To put a window on screen at construction time, insert it into the desktop. At runtime, from inside the run loop, open one through the program, which inserts it into the desktop and gives it focus in one step:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::Window;
fn _demo(prog: &mut tv::Program) {
let next_num: i16 = 1;
let r = prog.desktop_rect();
let win = Window::new(r, Some("Untitled".into()), next_num);
prog.desktop_insert(Box::new(win));
}
}

To give a window scroll bars, call Window::standard_scroll_bar with ScrollBarOptions: its vertical flag selects the right edge (else the bottom), and handle_keyboard opts the bar into post-processing of the focused chain's arrow keys. It inserts the bar on the correct edge and returns its ViewId. For child controls, use Window::insert_child.

Z-order, focus and window commands

Windows overlap, and the topmost one is the active window. It draws its frame in the active style and receives keyboard events. The active window enables the five window-management commands while it is selected; they are disabled otherwise (the framework starts them off; see Commands & events):

Commandhello keyEffect
Command::NEXTF6Cycle focus to the next window
Command::PREVnoneSend the active window to the back
Command::ZOOMF5Toggle between restored size and filling the desktop
Command::CLOSEAlt-F3Close the active window
Command::RESIZEnoneEnter keyboard move/resize mode (arrows, Enter/Esc)
Command::FULLSCREENnoneCycle the active window through Off/Desktop/Screen (no default key; example binds F4)

The keys above are the bindings the hello example installs on its status line and menu; the commands themselves carry no built-in key.

You can also drag a window by its title bar to move it, or by a bottom corner to resize it; the desktop routes the click and the window starts the drag. The drag runs as a capture handler on the single event loop, with no nested loop (see Modal execView → one loop + capture) (C++ used a dedicated dragView nested-mouse-loop for this).

Fullscreen windows

tvision-rs extension to TWindow: not in Turbo Vision. See Extensions beyond Turbo Vision.

A window can fill the screen without its frame border via three modes of Fullscreen:

ModeWhat you see
Fullscreen::OffNormal framed window (the default).
Fullscreen::DesktopFrameless; fills the desktop area. The menu bar and status line are unchanged.
Fullscreen::ScreenFrameless; also covers the menu row. The menu bar collapses to a [⋮] kebab at the top-right corner that opens a popup with the full menu.

Call set_fullscreen to switch modes, or dispatch Command::FULLSCREEN to cycle Off → Desktop → Screen → Off on the active window:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{Window, Fullscreen, Context};
fn _demo(win: &mut Window, ctx: &mut Context) {
// Drive the active window frameless, filling the desktop:
win.set_fullscreen(Fullscreen::Desktop, ctx);

// ...or compose the independent primitives directly:
win.set_bordered(false, ctx);  // hide the frame border
win.maximize(ctx);             // grow to fill the owner
}
}

Composable primitives

set_fullscreen is a thin composer over three independent primitives that apps can also call directly:

  • set_bordered(bool, ctx) / bordered() -> bool: show or hide the frame border. Toggling it reflows content through each child's existing grow modes: every content child resizes and shifts by the border thickness, and owned scroll bars re-anchor to the new client edge. Idempotent.
  • maximize(ctx) / restore(ctx) / is_maximized() -> bool: one maximize/restore slot, shared by Command::ZOOM and Fullscreen::Desktop so they cannot desync. maximize fills the owner; restore returns to the saved pre-maximize bounds.
  • client_rect() -> Rect: the content area: inset by the frame when bordered, full extent when frameless, minus any scroll-bar lanes (the right column for a vertical bar, the bottom row for a horizontal one). Content placed at client_rect fills up to the bars without overlapping them, regardless of border state.

For Fullscreen::Screen, the pump calls MenuBar::set_collapsed(true) on the application menu bar and shrinks the desktop to the full screen height; on exit it restores both. See Menus for the menu bar layout.

Tiling and cascading

The desktop can auto-arrange its tileable windows. Desktop::tile packs them into a most-equal grid; Desktop::cascade stacks them stepped down and to the right. Both skip windows that are not visible or not marked tileable, and both leave a window's bounds unchanged when it will not fit. Note that Window does not set the tileable option for you; opt a window in explicitly:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::View;
fn _demo(win: &mut tv::Window) {
win.state_mut().options.tileable = true;
}
}

The hello example wires Command::TILE / Command::CASCADE menu items that route to these calls, so its three demo windows rearrange on command.

Splitter: resizable panes

tvision-rs extension: not in Turbo Vision. See Extensions beyond Turbo Vision.

A Splitter divides a rectangle into N panes along one axis, separated by 1-cell divider seams that the user can drag to resize. Use it to build IDE-style or file-manager-style layouts inside a window.

Axes and panes

use tvision_rs::{Splitter, Constraints};

// Side-by-side panes (vertical dividers):
let h = Splitter::cols()
    .pane(left_view, Constraints::fixed(20))   // 20-cell sidebar
    .pane(right_view, Constraints::flex());     // rest of the space

// Stacked panes (horizontal dividers):
let v = Splitter::rows()
    .pane(top_view, Constraints::flex())
    .pane(bottom_view, Constraints::flex());

Splitter::cols() splits along x (side-by-side); Splitter::rows() splits along y (stacked). Each .pane(view, constraints) call appends a pane.

Constraints

Constraints control how much space a pane claims along the axis:

ConstructorMeaning
Constraints::flex()Elastic: takes its share of remaining space (weight 1)
Constraints::weight(w)Elastic with a custom weight
Constraints::fixed(n)Pinned to exactly n cells
.min(n) builderMinimum size in cells

Divider styles

DividerStyle controls how a seam looks and behaves:

VariantLookDraggable?
Line (default)Always-visible │ / ─Yes
HandleOnly a grab nub at midpointYes
HiddenInvisible in normal useOnly in resize mode
LockedInvisible and immovableNever

Set a per-seam style with .divider(i, style) or a blanket default with .default_divider(style).

Live drag and keyboard resize

Dragging a Line or Handle seam with the mouse resizes immediately. Pressing Ctrl-F5 (bound to Command::RESIZE) enters resize mode: Tab / Shift-Tab cycle the resize target between the window itself and each splitter divider; Enter commits; Esc cancels. Locked seams are skipped when cycling.

While the window is the active target, plain arrows move the window and Shift+arrows resize (grow) it, matching the classic TView::change contract. Ctrl scales the step to ±8 cells horizontally / ±4 vertically, so Ctrl+arrow is a big move and Ctrl+Shift+arrow is a big resize.

While a divider is the active target, plain arrows nudge it ±1 cell along its axis; Shift and Ctrl are ignored for dividers.

Nested splitters

A Splitter can contain another Splitter as a pane, building grid layouts:

use tvision_rs::{Splitter, Constraints, StaticText, Rect};

// Right column: two stacked panes.
let right = Splitter::rows()
    .pane(Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "top")), Constraints::flex())
    .pane(Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "bottom")), Constraints::flex());

// Outer: fixed sidebar + the nested right column.
let split = Splitter::cols()
    .pane(Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "sidebar")), Constraints::fixed(16))
    .pane(Box::new(right), Constraints::flex());

Joined linework

By default a splitter draws plain │/─ dividers. Call .joined() on the outermost splitter to connect the divider lines:

  • to the surrounding window frame: ┬ / ┴ at the top and bottom edges, ├ / ┤ at the left and right edges;
  • to each other inside nested splitters: interior ├ / ┤ / ┬ / ┴ / ┼ crossings.

Joining cascades: .joined() is needed only on the outermost splitter, and all nested pane-splitters inherit it. Override the grow mode (a splitter fills its owner by default) with .with_grow_mode(GrowMode::default()) for a fixed-size splitter.

use tvision_rs::{Splitter, Constraints, StaticText, Rect};

let split = Splitter::cols()
    .pane(Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "left")), Constraints::flex())
    .pane(Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "right")), Constraints::flex())
    .joined();   // connects divider lines to the window frame

A live example showing .joined() on a nested three-pane layout is in the Widget gallery.

Limiting move and resize

Every view carries a DragMode, a struct of bools controlling whether a window can be moved or resized, and which edges constrain the drag. Window sets drag_move and drag_grow by default (the user can drag the title bar to move and the bottom corners to resize).

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{DragMode, View};
fn _demo(win: &mut tv::Window) {
// Make the window movable but not resizable:
win.state_mut().drag_mode = DragMode {
    drag_move: true,
    drag_grow: false,
    drag_grow_left: false,
    limit_lo_x: true,
    limit_lo_y: true,
    limit_hi_x: true,
    limit_hi_y: true,
};
}
}

The limit_* bits clamp the drag to the owner's extent. Without them the user can drag the window partially off-screen. DragMode::limit_all() is a convenience that sets all four limit bits at once; it is the standard setting for a window that must remain fully on the desktop.

The drag_grow_left bit adds the left edge as a resize target. By default only the bottom-right corner is draggable; drag_grow_left: true extends resize to the left edge as well (useful for left-aligned panels).

Source: src/view/view.rs (DragMode), src/window/window.rs (window default drag setup).

Turbo Vision heritage: dmDragMove/dmDragGrow/dmLimitXxx were bit-field constants combined with |. tvision-rs replaces them with a struct of bools (deviation D5); the individual fields replace the bit-shift arithmetic.

Grow modes: anchoring edges

GrowMode controls how a child view reacts when its owner group is resized. Each gf* bit anchors one edge of the child to the corresponding edge of the owner. When the owner grows, the anchored edge moves with it.

FieldMeaning when true
lo_x (left edge)tracks the owner's right edge: child slides right
lo_y (top edge)tracks the owner's bottom edge: child slides down
hi_x (right edge)tracks the owner's right edge: child widens
hi_y (bottom edge)tracks the owner's bottom edge: child grows taller
fixedoverride: child size is fixed; none of the above apply
relproportional scale instead of absolute anchoring

A child whose right and bottom edges track the owner's (hi_x: true, hi_y: true) fills the owner and grows with it. A child whose left and right edges both track the owner's right (lo_x: true, hi_x: true) keeps a fixed width but slides to maintain its right-edge distance.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{GrowMode, View};
fn _demo(child: &mut tv::widgets::StaticText) {
// Child fills its owner (grows on both axes):
child.state_mut().grow_mode = GrowMode {
    hi_x: true,
    hi_y: true,
    ..Default::default()
};
}
}

GrowMode::grow_all() sets lo_x | lo_y | hi_x | hi_y: every edge tracks the owner, so the child maintains its margins on all four sides.

Grow mode is applied by View::change_bounds (src/view/view.rs): when a group is resized, it calls calc_bounds on each child (which applies the grow formula) and then change_bounds to commit the new rectangle. After that the pump calls on_bounds_changed, which the group passes to each child, so lists and scrollers inside the window update their scroll bars to the new size (see Reacting to a terminal resize).

Source: src/view/view.rs (GrowMode, ViewState::calc_bounds).

Turbo Vision heritage: the gf* constants (gfGrowLoX, gfGrowHiX, …) were individual bits in a ushort. tvision-rs maps each to a named bool field in GrowMode (deviation D5).

Bringing a window to the front

Z-order in a group is reverse insertion order: the most recently inserted child sits on top. When the user clicks a window or presses Alt-N, the framework calls Group::focus_child on the desktop. focus_child checks whether the outgoing current view wants to keep focus (the ofValidate path), then, because windows opt into raise-on-select (Options::top_select = true), calls Group::make_first: the window is moved to the last slot of the children Vec (the top slot in paint order).

There is no general "reorder to arbitrary Z position" primitive. Only two operations exist:

  • make_first(id, ctx): raises one view to the very top.
  • put_in_front_of(id, target, ctx): places id immediately in front of target (one slot above it in paint order).

make_first is the primitive; put_in_front_of(id, None, ctx) is its definition. Both are no-ops when the child is already in the target position.

Clicking any window brings it to the top of the stack and makes it active. The previous front window becomes passive (its frame changes color) and receives the StateFlag::Active clear cascade.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::View;
fn _demo(desktop: &mut tv::Group, win_id: tv::ViewId, ctx: &mut tv::Context) {
// Raise a window to the front programmatically:
desktop.make_first(win_id, ctx);
}
}

Source: src/view/group.rs (Group::focus_child, Group::make_first, Group::put_in_front_of, and the top_select option check).

Turbo Vision heritage: TGroup::makeFirst / putInFrontOf performed the same move in the circular doubly-linked sibling ring. tvision-rs stores children in a Vec and implements raise-to-top as a swap to the last slot (deviation D3).

See also

The data-movement model

A tvision-rs application moves values across view boundaries constantly: a user types text into an input line and the dialog gathers it; a scroller shifts its position and two scrollbars have to follow; a color-picker modal closes and its chosen color lands back in the caller. In C++ Turbo Vision all three of those motions went through the same loose channel (getData/setData for records, message()/infoPtr for signals, execView returning a bare ushort), and the caller interpreted a raw pointer or cast an integer back to a useful type.

In Rust, every "move this value to there" needs a typed answer, and the answer differs by what is being moved. tvision-rs gives one typed currency and one mechanism per kind of movement.

The three kinds

KindCurrency / mechanismDeep-dive
Field & record data (dialog ↔ controls)FieldValue via value() / set_value(); groups gather/scatter an ordered ListDialogs & data, Third-party components
Sync signals (sibling ↔ sibling)Defaulted View trait methods brokered by the pump (apply_scroll_sync, set_indicator_value, apply_page_sync)Cross-view brokering & ViewId
By-value modal resultsProgram::exec_view_with<R> (result by value) or Context::request_exec_view (record via set_modal_data, then close command via set_modal_answer)Modal execView → one loop

Field & record data

FieldValue is the single typed currency for data that moves between a dialog and its controls. The well-known shapes (Text, Int, Bool, Bits, List) interoperate with framework widgets and generic consumers. Custom(Rc<dyn CustomValue>) is the open seam for a payload your own component invents; the framework moves it opaquely and the consumer downcasts at the edge (runtime-checked, fail-loud).

A control exposes its value via View::value() and absorbs a new one via View::set_value(). A group gathers its children in insertion order into a FieldValue::List (Group::gather_list) and scatters a list back the same way (Group::scatter_list). This is the typed successor to C++ getData/setData: the same positional, anonymous walk over children, now statically typed.

See Dialogs & data for the full recipe and Third-party components for the Custom seam and the three open extensibility paths.

Sync signals

A scroller cannot reach its scrollbars inline: during event dispatch it holds only a downward &mut Context, and the borrow checker forbids a sideways reach to a sibling. Instead the scroller queues a deferred effect (Deferred::ScrollSync), and the pump, which owns the whole tree, resolves the target by ViewId and calls the appropriate defaulted View method (apply_scroll_sync, set_indicator_value, apply_page_sync) by virtual dispatch. The pump is the broker; there is no downcast and no pointer-chasing.

This is the return-less, deferred successor to C++ message(target, …, infoPtr) (deviation D3/D9). Sync signals are kept separate from field data because they are behavioral pokes ("recompute from your scrollbar") with no value to marshal and scatter, so they stay out of FieldValue.

See Cross-view brokering & ViewId for the broker pattern in depth.

By-value modal results

How a modal hands its result back depends on who opened it.

Turbo Vision heritage: C++ execView returned a ushort end command; the caller read results from the still-live dialog with getData. tvision-rs keeps that shape (run the modal, read the result before it is torn down), but the return type is now caller-named Rust instead of a bare integer.

Choosing how a modal returns its result

The decision rule:

Opened from a Program / Application method → use Program::exec_view_with<R>. At the pre-drop window, while the view is still in the tree, the extract closure receives the modal's &mut dyn View and the end command; whatever it returns comes back by value. Use this path when the result type is rich and does not map to FieldValue (for example Color or a whole Theme).

let chosen: Option<Color> = program.exec_view_with(Box::new(dialog), |modal, cmd| {
    (cmd == Command::OK)
        .then(|| read_color_from(modal))
        .flatten()
});

Opened from inside a view's handle_event → a view holds only &mut Context, never &mut Program, so it cannot call exec_view_with inline. Call ctx.request_exec_view(view, requester, then_command) instead; this queues Deferred::OpenModal and returns immediately. The pump picks it up on the same turn, runs the modal through the existing single-loop machinery, and on close delivers, in this order, the modal's record (value(), for a Dialog its gathered FieldValue::List) via View::set_modal_data (skipped when the close command is Command::CANCEL) and the close command via View::set_modal_answer(Command); the requester overrides the hooks it needs. See Getting the data back.

What stays separate, on purpose

Not everything is forced into FieldValue or routed through the pump:

  • Event::Broadcast { source } carries a ViewId as a subject filter that addresses a view and carries no data. A scrollbar sets itself as source so a scroller can tell which bar fired. This is infoPtr-as-subject, unchanged from C++ (deviation D4).
  • Color and Theme cross by value via exec_view_with<R> instead of as FieldValue. Color is a four-variant enum (Default/Bios/Indexed/Rgb) that does not pack into a scalar, and Theme is far larger than any field exchange warrants. Both are deliberate exceptions, documented at their sites.
  • Structural parent→child pushes (a frame being told it is zoomed, a window pushing display state into its known child frame) still resolve a known child directly. This is a parent orchestrating its own known composition, a category separate from data movement, and it stays where it is.

Where to go next

Dialogs & data

A dialog is a modal window: it appears on top of everything, captures input until the user dismisses it, and returns a single answer: which button closed it. Dialog embeds a Window and delegates to it, with dialog-specific behaviour layered on: Esc cancels, Enter accepts the default button, and the frame carries only the move and close affordances, without grow or zoom (the tvision-rs equivalent of C++ TDialog).

Building a dialog

Construct the dialog with a rectangle and an optional title, then populate it with child views (buttons, input lines, checkboxes, labels) via insert_child:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{Command, Dialog, Rect};
use tv::widgets::{Button, ButtonFlags, InputLine};
let mut dialog = Dialog::new(Rect::new(0, 0, 40, 11), Some("Sign in".into()));

// insert_child returns the child's ViewId, so you can reach it later.
let name = dialog.insert_child(Box::new(InputLine::with_limit(
    Rect::new(3, 4, 34, 5),
    64, // byte limit (the convenience ctor uses LimitMode::MaxBytes)
)));
dialog.insert_child(Box::new(Button::new(
    Rect::new(15, 8, 25, 10),
    "~O~K",
    Command::OK,
    ButtonFlags { default: true, ..Default::default() },
)));
let _ = name;
}

InputLine::new takes a validator and a LimitMode too; with_limit is the no-validator, byte-limit shortcut. ButtonFlags is a struct of named bools, so the default button is ButtonFlags { default: true, .. }.

A button carries the Command it broadcasts when pressed. The conventional end commands are Command::OK and Command::CANCEL; a message box also uses Command::YES / Command::NO.

A dialog assembled this way, with a labelled input, check boxes, and the two buttons, looks like this:

  File  Edit  Window                                
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]════════════ Settings ════════════════╗░░░░░░
░░║                                          ║░░░░░░
░░║  Name:                                   ║░░░░░░
░░║                                          ║░░░░░░
░░║                                          ║░░░░░░
░░║  [X] Enable logging                      ║░░░░░░
░░║  [ ] Auto-save                           ║░░░░░░
░░║  [ ] Show hints                          ║░░░░░░
░░║                                          ║░░░░░░
░░║                                          ║░░░░░░
░░║         OK    ▄              Cancel   ▄  ║░░░░░░
░░║      ▀▀▀▀▀▀▀▀▀▀            ▀▀▀▀▀▀▀▀▀▀▀▀  ║░░░░░░
░░╚══════════════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                               

The runnable source is the dialog entry in the widget gallery.

Running it modally

You do not insert a dialog into the view tree yourself. You hand it to Program::exec_view. It inserts the dialog at the top of the tree, marks it modal, gives it focus, and spins the same event loop until the dialog ends itself, then removes it and hands back the closing command:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{Command, Dialog};
fn _demo(program: &mut tv::Program, dialog: Dialog) {
match program.exec_view(Box::new(dialog)) {
    Command::OK     => { /* read the fields back, act on them */ }
    Command::CANCEL => { /* user backed out */ }
    _ => {}
}
}
}

There is no separate "modal loop." tvision-rs runs a single event loop plus a capture stack: exec_view pushes the dialog as the capture target, and the loop drives it until the dialog closes itself (see Modal execView → one loop + capture and the event loop in depth). exec_view is top-level only: a view holds only a &mut Context, never the Program, so it cannot re-enter the loop from inside handle_event. This keeps the single loop sound.

Turbo Vision heritage: in C++ each TGroup::execView spun a fresh nested getEvent loop. tvision-rs collapses all modal nesting into one loop + capture stack, which removes the reentrancy.

A modal must have a path to closing itself, or it hangs. Dialog provides one by default: Esc becomes a Cancel, the default button becomes an OK. If you build a bare modal with neither, nothing will end it.

The framework ships ready-made modals built on this path: message_box for a titled alert with Yes/No/OK/Cancel buttons, and input_box for a single labelled text field. Both build a Dialog, run it through exec_view, and return the user's answer.

Moving data in and out

Dialog data flows through a typed value currency, FieldValue, passed through the value / set_value pair on the View trait. A text field reads and writes FieldValue::Text; an integer control uses FieldValue::Int. The enum grows as controls need it (this replaces the C++ getData/setData pair, which moved data through an untyped memcpy record).

Two operations bracket a dialog:

Turbo Visiontvision-rsDirection
setDatascatter: set_value on each fieldseed the dialog before showing it
getDatagather: value() on each fieldread results after OK

For a single-field dialog you call set_value/value on that one field directly; input_box does this internally to seed and read its lone input line. For a multi-field dialog, the Group behind the dialog walks its children in order: gather_data collects a Vec<Option<FieldValue>> (one slot per child, None where a child has no transferable value), and scatter_data distributes a matching vector back in the same child order. Seed before exec_view, gather after it returns Command::OK.

The full FieldValue currency

FieldValue is the single typed currency for all data exchange in tvision-rs. The well-known shapes are:

VariantProduced by
Text(String)InputLine, Editor
Int(i64)numeric inputs
Bool(bool)single-item toggle controls
Bits(u32)CheckBoxes / RadioButtons cluster
List(Vec<FieldValue>)Group::gather_list / scatter_list
Custom(Rc<dyn CustomValue>)your own controls

Bool carries a simple toggle; Bits carries a bitmask from a cluster (each CheckBoxes or RadioButtons bit maps to one check or radio item in order).

Ordered-record gather and scatter

When you want the whole dialog's data as one value instead of one field at a time, use the ordered-record pair on Group:

// Seed before exec_view — positional, same child order as insert_child.
// scatter_list takes a &mut Context (available inside a handle_event / the pump):
let initial = FieldValue::List(vec![
    FieldValue::Text("Alice".into()),
    FieldValue::Bits(0b01),  // first checkbox ticked
]);
dialog.scatter_list(&initial, ctx);

// Read after exec_view returns Command::OK:
let record = dialog.gather_list();
// record == FieldValue::List([FieldValue::Text(...), FieldValue::Bits(...)])

gather_list walks the group's children in insertion order and collects each child's value() into a FieldValue::List, the positional equivalent of C++ getData's memcpy record. scatter_list distributes the list back in the same order via set_value. Children with no transferable value (labels, decorative views) are skipped in both directions; the list contains only the slots that produce a value, so the index order matches the sequence of data-bearing children.

Dialog::value() returns the same record (gather_list()), so a dialog nested in another group, or a view that delegates value to a dialog, hands over its whole record through the ordinary value() call.

The Custom seam and third-party controls

For richer payloads, such as a date range, a colour swatch or a structured selection, a control can return FieldValue::Custom(...). See Third-party components & data interchange for the details: the three exchange paths, value_as::<T>() / as_custom::<T>(), the TypeId caveat, and when to skip FieldValue entirely.

Delivering a modal's result back to its launcher

How a modal's result reaches the view that opened it depends on who opened it.

Program-launched modals, opened from outside the view tree (for example the color picker or theme editor), return their result directly: the pump runs exec_view_with<R>, the closure reads the modal's state while it is still in the tree, and the result comes back as a plain Rust value. Use this path when the result type is rich and does not map naturally to FieldValue (such as Color or Theme).

View-launched modals, opened from inside handle_event via the Deferred channel, cannot return inline (a view holds only &mut Context, never the Program). Instead, after the modal closes, the pump reads each dialog field by id via View::value() and delivers the assembled result to the launcher by id via View::set_modal_data(FieldValue) (virtual dispatch, no downcast). The launcher overrides set_modal_data to interpret the ordered FieldValue::List and update its own state. The editor's Find/Replace modals follow this pattern: the pump reads the text field as FieldValue::Text and the options cluster as FieldValue::Bits, then calls editor.set_modal_data(List([Text, Bits])).

A modal you launch yourself with Context::request_exec_view gets the same delivery without a custom completion: on a non-cancel close the pump reads the modal's value() (for a Dialog, its gathered FieldValue::List) and calls requester.set_modal_data(record) before set_modal_answer(command) (see Getting the data back).

Note that set_modal_data is distinct from set_value: set_value carries a view's own document or field data (the D10 scatter path); set_modal_data carries a modal's result collected by the pump on the launcher's behalf.

Tab order and data transfer

Both Tab navigation and gather/scatter data order follow the single children Vec in the group, specifically the insertion order (oldest first, as stored in children[0], children[1], …). The children are stored back-to-front for painting, and forward for data transfer: gather_data walks them oldest-first and returns one Option<FieldValue> per child.

inserted 1st → children[0]  (Tab: first stop; gather: slot 0)
inserted 2nd → children[1]  (Tab: second stop; gather: slot 1)
…
inserted last → children[n] (Tab: last stop; gather: slot n)

Tab calls Group::focus_next(forwards: true, ctx), which iterates children in forward order and wraps around. Shift-Tab iterates in reverse. Disabled or invisible children are skipped: they remain in the children slice but focus_next steps over them.

When you assemble a dialog, insert controls in the order you want the Tab key to visit them, typically top-to-bottom, then left-to-right. Buttons are usually inserted last so they receive focus after all the data fields.

Gather (the dialog walking its children to collect values) follows the same forward order. Scatter distributes values in the same order. The index in the Vec<Option<FieldValue>> that gather_data returns corresponds 1:1 to the insertion slot: index 0 is the first-inserted child, index 1 is the second, and so on.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{Command, Dialog, Rect};
use tv::widgets::{Button, ButtonFlags, InputLine, LimitMode};
#[allow(unused_variables)]
fn _demo() {
let mut dialog = Dialog::new(Rect::new(0, 0, 40, 10), Some("Login".into()));

// Insert in Tab order: name first, password second, button last.
let name_id   = dialog.insert_child(Box::new(InputLine::new(Rect::new(3, 3, 34, 4), 64, None, LimitMode::MaxBytes)));
let pass_id   = dialog.insert_child(Box::new(InputLine::new(Rect::new(3, 5, 34, 6), 64, None, LimitMode::MaxBytes)));
let _btn_id   = dialog.insert_child(Box::new(Button::new(Rect::new(15, 7, 25, 9), "~O~K", Command::OK, ButtonFlags { default: true, ..Default::default() })));

// After exec_view returns Command::OK, gather in the same order:
// gathered[0] = name, gathered[1] = password, gathered[2] = None (button has no value).
}
}

Source: src/view/group.rs (Group::gather_data, Group::scatter_data, Group::focus_next).

Turbo Vision heritage: in C++ TGroup::getData/setData walked the same circular sibling ring in forward order; the ring order was insertion order (newest at the front, so a full walk from last->next gives oldest first). The tvision-rs Vec stores oldest at index 0, preserving the same forward walk.

The change-directory dialog

ChDirDialog is a ready-made directory chooser: a path input line with a history recall icon, a collapsible directory tree (DirListBox), and action buttons. Build it with ChDirDialog::new:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(program: &mut tv::Program) {
use tv::dialog::{ChDirDialog, CD_NORMAL};

let mut cd = ChDirDialog::new(CD_NORMAL, 0);
let result = program.exec_view(Box::new(cd));
let _ = result;
}
}

The opts parameter is a bitmask:

ConstantEffect
CD_NORMALStandard dialog, loads the current directory tree on open
CD_NO_LOAD_DIRSkip the initial directory scan (faster first open)
CD_HELP_BUTTONAdd a Help button at the right

The second argument is the history_id (u8) for the path input's recall dropdown. Use a non-zero id to enable history recall, or 0 to skip it (the gallery example uses 0).

When the user navigates the tree and double-clicks a directory (or types a path and presses Chdir), the dialog writes the chosen path into its input field and dismisses with Command::OK. Read the result from the dialog's input:

use tv::dialog::{ChDirDialog, CD_NORMAL};
use tv::data::FieldValue;

let mut cd = ChDirDialog::new(CD_NORMAL, 0);
if program.exec_view(Box::new(cd)) == tv::Command::OK {
    // The path is available after exec_view returns — gather from the child
    // or std::env::current_dir() if ChDirDialog has already changed directories.
    if let Ok(path) = std::env::current_dir() {
        println!("Changed to {}", path.display());
    }
}

The dialog is growable (the WindowFlags::grow flag is set internally) so the user can resize it, and the tree grows with the dialog bounds via GrowMode.

Source: src/dialog/filedlg.rs (ChDirDialog::new, DirListBox, DirCollection).

See also

Third-party components & data interchange

tvision-rs gives your own widgets the same typed data interchange the framework's controls use. C++ Turbo Vision did this with void*/getData; here type safety is kept. There are three open paths, each typed at the layer that owns the type.

1. A modal that returns a value: exec_view_with

A component launched modally returns any native type by value (see Modal execView). The result type is yours; the framework never names it.

2. Field data: FieldValue, including Custom

A control exposes its value as a FieldValue. The well-known shapes (Text/Int/Bool/Bits/List) interoperate with framework widgets and generic consumers. For a payload your component invents, use FieldValue::Custom:

#[derive(Debug, PartialEq)]
pub struct DateRange { pub start: Date, pub end: Date } // export this type!

impl View for DateRangePicker {
    fn value(&self) -> Option<FieldValue> { Some(FieldValue::custom(self.range.clone())) }
}

// the consumer (your code, or anyone who depends on your crate):
let range = fv.value_as::<DateRange>()?;   // loud: a mismatch is a descriptive error

Custom is runtime-checked and fail-loud: value_as::<T>() returns a descriptive Result (a mismatch announces itself at first execution), while as_custom::<T>() returns Option for match-style reads. It is type-safe (a wrong type fails closed and is never misread), but it is not compile-checked across the value() boundary, because the value crosses the object-safe dyn View boundary. The exported payload type is the contract; one test exercising the producer→consumer exchange pins it. (Caveat: TypeId is per-version, so a diamond dependency pulling your crate at two incompatible versions yields distinct types that won't cross. Handle this by dependency discipline.)

A distributable component can offer both a typed Custom(MyType) and a generic scalar/List projection, so consumers who don't depend on your types can still read it. Two of your own tightly-coupled components can skip FieldValue entirely and share a typed Rc<RefCell<MyState>> for full compile-time checking. Custom is only needed for the framework's generic plumbing.

3. Notification: a custom Command broadcast

Command is an open newtype: mint your own and broadcast it (Event::Broadcast) to notify siblings; read the data they then expose via path 2.

Controls

Controls are the leaf views you put inside a dialog or window: buttons, check boxes, radio buttons, input fields, captions, list boxes, and scroll bars. You build them, insert them into a group (a Dialog or Window), and let the event loop drive them. The names follow the tv:: house style with no T prefix. Most map to the Turbo Vision T* class of the same name; the ones Turbo Vision lacks are marked tvision-rs extension and listed on Extensions beyond Turbo Vision.

Buttons

A Button is a clickable command button: a boxed, shadowed title with an optional ~-marked hotkey. Pressing it (mouse, Alt+hotkey, or focused Space) fires its command, either posted as a normal command event or, when the button is flagged broadcast, sent as a broadcast. The default button additionally responds to Enter. A keyboard press does not fire instantly: the button flashes its pressed look for a moment (a short one-shot timer) and then fires, so the click is visible.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::Command;
let bounds = tv::Rect::new(0, 0, 10, 3);
use tv::widgets::{Button, ButtonFlags};
// bounds, title (~ marks the hotkey), command, flags — then insert into the dialog.
let ok = Button::new(bounds, "~O~K", Command::OK, ButtonFlags { default: true, ..Default::default() });
let _ = ok;
}
  File  Edit  Window                    
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]═══════ Buttons ════════════╗░░░░
░░║                                ║░░░░
░░║                                ║░░░░
░░║                                ║░░░░
░░║        OK    ▄      Cancel  ▄  ║░░░░
░░║     ▀▀▀▀▀▀▀▀▀▀     ▀▀▀▀▀▀▀▀▀▀  ║░░░░
░░║                                ║░░░░
░░╚════════════════════════════════╝░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                   

A runnable, captured example of every control on this page (buttons, check boxes, radio buttons, input lines, and more) is in the widget gallery.

Check boxes & radio buttons

These share one engine, the Cluster: a single type that branches on a ClusterKind, wrapped by three named types:

  • CheckBoxes: independent on/off boxes ([X]); any combination may be set.
  • RadioButtons: mutually exclusive options ((•)); exactly one is selected.
  • MultiCheckBoxes: multi-state boxes that cycle through more than two values.

A cluster lays its items out top-to-bottom and wraps into a new column when the height is exceeded; the bounds height is the column-break period. The selected value is read and written through the data protocol like every other control, so a dialog gathers and scatters cluster state automatically.

Input lines

An InputLine is a single-line text field with selection, horizontal scrolling, clipboard cut/copy/paste, and an optional Validator. Its cursor and selection track byte offsets into a real Rust String, so multi-byte and wide text behave correctly.

Read-only fields

tvision-rs extension to TInputLine: not in Turbo Vision. See Extensions beyond Turbo Vision.

set_read_only(true) makes a field refuse every change to its text while leaving it fully navigable. Disabling a field is different: a disabled view is skipped by focus entirely, so a value too wide for its cell can never be scrolled into view, selected, or copied. A read-only field still takes focus, moves its caret, scrolls, select-alls and copies. Only typing, deleting, cutting and pasting are refused.

Each refusal consumes the event and broadcasts InputLine::READ_ONLY_REJECTED with the field's own ViewId as the source, so the owner can tell the user which field would not budge and why. The widget says nothing on its own, because only the owner knows the reason. Cut and paste are also grayed in the command set, so the menu route cannot do what the keyboard route refuses.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo() {
use tv::widgets::{InputLine, LimitMode};

let mut line = InputLine::new(tv::Rect::new(3, 3, 30, 4), 64, None, LimitMode::MaxBytes);
line.set_read_only(true); // reachable and copyable, but not editable
}
}

A read-only field is drawn exactly like an editable one. Signalling the distinction visually is left to the owner, which knows whether "read-only" means server-maintained, computed, or merely not-yet-unlocked.

Which end of a long value shows

tvision-rs extension to TInputLine: not in Turbo Vision. See Extensions beyond Turbo Vision.

A value wider than its field can only show one end of itself. set_value select-alls, so by default the view sits at the tail. This is Turbo Vision's behaviour, and it suits a field whose first keystroke should replace the value. For data whose front identifies it, the operator is left reading …,dc=example,dc=org.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(line: &mut tv::widgets::InputLine) {
use tv::widgets::ValuePosition;

line.set_value_position(ValuePosition::Start); // show the head, caret homed
}
}

This governs set_value only: both the plain text path and the validator-transfer path. Focus behaviour is separate: see set_select_all_on_focus.

Labels & static text

  • StaticText: a read-only, word-wrapped block of text. It is not selectable and only paints.
  • ParamText: a StaticText variant whose content you set at runtime.
  • Label: a single-line caption linked to another control. Clicking the label, or pressing its ~-marked hotkey, focuses the linked control, and the label highlights while that control holds focus. The link is a view handle, not a pointer.

List boxes, scrollers & scroll bars

  • ListBox: a scrollable list of string items. Populate it after inserting it into a group (a Context is needed to publish the scroll range to its bars), then it handles selection and navigation for you. SortedListBox keeps the items ordered.

    tvision-rs extension to TListViewer: incremental find is not in Turbo Vision. See Extensions beyond Turbo Vision.

    Both support an opt-in incremental find via with_find(FindMode): FindMode::Highlight owns the query and highlights the matched substring in every visible row; FindMode::Filter additionally self-filters the list to rows that contain the query (showing No match: <query> when nothing survives). FindMode::Off is the default; the classic type-to-jump lookup is unchanged for existing consumers. While find is active, printable keys (including Space) append to the query, Backspace deletes, and Esc clears (an empty-query Esc still propagates so a host dialog can close). The current query is readable via find_query() and clearable externally via clear_find(). Every query change broadcasts Command::LIST_FIND_CHANGED with the list's own ViewId as source, the same notify-by-broadcast pattern ScrollBar uses, so a host can mirror the query or drive an async search.

  • ScrollBar: a vertical or horizontal bar (orientation inferred from its 1×N or N×1 bounds). It broadcasts a changed message when its value moves, naming itself as the source so a two-bar owner can tell which bar fired.

  • Scroller: the base for scrollable content. It references two sibling scroll bars on the window frame, mirrors their value into its own scroll offset, and pushes range changes back to them. The wiring between a scroller and its bars is brokered by the event loop; see Cross-view brokering.

  • Table: a multi-column list under a click-to-sort header.

    tvision-rs extension: not in Turbo Vision. See Extensions beyond Turbo Vision.

    Rows come from a TableModel and keep a stable RowKey, so focus and the marked rows follow the record through a re-sort or reload. Columns can be resized, moved and hidden with the mouse (column_layout / set_column_layout save the arrangement), and cells of editable columns are edited in place with Enter, F2 or a double-click. See the gallery for the full behaviour.

Validators

A validator gates what an input line accepts. Validator is a trait; an input line holds one as a boxed trait object (the Rust-idiomatic successor to C++ TValidator's abstract base class). With no validator, every keystroke is accepted. The trait has two checkpoints: is_valid_input runs as each character is typed (and may auto-fill or modify the buffer), while is_valid runs the final-form check when the field must be fully valid: on focus-release or when a modal dialog's OK button is pressed.

The concrete validators port the Turbo Vision set, plus RegexValidator:

ValidatorAccepts
FilterValidatoronly characters from a given set
RangeValidatoran integer within [min, max]
PXPictureValidatortext matching a Paradox picture mask
LookupValidator / StringLookupValidatora value from a fixed list
RegexValidatortext matching a regular expression (tvision-rs extension, see Extensions beyond Turbo Vision)

When a final-form check fails, the validator can pop an informational error message box explaining what is wrong, then return focus to the field.

Validating a field

Setting Options::validate (ofValidate) on a control tells the owning group to ask the control whether it is ready to give up focus before moving focus away. The check runs through View::valid with the command Command::RELEASED_FOCUS.

For an InputLine with a validator, this is wired automatically: the input line sets ofValidate for you, and its valid override calls the validator's validate method. If the field is not yet valid, valid returns false, and Group::focus_child refuses the focus transfer and keeps the cursor in the current field.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo() {
use tv::widgets::{InputLine, LimitMode};
use tv::RangeValidator;

// An input line that only accepts integers in [1, 100].
// ofValidate is set automatically because a validator is attached.
let line = InputLine::new(
    tv::Rect::new(3, 3, 20, 4),
    64,
    Some(Box::new(RangeValidator::new(1, 100))),
    LimitMode::MaxBytes,
);
let _ = line;
}
}

The user cannot Tab away or dismiss the dialog with OK until every validated field reports is_valid. Source: src/view/group.rs (Group::focus_child validate gate).

Validating without closing

Validation runs at two moments:

  1. Focus release: valid(Command::RELEASED_FOCUS): only the current (focused) control is asked. The group's valid override for this command delegates to the current child exclusively (src/view/group.rs).
  2. Modal close: valid(cmd) for any other command (for example Command::OK): the group walks all children, calling valid on each and stopping at the first that returns false (a firstThat walk).

You can also call group.valid(Command::OK, ctx) programmatically, from a button handler for instance, to force a full validation pass without closing the dialog. The dialog's own handle_event for Command::OK runs exactly this check before it calls ctx.end_modal(Command::OK).

Source: src/view/group.rs (Group::valid), src/dialog/dialog.rs (Dialog::handle_event OK branch).

Turbo Vision heritage: TGroup::valid had the same two arms: one for cmReleasedFocus (current only) and one for all other commands (all children). tvision-rs ports both behaviors verbatim.

When validation fails

When Validator::is_valid returns false, the validator's error method is called. This is where the user sees an informational message box explaining what is wrong.

A leaf view cannot run a modal dialog inline: it holds only &mut Context, never the Program. Instead, error requests the message box through the async-modal seam: Context::request_message_box queues a Deferred::RequestMessageBox entry; the event loop builds and runs the dialog at the end of the current pump tick. The call parameters include an optional answer_to: Option<ViewId> and then_command: Option<Command>. When these are None (the validator error case), the message box is informational only: the user clicks OK, the box closes, and focus returns to the invalid field. No round-trip answer is needed.

Here is how a concrete validator implements error (from src/validate.rs, FilterValidator::error):

fn error(&self, ctx: &mut Context) {
    ctx.request_message_box(
        "Invalid character in input".to_string(),
        tvision_rs::dialog::MessageBoxKind::Error,
        tvision_rs::dialog::MessageBoxButtons::ok(),
        None,  // answer_to — no round-trip needed
        None,  // then_command
    );
}

When you write a custom validator, override both is_valid and error:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::validate::Validator;
use tv::view::Context;

struct NoSpaceValidator;

impl Validator for NoSpaceValidator {
    fn is_valid(&self, s: &str) -> bool {
        !s.contains(' ')
    }

    fn error(&self, ctx: &mut Context) {
        ctx.request_message_box(
            "Spaces are not allowed.".to_string(),
            tv::dialog::MessageBoxKind::Error,
            tv::dialog::MessageBoxButtons::ok(),
            None,
            None,
        );
    }
}
}

The provided validate method calls is_valid and then error for you; override is_valid and error instead of validate itself.

Source: src/validate.rs (Validator::error, FilterValidator::error), src/view/context.rs (Context::request_message_box).

History lists

A THistory dropdown icon lets users recall previous entries for an input field. It pairs with a u8 channel id (the history_id) that identifies which history list the icon reads and writes.

Place the icon immediately to the right of the input line (it is 3 cells wide: ▐↓▌) and pass the input's ViewId and the channel id:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(dialog: &mut tv::Dialog) {
use tv::widgets::{InputLine, THistory, LimitMode};

// Insert the input line first to get its ViewId.
let input_id = dialog.insert_child(Box::new(
    InputLine::new(tv::Rect::new(3, 3, 30, 4), 64, None, LimitMode::MaxBytes)
));

// Place the recall icon immediately to the right.
let _hist_id = dialog.insert_child(Box::new(
    THistory::new(tv::Rect::new(30, 3, 33, 4), input_id, 42)
));
}
}

The channel id 42 (any u8) is the key for the global history store. When the user confirms an entry in the field (the input's value is saved on dialog OK), call history_add(id, text) to push the string into the store. On the next open, the ↓ button pops a scrollable recall list sorted newest-first; picking an entry writes it back into the linked input.

The store is process-global and byte-budgeted (default 1024 bytes across all channels). The oldest entries across all channels are evicted when the budget is exceeded. Access the store directly with history_str(id, index) and history_count(id) when you need to pre-populate or audit entries.

The icon is not selectable (clicking it does not steal focus from the linked input), and it opts into post-processing so it sees key events after the focused input, leaving the ↓ arrow key available as a keyboard trigger.

Source: src/widgets/history.rs (THistory, HistoryViewer, HistoryWindow, history_add, history_str, history_count).

Turbo Vision heritage: THistory / THistoryViewer / THistoryWindow port one-to-one. The global byte store (histlist.cpp) is reimplemented as a thread-local Vec<HistRec>, dropping the original front-sentinel bookkeeping for a simpler read contract.

Where to go next

Menus, status line & help

The top menu bar, the bottom status line, and the context-sensitive help that ties them together are the chrome of every Turbo Vision program. In tvision-rs all three are data trees you describe with fluent builders, then hand to a view. The data lives in tv::menu and tv::status; the help context is HelpCtx.

The menu bar

A menu is a Menu: an ordered list of entries plus a default selection. You rarely build one by hand; instead you chain a MenuBuilder, a fluent builder where each call appends one MenuItem and returns self (the idiomatic successor to C++'s operator+ chains):

let menu = Menu::builder()
    .submenu("~F~ile", alt('f'), |m| {
        m.command_key("~O~pen…", CMD_OPEN, KeyEvent::from(Key::F(3)), "F3")
            .command_key("~N~ew", CMD_NEW, KeyEvent::from(Key::F(4)), "F4")
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
    })
    .submenu("~W~indow", alt('w'), |m| {
        m.command("~T~ile", Command::TILE)
            .command("C~a~scade", Command::CASCADE)
    })
    .build();

Notes on the example:

  • ~-marked labels. The tildes bracket the hot-letter ("~F~ile" highlights the F). Submenus take an alt() accelerator, a convenience that builds an Alt+<char> key.
  • Three entry kinds. command / command_key append a MenuItem::Command (the latter adds an accelerator key plus the shortcut text shown at the right, like "F3"); submenu appends a nested menu; separator appends a divider.
  • A menu is data. Choosing an item emits its Command as an event; the menu never does anything itself. See Commands & events for how that command reaches a handler, and for how a greyed-out (disabled) item is driven by command enable/disable state.

Turbo Vision heritage: command/command_key, submenu, and separator map one-to-one onto C++ TMenuItem, TSubMenu, and newLine(); the ~-marked hot-letters and alt() accelerators mirror the C++ "~F~ile" label convention and kbAltF literals.

Wrap the finished Menu in a MenuBar and return it from your init_menu_bar factory. F10 enters the bar; the Alt accelerators open submenus directly. When a window is in Fullscreen::Screen mode the framework calls MenuBar::set_collapsed(true), which replaces the full bar with a [⋮] kebab at the top-right corner; pressing F10 (or clicking the kebab) opens the full menu as a corner popup. With the File menu pulled down it looks like this:

  File  Edit  Window                                    
 ┌─────────────┐ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 │ Open…    F3 │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 │ New      F4 │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 │ Recent    ► │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 ├ ┌────────────┐ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 │ │ report.txt │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 └ │ budget.csv │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░ │ notes.md   │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░ └────────────┘ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                   

The complete factory is in examples/hello.rs (see Your first app); the runnable menu/status sources are the menubar and statusline entries in the widget gallery.

The status line

A status line is a Vec<StatusDef>: a list of definitions, each owning a list of StatusItems, built with StatusDef::list():

let defs = StatusDef::list()
    .def_all(|d| {
        d.item("~F3~ Open", KeyEvent::from(Key::F(3)), CMD_OPEN)
            .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
            .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
    })
    .build();

Each item carries display text, an optional accelerator key, and a command; clicking the label or pressing the key fires that command. Hand the defs to a StatusLine and return it from your init_status_line factory.

A hidden hotkey binding is an item with no text, built with the key_item builder method. It draws nothing and consumes no width, but its accelerator still fires globally. This is the standard trick for app-wide shortcuts like Shift-Del ⇒ Cut (the C++ equivalent was TStatusItem(0, key, cmd)).

Context-sensitive help

This is what a multiple-StatusDef list is for. Each def carries a HelpCtxRange; the status line shows the items of the first def whose range matches the current help context. Most apps need only one universal def, which is what def_all (HelpCtxRange::All) builds, but you can register a def_one_of(...) whose items appear only while a particular context is active, so the bottom line changes as focus moves between an editor, a browser, and so on.

The current context is a HelpCtx. A help context is a namespaced &'static str (HelpCtx::custom("myapp.editor")), so app- and view-defined contexts can never collide. Because string identity carries no ordering, context ranges are expressed as the two-variant HelpCtxRange above: All, or an explicit OneOf membership set. Menu items also carry a help_ctx, so the same identity threads through the whole UI.

Turbo Vision heritage: the C++ HelpCtx was a hand-assigned int, and ranges were [min, max] numeric intervals. tvision-rs replaces the integer with a &'static str key and the numeric range with HelpCtxRange.

Context-sensitive hints

Beyond switching which status-line items appear, the status line can show a free-form hint string to the right of the items: a short message that changes as the focused view changes context. This is the hint provider.

By default no hint is shown (None). Install one with StatusLine::with_hint (builder) or StatusLine::set_hint (post-construction). The provider is a closure Fn(HelpCtx) -> Option<String>; it receives the current help context and returns the text to show (or None to show nothing):

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::help::HelpCtx;
use tv::status::{StatusDef, StatusLine};
use tv::Rect;
#[allow(unused_variables)]
fn _demo() {
let defs = StatusDef::list()
    .def_all(|d| d)
    .build();

let line = StatusLine::new(Rect::new(0, 23, 80, 24), defs)
    .with_hint(|ctx| match ctx {
        c if c == HelpCtx::custom("myapp.editor") =>
            Some("F2 Save  F3 Open  Ctrl-F Find".to_string()),
        c if c == HelpCtx::custom("myapp.browser") =>
            Some("Enter Select  Esc Back  F5 Refresh".to_string()),
        _ => None,
    });
let _ = line;
}
}

The Program idle loop reads the focused view's help_ctx from its ViewState and calls StatusLine::set_help_ctx at the start of each pump, so the hint updates as the user moves focus. The status line re-draws itself when the context changes (it skips the redraw if the context has not changed, making it idempotent).

Combining defs with hints: the two mechanisms are independent. Defs swap the entire item list; the hint overlays a text string at the right end of the line. Use def_one_of when you want different command buttons per context; use with_hint for a short advisory string that supplements a shared button set.

Source: src/status/status_line.rs (StatusLine::set_hint, StatusLine::with_hint, StatusLine::set_help_ctx), src/status/mod.rs (HelpCtxRange, StatusDef).

See also

Commands & events

The things that happen in your app (clicking OK, choosing a menu item, a scrollbar moving) travel through the view tree as commands and events. A button does not call a function directly. It emits a command, and some view up the tree decides what to do with it. Because of this indirection the same Command::OK can come from a button, a menu, or a keystroke and be handled in exactly one place.

Commands

A Command is an opaque token naming an intent. The framework ships a standard vocabulary as associated constants: Command::OK, Command::CANCEL, Command::QUIT, Command::CLOSE, and so on. A command's identity is a namespaced &'static str (so Command::OK is "tv.ok"), which keeps app- and view-defined commands from colliding (the standard names map one-to-one onto the C++ cm* constants). Mint your own with Command::custom, under a dotted prefix of your own:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
const REFRESH: tv::Command = tv::Command::custom("myapp.refresh");
}

Commands reach the tree as events. A view emits one through its Context:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
const REFRESH: tv::Command = tv::Command::custom("myapp.refresh");
fn _demo(ctx: &mut tv::Context) {
// a targeted command, like cmXxx — handled by one view up the tree
ctx.post(REFRESH);
}
}

The command then rides the event loop as an Event::Command, is offered to views in turn, and the first one to recognise it consumes it. (How the loop walks the tree is the subject of The event loop in depth.)

Enabling & graying out

Every command is enabled by default. To make a command unavailable, which grays out the menu items and buttons that emit it, disable it. When you hold the top-level handle (an app main, startup, a test), call Program::disable_command / enable_command. From inside a view, where you only have a downward-borrowed Context, request it deferred via ctx.disable_command(cmd) / ctx.enable_command(cmd). A view can ask whether a command is currently live with ctx.command_enabled(cmd), which answers from a per-pump snapshot.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(app: &mut tv::Program) {
app.disable_command(tv::Command::SAVE);   // Save menu item / button grays out
// ...later, once there is something to save:
app.enable_command(tv::Command::SAVE);
}
}

Internally Program stores the disabled set (a denylist), so a brand-new custom command is enabled the moment it exists, with no registration step. Five window commands (ZOOM, CLOSE, RESIZE, NEXT, PREV) start disabled and are granted only while a window is selected. The disabled command set is a CommandSet, a set of commands with += / -= / union / intersection operators (the successor to C++ TCommandSet).

When the enabled set changes, the framework broadcasts Command::COMMAND_SET_CHANGED once on the next idle so menus, buttons and the status line re-evaluate which of their commands are live and redraw themselves grayed or active.

Broadcasts

A targeted command goes to whoever handles it; a broadcast is offered to every interested view. Sibling views coordinate through broadcasts: a scrollbar tells its scroller it moved, a list tells its dialog an item was chosen. Emit one through the context:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(ctx: &mut tv::Context, my_id: tv::ViewId) {
ctx.broadcast(tv::Command::SCROLL_BAR_CHANGED, Some(my_id));
}
}

A broadcast is an Event::Broadcast { command, source }. The source is an optional ViewId naming which view the broadcast is about. It is the resolvable successor to C++'s infoPtr void-pointer, and a receiver uses it as a filter: it checks "is this broadcast from the scrollbar I care about?" and ignores the rest. It carries no payload. None means the broadcast concerns no particular view. List find-mode uses the same pattern: a list box broadcasts Command::LIST_FIND_CHANGED with its own ViewId as source whenever the typed query changes, so a host can mirror the query or kick off an async search. Because a leaf view cannot reach across the tree to its sibling, the event loop itself brokers the read/write between the two views when it applies the broadcast; see Cross-view brokering & ViewId.

Where to go next

Keyboard & key mapping

When a key is pressed, it reaches your views as a key-down event; text widgets turn that keystroke into an editing command through a keymap. This page covers both halves: the key model your Views see, and the configurable Keymap that drives the editor and input line.

The key model

A keystroke is a physical Key plus a separate KeyModifiers channel, bundled into a KeyEvent. There are no modifier-combined variants: keys and modifiers are always separate. Ctrl+C is Key::Char('c') with ctrl set; Shift+Tab is Key::Tab with shift; Alt+F3 is Key::F(3) with alt. The enum holds only base keys: characters, function keys, and the navigation/editing keys (Enter, Tab, arrows, Home, PageUp, Insert, Delete, …). The three logical modifiers shift, ctrl, and alt collapse the platform's left/right distinctions (mirroring the C++ kb*Shift masks).

Two helpers bridge the old DOS conventions into this model:

  • ctrl_to_arrow maps the WordStar Ctrl-letter diamond (Ctrl+S/D/E/X and friends) to the equivalent arrow and navigation keys, clearing all modifiers on a match and passing everything else through unchanged. It is a faithful port of ctrlToArrow.
  • hot_key extracts the ~-delimited accelerator character from a label (uppercased), so a button or menu item knows which Alt+ chord activates it.

The keymap

tvision-rs extension: not in Turbo Vision. See Extensions beyond Turbo Vision.

Text input does not hard-wire keys to editing actions. Instead a Keymap maps a chord to a Command by name, in the same data-driven shape as a VS Code keybindings file. A chord is one keystroke, or two for a prefix sequence in the classic Ctrl-K/Ctrl-Q editor style. You describe chords as strings: space-separated strokes, each a +-joined list of modifiers ending in a key name.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
let mut km = tv::keymap::Keymap::new();
km.bind("ctrl+s", tv::Command::CHAR_LEFT)        // single stroke
  .bind("ctrl+k ctrl+c", tv::Command::COPY)      // two-stroke prefix chord
  .bind("shift+insert", tv::Command::PASTE);     // shift kept where it matters
km.unbind("ctrl+s");
}

Keystrokes are normalized before lookup so the presets stay small and the historic behaviours survive. Alphabetic characters lowercase and drop shift (ctrl+q a equals ctrl+q A), and the cursor-pad keys drop shift too, since Shift+Left is a selection modifier handled inside the widget and has no binding of its own. Keys where shift carries meaning, such as Shift+Insert for paste, keep it.

Resolving a stroke (optionally combined with a pending prefix) yields a Resolve: a fully matched Command, a Prefix signal meaning "this begins a two-stroke chord, hold the next key", or None so the caller treats the key as insertable text or lets it bubble.

Presets and the global keymap

Three ready-made keymaps ship as constructors:

PresetConstructorFeel
WordStarKeymap::word_star()the classic editor diamond + Ctrl-K/Ctrl-Q blocks
CUA / OfficeKeymap::cua()modern Ctrl+C/X/V/Z muscle memory
EmacsKeymap::emacs()readline/Cocoa bindings (Ctrl+A/E/K/Y)

There is one process-global keymap, the default for all text input; it starts as word_star(). Swap it once at startup with set_global, and the editor and every input field follow:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
tv::keymap::set_global(tv::keymap::Keymap::cua());
}

Widgets consult it via resolve_global. You rarely call that yourself; a custom text view calls it to join the same binding scheme.

Where to go next

  • Commands & events: what those resolved Commands do once a view consumes them.
  • Text editing: the Memo, Editor and input-line widgets the keymap drives.
  • Events → enum + match: the design behind the decomposed Key/KeyModifiers model, for Turbo Vision veterans.

Theming & colors

In tvision-rs, colors come from a single central, swappable table: a typed map from a semantic Role to a Style. No widget hard-codes a color; every draw() asks for a role, and the active theme resolves it. One call swaps the whole palette. The narrative behind the design is in Palettes & glyphs.

Turbo Vision heritage: the C++ framework used a chain of per-widget palette index strings that bottomed out in one-byte BIOS attributes. tvision-rs keeps the central-swappable-table idea but replaces the index arithmetic and the palette-chain traversal with a typed Role → Style map.

The three types

TypeWhat it is
ColorA desired color: terminal Default, 4-bit Bios, 256-color Indexed, or 24-bit Rgb.
StyleA foreground Color, a background Color, and a Modifiers struct-of-bools (bold, italic, underline, blink, reverse, strike).
ThemeThe whole palette: a Role → Style map plus a Glyphs holder for the box-drawing and marker characters.

A Role is a semantic slot such as FrameActive, ButtonDefault, MenuSelected or Error. Widgets ask for roles and never for raw colors, so one theme drives every control. The enum is closed and first-party: it grows as new widgets are ported, but applications do not add their own roles.

The default theme

The framework starts on Theme::classic_blue, the canonical Turbo Vision blue look and the value behind Theme::default. Each role resolves to a definite true-color RGB via Color::bios_rgb, so contrast is correct regardless of how the terminal has remapped its own 16-color palette. The source carries the full per-role derivation inline (each value is anchored to the corresponding entry in the classic C++ palette chain).

Reading a theme color

If you are writing a custom View, you do not touch the Theme directly; the draw context hands you the resolved style. Inside draw() you have a DrawCtx; ask it for the style of a role and paint with it:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
struct MyWidget;
impl MyWidget {
fn draw(&self, ctx: &mut tv::DrawCtx) {
    let style = ctx.style(tv::Role::Normal);
    ctx.put_str(0, 0, "hello", style);
}
}
}

ctx.style(role) is a thin pass-through to Theme::style, so it is total and never panics: every role always resolves. Box-drawing and marker characters come from ctx.glyphs() the same way. See Writing your own View for the full draw path.

Overriding colors

Re-theming is a whole-theme swap. Take the default, override the roles you care about with set_style, and install it on the running program with Program::set_theme, which forces a full repaint:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(program: &mut tv::Program) {
let mut theme = tv::Theme::classic_blue();
theme.set_style(
    tv::Role::Background,
    tv::Style::new(tv::Color::Rgb(20, 20, 30), tv::Color::Default),
);
program.set_theme(theme);
}
}

You can also build a Style with attributes via Style::with_modifiers, or flip foreground and background with reversed. It swaps concrete colors but toggles the reverse flag when one side is Default, matching Turbo Vision's reverseAttribute.

The theme editor

tvision-rs extension: not in Turbo Vision. See Extensions beyond Turbo Vision.

For an interactive way to tweak roles at runtime, the program ships a built-in theme-editor dialog (Program::theme_editor): it opens an editor seeded with the current theme and, on OK, installs the result through set_theme.

See also

Text editing

tvision-rs ships a multi-line text editor and a scrolling terminal view, both ported faithfully from Turbo Vision. They build on one engine, Editor (TEditor): a gap-buffer text editor with a cursor, a selection, single-level undo, word-by-word navigation, and substring search. You rarely embed Editor directly; you use one of the three faces it wears.

Three faces of the editor

TypeUse it for
Memo (TMemo)a multi-line edit field inside a dialog
FileEditor (TFileEditor)an editor backed by a file on disk
EditWindow (TEditWindow)a ready-made window wrapping a FileEditor plus its scrollbars and indicator

Memo is a thin wrapper over Editor that does two extra things: it lets a plain Tab fall through to the dialog's focus navigation (instead of inserting a tab), and it exposes its text as a typed FieldValue so dialog gather/scatter works as for any other control.

EditWindow is the one to start from for an editor application. Its constructor inserts the (initially hidden) horizontal and vertical scrollbars and the line/column indicator, wires a FileEditor to them, and titles the window after the file (or "Untitled"):

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::widgets::EditWindow;
fn _demo(desktop: &mut tv::Group) {
let bounds = tv::Rect::new(0, 0, 80, 24);
let path = std::path::PathBuf::from("my_file.txt");
let window_number: i16 = 1;
let win = EditWindow::new(bounds, Some(path), window_number);
desktop.insert(Box::new(win));
}
}

Files: loading, saving, and the modified prompt

FileEditor loads its file in the constructor when you pass a path; a None path is an untitled buffer. It handles Command::SAVE itself, opens a Save-as file dialog for an untitled buffer or Command::SAVE_AS, and, through its valid check, puts up the classic "… has been modified. Save?" Yes/No/Cancel prompt before a dirty buffer is closed. All of that runs through tvision-rs's deferred message-box and file-dialog seams, so a single editor view can drive a modal dialog without owning the event loop (see Deferred effects).

Backup files are off by default; when enabled, tvision-rs appends ~ to the filename (foo.txt → foo.txt~), following Unix convention instead of the DOS .bak rename.

Line endings and encoding

Two settings control how text is stored and stepped over:

  • LineEnding: Lf, CrLf, or Cr, deciding the byte sequence written for each line break when text is inserted. tvision-rs defaults to Lf (the modern-host default; DOS Turbo Vision defaulted to CrLf).
  • Encoding: Default steps over characters using width-aware (grapheme) logic, so multi-byte UTF-8 and wide glyphs advance the cursor correctly; SingleByte treats every byte as one column.

The terminal view

Terminal (TTerminal) is the other text view: a scrolling, ring-buffered output pane that you write into. It implements the TextDevice trait, so you append output by calling write_bytes; the most recent lines that fit are drawn, and the embedded scroller keeps its scrollbars in sync. There is no stream wrapper, only the byte sink (the C++ streambuf/otstream layer is not ported).

Because its constructor cannot touch the screen, Terminal follows the deferred-init pattern: build it, insert it into a group, then call init once to set up its limits and cursor.

Edit commands enable themselves

The editor tracks which editing commands make sense for the current state and enables or disables them on every state change, including when the window gains or loses focus. The update_commands method (src/widgets/editor.rs) runs after every edit and on focus change:

CommandEnabled when
Command::UNDOundo history is non-empty (`del_count > 0
Command::CUTthere is a selection
Command::COPYthere is a selection
Command::PASTEno clipboard editor active, or clipboard has a selection
Command::CLEARthere is a selection
Command::FINDalways (while the editor is focused)
Command::REPLACEalways
Command::SEARCH_AGAINalways
Command::SAVE / SAVE_ASalways, for a FileEditor

The enable/disable changes go through the deferred channel (ctx.enable_command / ctx.disable_command), so they apply after the current dispatch. A menu that depends on these commands automatically grays or un-grays its items at the next pump because the menu's draw reads the current command-set snapshot.

The clipboard editor (is_clipboard: true) skips cut/copy/paste updates. It is a special internal editor used for the clipboard window, which should not compete with the main editor for those commands.

Source: src/widgets/editor.rs (Editor::update_commands, Editor::set_state).

Key bindings

tvision-rs extension: the configurable keymap is not in Turbo Vision. See Extensions beyond Turbo Vision.

The editor resolves keystrokes through the process-global Keymap (src/keymap.rs). The keymap maps one- or two-stroke chords to Command values. Three preset keymaps ship with the crate:

PresetDefault?Style
Keymap::word_star()yesWordStar / Ctrl-letter diamond + Ctrl-K/Ctrl-Q block prefixes
Keymap::cua()noCUA / "Office" (Ctrl-C copy, Ctrl-V paste, Ctrl-Z undo)
Keymap::emacs()noEmacs / readline (Ctrl-A line-start, Ctrl-E line-end, …)

The WordStar preset mirrors the C++ editor's firstKeys / quickKeys / blockKeys tables faithfully:

  • Single-stroke firstKeys: the Ctrl-letter diamond: Ctrl-S left, Ctrl-D right, Ctrl-E up, Ctrl-X down, etc., plus named keys (Left, Right, Home, End, PageUp, PageDown).
  • Ctrl-Q prefix (quickKeys): Ctrl-Q F find, Ctrl-Q A replace, Ctrl-Q S line-start, Ctrl-Q D line-end, …
  • Ctrl-K prefix (blockKeys): Ctrl-K B start-select, Ctrl-K K copy, Ctrl-K C paste, Ctrl-K Y cut, Ctrl-K H hide-select.

Replace the keymap process-globally with keymap::set_global:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::keymap::{Keymap, set_global};

// Switch the whole application to CUA bindings.
set_global(Keymap::cua());
}

Or build a custom map from scratch:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::keymap::{Keymap, set_global};
use tv::Command;

let mut km = Keymap::word_star();   // start from the WordStar base
km.bind("ctrl+z", Command::UNDO);   // add a CUA undo chord
set_global(km);
}

The two-stroke prefix (Ctrl-K, Ctrl-Q) works through the Keymap::resolve API: when resolve(None, stroke) returns Resolve::Prefix, the editor holds the first stroke as pending; the next keystroke is resolved as resolve(Some(prefix), stroke).

Source: src/keymap.rs.

Turbo Vision heritage: the C++ editor maintained a key_state machine and three hard-coded tables (firstKeys, quickKeys, blockKeys). tvision-rs replaces them with a data-driven Keymap; the word_star() preset is a direct transcription of those tables.

Search and replace

The editor handles Command::FIND, Command::REPLACE, and Command::SEARCH_AGAIN:

  • FIND: requests a find dialog from the loop via Context::open_find_dialog(editor_id). The loop builds the dialog (pre-filled with the editor's last search string), runs it, and on OK re-injects a SEARCH_AGAIN command targeting the editor.
  • REPLACE: same flow with a replace dialog that also has a replacement string field and option checkboxes.
  • SEARCH_AGAIN: calls do_search_replace, which runs the actual search using the stored find_str, replace_str, and editor_flags (EF_DO_REPLACE, EF_REPLACE_ALL, EF_PROMPT_ON_REPLACE).

The prompt-on-replace path is asynchronous: when the "prompt on replace" option is checked, each found occurrence triggers a request_message_box (Yes / No / Cancel). The editor caches the answer in pending_replace_answer via set_modal_answer, then the loop re-injects SEARCH_AGAIN. On the next dispatch the editor reads the cached answer before searching for the next occurrence: "Yes" replaces and continues, "No" skips and continues, "Cancel" aborts the whole loop.

The loop option EF_REPLACE_ALL skips the per-occurrence prompt and replaces every match in a tight loop; EF_DO_REPLACE distinguishes replace from find-only.

Source: src/widgets/editor.rs (do_search_replace, Command::FIND / REPLACE arms in handle_event, pending_replace_answer).

Turbo Vision heritage: TEditor used a synchronous nested event loop for the search dialogs. tvision-rs routes both the dialog result and the prompt-on-replace answer through the deferred/async-modal seam, keeping the single event loop intact.

Editor as a dialog control (Memo)

Memo is a thin wrapper over Editor that turns it into a dialog control:

  1. Tab pass-through: a plain (unmodified) Tab keystroke is not consumed by the editor; it falls through to the dialog's focus navigation. Shift-Tab, Ctrl-Tab, and Alt-Tab are forwarded to the editor as normal (those bindings have in-editor meaning or are editor-application-specific).
  2. FieldValue transfer: Memo::value() returns FieldValue::Text(contents) and Memo::set_value(FieldValue::Text(s)) loads text into the buffer. This makes Memo transparent to the dialog's gather/scatter walk.
#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(dialog: &mut tv::Dialog) {
use tv::widgets::Memo;

let memo_id = dialog.insert_child(Box::new(
    Memo::new(
        tv::Rect::new(3, 3, 37, 10),
        None, // h_scroll_bar
        None, // v_scroll_bar
        None, // indicator
        4096, // buffer size in bytes
    )
));
let _ = memo_id;
}
}

After exec_view returns Command::OK, gather the memo's text through the dialog's child value (index in the gather Vec matches insertion order):

use tvision_rs::data::FieldValue;
let values = dialog.gather_data(); // Vec<Option<FieldValue>>
if let Some(Some(FieldValue::Text(text))) = values.first() {
    // text is the memo's current content
    println!("memo: {}", text);
}

Source: src/widgets/editor.rs (Memo::handle_event, Memo::value, Memo::set_value), src/data.rs (FieldValue::Text).

Where to go next

Common app patterns

Short answers to questions that come up when a first real application is built on tvision-rs. Each section links to the page or API entry with the full story.

Is my view the one receiving keys?

A view receives keyboard input when it is focused: State::focused is true when the view is the current (selected) child of its owner and every owner up to the root is focused too. Group::set_state sends the Focused flag down the chain of current children only, so in a window with two list panes exactly one of them has focused == true. While a modal dialog is open, the dialog is the current child of the root, so every view on the desktop reads focused == false.

To show which pane is active, read the flag in draw; there is nothing to track yourself:

fn draw(&mut self, ctx: &mut DrawCtx) {
    let active = self.state().state.focused;
    let role = if active { Role::ListFocused } else { Role::ListNormal };
    // ... draw the title / cursor row with `role`
}

A wrapper built with #[delegate(to = inner)] has exactly one ViewState, the inner one. Read the flag through self.state(), never from a second copy; see Wrapping an existing view.

Reacting to a terminal resize

There is no resize event and no resize command. On every pass of the loop the pump compares the backend size with the root size; when they differ it calls change_bounds on the root group. Group::change_bounds then calls calc_bounds and change_bounds on each child, so the new size cascades down the tree under each child's grow mode.

To lay out children by hand after any resize, override View::change_bounds (the C++ changeBounds override). Splitter does this:

#[delegate(to = group)]
impl View for TwoPanes {
    fn change_bounds(&mut self, bounds: Rect) {
        self.group.change_bounds(bounds); // grow-mode cascade to the children
        self.place_panes();               // then move panes with group.child_mut(id)
    }
}

View::on_bounds_changed is the second half of a resize. Every resize path (a window drag or Context::request_bounds, zoom, tile and cascade, a moved splitter divider, a terminal resize) ends with this call on the view it re-bounded, and a Group whose size changed forwards it to every child, so it reaches views at any depth. It gets a Context, so use it for work that needs one, such as publishing new scroll-bar limits; Scroller and the list viewers do this. Do the layout itself in change_bounds, which runs first.

The cursor of an embedded terminal or custom view

The hardware cursor is shown for one view only: the focused view at the end of the current chain, and only when its State::cursor_vis is set. View::cursor_request implements this test, and the pump places the cursor from it on every pass before the redraw (the TView::resetCursor port).

A view that hosts a terminal emulator copies the emulator cursor into its own ViewState each time the emulator state changes, in view-local coordinates:

let (x, y, visible) = self.emu.cursor();
let st = self.state_mut();
st.set_cursor(x, y);
if visible { st.show_cursor() } else { st.hide_cursor() }

When the view loses focus the cursor disappears, and it comes back when focus returns. This is intended: one cursor exists on the screen, and it belongs to the view that receives the keys. Keep the position inside the view's size: the pump hides a cursor that lies outside the view, outside an owner on the chain, past the screen edge, or under another window.

The status line follows the focused view. On each idle pass the pump reads the help context and hands it to the status line, which then shows the first StatusDef whose range matches. An open menu supplies the context first; else, with a modal open, the context comes from the modal; otherwise from the root. In both cases Group::get_help_ctx returns the focused child's context and falls back to the group's own when the child has HelpCtx::NO_CONTEXT. Give a dialog a context by setting state_mut().help_ctx on the dialog or on one of its controls.

Status-line keys are routed before any view sees them, also while a modal is open. When a key matches an item of the current def (including hidden key_item bindings) and its command is enabled, the status line turns the key event into that command. The focused view never receives the key.

While a modal runs, a command (from a status-line key, a button or put_event) goes to the modal alone, as in C++ TGroup::execute. A command the modal does not handle is dropped: the program-level command handler (for example run_app's) does not see it. So ~F1~ Help, or the Help button of a file dialog, does nothing under a modal unless the dialog handles Command::HELP itself. To add that, embed the dialog in your own view type (#[delegate(to = dialog)]) and handle the command in its handle_event.

let defs = StatusDef::list()
    .def_one_of([HelpCtx::custom("app.containers")], |d| {
        d.item("~Del~ Remove", KeyEvent::from(Key::Delete), CMD_REMOVE)
    })
    .def_all(|d| d.item("~Alt-X~ Exit", alt('x'), Command::QUIT))
    .build();

An app-wide def must therefore not bind keys that dialogs and editors need, such as Enter, Esc, Tab or Del: an input line would never see Del. Put such bindings in a def that matches only the help context of the view that owns them, as above. The keymap is different: it is read only by the editor and the input line to map keys to editing commands, and does not route keys for the app. See Menus, status line & help.

Getting results out of a modal

From application code that holds &mut Program, use Program::exec_view_with: its closure reads the result from the modal before the modal is dropped.

From inside a view, which only has &mut Context, call ctx.request_exec_view(dialog, my_id, Some(CMD_DONE)). When the modal closes, the pump calls three things on the requesting view, in this order: it gives the dialog's gathered record to set_modal_data (skipped when the close command is Command::CANCEL), gives the close command to set_modal_answer, and posts CMD_DONE. The two hooks have no Context, so store what they receive and act when CMD_DONE arrives in handle_event:

fn set_modal_data(&mut self, data: FieldValue) {
    if let FieldValue::List(fields) = data
        && let Some(FieldValue::Text(name)) = fields.into_iter().next()
    {
        self.pending_name = Some(name); // used when CMD_DONE arrives
    }
}

Full details: Modal execView → one loop and The data-movement model.

Feeding async results into the UI

Two hooks exist. Both run only on idle passes, which are passes with no input event. With no input they come about every 20 ms, sooner when a timer is due.

  • Program::set_on_idle holds one callback with &mut Program. It also runs while a modal is open. The callback can update shared state (Rc<RefCell<_>>) that views read in draw; the next redraw shows the change. To make views react, it queues an event with Program::broadcast(REFRESH, None) or Program::put_event(ev). The event is delivered on the next pump pass, not inside the callback. Queue it only when new data arrived, not on every pass. Use broadcast for refreshes: a broadcast reaches the whole tree also under a modal, but a command or key queued with put_event while a modal is open reaches only the modal and is dropped if the modal does not handle it.
  • A view-owned periodic timer: Context::set_timer with a period. Each expiry arrives as Event::Timer(id) and is delivered to every view in the tree like a broadcast, also while a modal is open, a window or a column is dragged, or a menu is open. The view can drain a channel and call ctx.broadcast(REFRESH, None) so other views update themselves. The timer is not tied to its view: call ctx.kill_timer(id) when the work ends.

Use the idle hook when the program owns the data source; use the timer when a view owns it. The external_state example shows the timer pattern end to end; see also Background work each idle pass.

Mouse double-click

The loop marks a mouse press as a double or triple click when the same buttons are pressed on the same cell within the double-click interval. Read the flags in the MouseDown handler:

Event::MouseDown(m) if m.flags.double_click => {
    self.open_selected(ctx);
    ev.clear();
}

MouseEventFlags also has triple_click. The interval is 440 ms by default; change it with Program::set_double_delay_ms.

The Program::new factories

Program::new takes three factories, each an impl FnOnce(Rect) -> Option<Box<dyn View>>, for the desktop, the status line and the menu bar. Each one runs once, inside Program::new, and receives the full screen rectangle; it shrinks the rectangle to its own row or area. Return None to leave out the status line or the menu bar. Because the factories are FnOnce, they can move app handles in:

let program = Program::new(
    backend,
    Box::new(SystemClock::new()),
    Theme::classic_blue(),
    move |r| init_desktop(r, state.clone(), rx), // moves the Receiver in
    init_status_line,
    init_menu_bar,
);

After construction, Program::desktop, status_line and menu_bar return the ViewId of each part. See The application skeleton and examples/external_state.rs.

Widget gallery

Every widget tvision-rs draws, shown running with the code that builds it. Each screenshot is the real terminal output of the gallery example, captured live. Each code block is the builder fn the screenshot was made from, included verbatim from the compiled example.

Run any of these yourself:

$ cargo run --example gallery -- <name>     # e.g. button, listbox, filedialog
$ cargo run --example gallery               # list every name

Each builder returns a Box<dyn View> (or a Menu / status definition); the example wraps it in a desktop with a menu bar and status line and runs the real event loop. See Controls, Dialogs & data, and Menus, status line & help for the concepts behind them.

Buttons & selection

Button

A clickable command button. The ~ marks the hot-letter; default: true makes Enter fire it.

  File  Edit  Window                    
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]═══════ Buttons ════════════╗░░░░
░░║                                ║░░░░
░░║                                ║░░░░
░░║                                ║░░░░
░░║        OK    ▄      Cancel  ▄  ║░░░░
░░║     ▀▀▀▀▀▀▀▀▀▀     ▀▀▀▀▀▀▀▀▀▀  ║░░░░
░░║                                ║░░░░
░░╚════════════════════════════════╝░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                   
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Check boxes

Independent on/off boxes; any combination may be set. cluster.value is a bitmask.

  File  Edit  Window                        
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]══════ Check Boxes ═══════════╗░░░░░░
░░║                                  ║░░░░░░
░░║                                  ║░░░░░░
░░║   [X] Option A                   ║░░░░░░
░░║   [ ] Option B                   ║░░░░░░
░░║   [X] Option C                   ║░░░░░░
░░║                                  ║░░░░░░
░░╚══════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                       
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Radio buttons

Mutually-exclusive options sharing one cluster; cluster.value is the selected index.

  File  Edit  Window                        
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]═════ Radio Buttons ══════════╗░░░░░░
░░║                                  ║░░░░░░
░░║                                  ║░░░░░░
░░║   ( ) One                        ║░░░░░░
░░║   (•) Two                        ║░░░░░░
░░║   ( ) Three                      ║░░░░░░
░░║                                  ║░░░░░░
░░╚══════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                       
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Text entry & labels

Input line

A single-line text field with a linked Label. The label's hot-letter focuses the field.

  File  Edit  Window                              
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]══════════ Input Line ══════════════╗░░░░░░
░░║                                        ║░░░░░░
░░║                                        ║░░░░░░
░░║  Name:   default text                  ║░░░░░░
░░║                                        ║░░░░░░
░░║                                        ║░░░░░░
░░║                                        ║░░░░░░
░░╚════════════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                             
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Masked input

tvision-rs extension: not in Turbo Vision. See Extensions beyond Turbo Vision.

A password field (MaskedInput) that shows its value as bullets while keeping the real text intact, with a reveal eye in the last column (its own Tab stop). Press-and-hold the eye, or focus it and press Space, to peek; Cut/Copy never place the cleartext on the clipboard. The eye glyphs come from the theme.

  File  Edit  Window                              
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]═════════ Masked Input ═════════════╗░░░░░░
░░║                                        ║░░░░░░
░░║                                        ║░░░░░░
░░║  Pass:   ••••••                      ⊝ ║░░░░░░
░░║                                        ║░░░░░░
░░║                                        ║░░░░░░
░░║                                        ║░░░░░░
░░╚════════════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                             
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Input line with history

An input line plus a THistory dropdown icon that recalls earlier entries from a named channel.

  File  Edit  Window                                    
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]══════════════ History ═══════════════════╗░░░░░░
░░║                                              ║░░░░░░
░░║                                       ▐↓▌    ║░░░░░░
░░║  ╔═[■]═════════════════════════╗             ║░░░░░░
░░║  ║ report.txt                  ▲             ║░░░░░░
░░║  ║ budget.csv                  ▒             ║░░░░░░
░░║  ║ notes.md                    ■             ║░░░░░░
░░║  ║ config.toml                 ▒             ║░░░░░░
░░║  ║ readme.md                   ▒             ║░░░░░░
 F10 Menu  Alt-X Exit                                   
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Static text

Read-only text with word-wrap; a leading \x03 centers a line.

  File  Edit  Window                              
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]═════════ Static Text ══════════════╗░░░░░░
░░║                                        ║░░░░░░
░░║             Centered Title             ║░░░░░░
░░║                                        ║░░░░░░
░░║ Left-aligned body text.                ║░░░░░░
░░║ Second line of body.                   ║░░░░░░
░░║ Third line here.                       ║░░░░░░
░░║                                        ║░░░░░░
░░║                                        ║░░░░░░
░░║                                        ║░░░░░░
░░╚════════════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                             
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Lists & trees

List box

A scrollable single-column list wired to a vertical scroll bar. Its items are filled on the first event tick, because new_list needs a Context; the thin wrapper view is the deferred-init pattern.

tvision-rs extension to TListViewer: incremental find is not in Turbo Vision. See Extensions beyond Turbo Vision.

Opt-in incremental find (with_find(FindMode::Filter) or FindMode::Highlight) lets the list own its query and highlight or self-filter while focused (see Controls).

  File  Edit  Window                                
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]════════════ List Box ════════════════╗░░░░░░
░░║                                          ║░░░░░░
░░║  Alpha                                 ▲ ║░░░░░░
░░║  Beta                                  ■ ║░░░░░░
░░║  Gamma                                 ▒ ║░░░░░░
░░║  Delta                                 ▒ ║░░░░░░
░░║  Epsilon                               ▒ ║░░░░░░
░░║  Zeta                                  ▒ ║░░░░░░
░░║  Eta                                   ▒ ║░░░░░░
░░║  Theta                                 ▒ ║░░░░░░
░░║                                        ▒ ║░░░░░░
░░║                                        ▼ ║░░░░░░
░░║                                          ║░░░░░░
░░╚══════════════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                               
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Table

tvision-rs extension: not in Turbo Vision. See Extensions beyond Turbo Vision.

A column header over a scrolling row list. Rows come from a TableModel (VecModel for plain strings) and carry a stable RowKey, so focus and the marked rows follow the record through a re-sort or a set_model reload. Click a column label to sort by it, click again to flip; numbers sort numerically. Columns shrink widest first to fit (never below min_width), cut text with …, and can be hidden; a flex column takes the spare width when the table is wider than its columns. Columns that do not fit at their min_width scroll horizontally: ←/→ or the horizontal bar (with_h_bar) move them, the header moves along, the check column stays put. Resize the window in the demo to see both. Drag the separator right of a label to resize that column (it then keeps that width), drag a label to move the column (a marker shows where it lands), and right-click the header to show or hide columns from a popup; TABLE_COLUMNS opens the same popup from a key or menu. Each of these broadcasts TABLE_COLUMNS_CHANGED; column_layout() / set_column_layout() save and restore the arrangement. resizable(false) / movable(false) lock a column. with_separators decides whether the one-cell gaps between the columns stay blank (the default, Separators::Off) or carry the theme's │ rule: Separators::Header rules the label row only, so the separator you drag to resize a column has a visible target, and Separators::All rules between every row's cells as well. When the columns leave spare width, the header also rules the cell after the last column, which is that column's resize handle; the rows leave that cell blank. In SelectionMode::Multi the rows get a leading check column drawn like check boxes: click a row's [ ] box, or press Space, to mark it. The table broadcasts TABLE_SORT_CHANGED, TABLE_SELECTION_CHANGED and, in single mode, LIST_ITEM_SELECTED, each with the table's id as source; its value is the focused key (single) or the list of marked keys (multi). Keyboard sorting is opt-in: bind keys to TABLE_SORT_NEXT / TABLE_SORT_FLIP. Columns built editable(true) are edited in place: the focused row shows a cell cursor that ←/→ move between them, and Enter, F2 or a double-click opens an input line over the cell (with the column's validator, if any). Enter stores the text through TableModel::set_cell (a refusal shows its message and keeps the editor open) and leaves the cursor on the cell, Esc or a click elsewhere cancels, Tab/Shift-Tab store and move to the next/previous editable cell; a store re-sorts and broadcasts TABLE_CELL_EDITED. Without an editable column Enter keeps its list meaning and presses the dialog's default button. In the demo, Image and CPU % are editable.

  File  Edit  Window                                  
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]════════════════ Table ═══════════════1═[↑]═╗░░
░░║     Name     Image              State     CPU %▲░░
░░║ [ ] web      nginx              running    12.5■░░
░░║ [ ] db       postgres           running    31.0▒░░
░░║ [ ] cache    redis              exited        0▒░░
░░║ [ ] queue    rabbitmq           running    4.25▒░░
░░║ [ ] mail     postfix            paused      0.5▒░░
░░║ [ ] search   opensearch         running    48.0▒░░
░░║ [ ] backup   restic             exited        0▒░░
░░║ [ ] proxy    haproxy            running     2.0▒░░
░░║ [ ] metrics  prometheus         running    9.75▒░░
░░║ [ ] logs     loki               running     6.5▒░░
░░║                                                ▒░░
░░║                                                ▼░░
░░└─◄▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓►─┘░░
 F10 Menu  Alt-X Exit                                 
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Outline

A collapsible tree viewer built from a Node tree, with horizontal and vertical scroll bars. Build the tree with Node::new and the builder methods, then pass the root to Outline::new. Each node can be expanded or collapsed with a mouse click on the +/- icon or the Enter key. The underlying OutlineViewer trait lets you swap in a custom data source (your own get_root/get_next/ get_child/get_text/is_expanded implementation) without reimplementing draw or navigation logic.

Call ov_update(outline, ctx) once after insertion (needs a Context) to publish the scroll range and initial cursor position to the sibling scroll bars.

  File  Edit  Window                                
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]════════════ Outline ═══════════1═[↑]═╗░░░░░░
░░║└──Root                                   ▲░░░░░░
░░║   ├──Child A                             ▓░░░░░░
░░║   │  ├──Grandchild A1                    ▓░░░░░░
░░║   │  └──Grandchild A2                    ▓░░░░░░
░░║   └──Child B                             ▓░░░░░░
░░║      └──Grandchild B1                    ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▓░░░░░░
░░║                                          ▼░░░░░░
░░└─◄▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓►─┘░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                               
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Scrolling & display

Scroll bars

A vertical and a horizontal scroll bar; the thumb position comes from the public value / max_value / page_step fields.

  File  Edit  Window                              
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]═════════ Scroll Bars ══════════════╗░░░░░░
░░║                                       ▲║░░░░░░
░░║                                       ▒║░░░░░░
░░║                                       ▒║░░░░░░
░░║                                       ■║░░░░░░
░░║                                       ▒║░░░░░░
░░║                                       ▒║░░░░░░
░░║                                       ▒║░░░░░░
░░║                                       ▒║░░░░░░
░░║                                       ▒║░░░░░░
░░║                                       ▒║░░░░░░
░░║◄▒▒▒▒▒▒▒▒▒▒▒▒▒▒■▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒►▼║░░░░░░
░░╚════════════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                             
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Memo

A multi-line text editor for use inside a dialog; set_text loads its initial content.

  File  Edit  Window                                    
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]════════════════ Memo ════════════════════╗░░░░░░
░░║                                              ║░░░░░░
░░║ Initial memo text.                           ║░░░░░░
░░║ Second line.                                 ║░░░░░░
░░║ Third line of content.                       ║░░░░░░
░░║                                              ║░░░░░░
░░║                                              ║░░░░░░
░░║                                              ║░░░░░░
░░║                                              ║░░░░░░
░░║                                              ║░░░░░░
░░║                                              ║░░░░░░
░░║                                              ║░░░░░░
░░╚══════════════════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                   
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Terminal

A scrolling output view you write into. Terminal embeds a Scroller and stores incoming bytes in a fixed-size ring buffer; the most recent lines that fit the view height are drawn. Write to it via the TextDevice::write_bytes method; there is no stream wrapper. Call Terminal::init once after insertion (needs a Context) to set the scroll limit, cursor position, and visibility. The gallery wrapper view seeds both calls on the first event tick because a Context is not available at construction time.

  File  Edit  Window                                            
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]══════════════════ Terminal ════════════════1═[↑]═╗░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░║                                                      ║░░░░░░
░░└─════════════════════════════════════════════════════─┘░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                           
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Windows & dialogs

Window

A titled, movable, resizable window that hosts child views.

  File  Edit  Window                                    
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]════════════════ Window ══════════════1═[↑]═╗░░░░
░░║                                                ║░░░░
░░║ This is a plain titled Window.                 ║░░░░
░░║                                                ║░░░░
░░║ It can host any child views,                   ║░░░░
░░║ just like a Dialog.                            ║░░░░
░░║                                                ║░░░░
░░║                                                ║░░░░
░░║                                                ║░░░░
░░║                                                ║░░░░
░░║                                                ║░░░░
░░║                                                ║░░░░
░░║                                                ║░░░░
░░║                                                ║░░░░
░░║                                                ║░░░░
░░└─══════════════════════════════════════════════─┘░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                   
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Splitter

tvision-rs extension: not in Turbo Vision. See Extensions beyond Turbo Vision.

Resizable multi-pane layout. Splitter::cols()/rows() arrange panes along one axis with draggable divider seams; .joined() connects the divider lines to the window frame (┬ ┴ ┤) and to each other (├). The left column here is a fixed sidebar; the right column is split into two rows.

  File  Edit  Window                                            
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]════════════╤════ Splitter ═══════════════1═[↑]═╗░░░░░░░░
░░║tree pane       │list pane                          ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                ├───────────────────────────────────╢░░░░░░░░
░░║                │form pane                          ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░║                │                                   ║░░░░░░░░
░░└─═══════════════╧══════════════════════════════════─┘░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                           
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Dialog

A modal form combining a labelled input, check boxes, and OK / Cancel buttons, the canonical Turbo Vision dialog.

  File  Edit  Window                                
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░╔═[■]════════════ Settings ════════════════╗░░░░░░
░░║                                          ║░░░░░░
░░║  Name:                                   ║░░░░░░
░░║                                          ║░░░░░░
░░║                                          ║░░░░░░
░░║  [X] Enable logging                      ║░░░░░░
░░║  [ ] Auto-save                           ║░░░░░░
░░║  [ ] Show hints                          ║░░░░░░
░░║                                          ║░░░░░░
░░║                                          ║░░░░░░
░░║         OK    ▄              Cancel   ▄  ║░░░░░░
░░║      ▀▀▀▀▀▀▀▀▀▀            ▀▀▀▀▀▀▀▀▀▀▀▀  ║░░░░░░
░░╚══════════════════════════════════════════╝░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                               
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Message box

A short message with a default button. (The framework's Program::message_box helper builds one for you; this shows the equivalent assembled by hand.)

  File  Edit  Window                                    
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░╔═[■]════════ Information ═════════════╗░░░░░░░░░░░
░░░░░║                                      ║░░░░░░░░░░░
░░░░░║  Operation completed successfully.   ║░░░░░░░░░░░
░░░░░║                                      ║░░░░░░░░░░░
░░░░░║                                      ║░░░░░░░░░░░
░░░░░║                                      ║░░░░░░░░░░░
░░░░░║                  OK    ▄             ║░░░░░░░░░░░
░░░░░║               ▀▀▀▀▀▀▀▀▀▀             ║░░░░░░░░░░░
░░░░░╚══════════════════════════════════════╝░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                   
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Color picker

tvision-rs extension: not in Turbo Vision. See Extensions beyond Turbo Vision.

The truecolor picker dialog, with Presets, RGB, Hue/Sat and Xterm tabs. It takes the place of Turbo Vision's TColorDialog.

  File  Edit  Window                                                  
░╔═[■]═══════════════════ Select Color ═══════════════════════╗░░░░░░░
░║                                                            ║░░░░░░░
░║ Presets RGB ┌Hue/Sat┐ Xterm              Old:              ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▲▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ New:              ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ Rgb(30,144,255)   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▲▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║ ▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀                   ║░░░░░░░
░║                                                            ║░░░░░░░
░║                                         OK   ▄    Cancel ▄ ║░░░░░░░
░║                                       ▀▀▀▀▀▀▀▀    ▀▀▀▀▀▀▀▀ ║░░░░░░░
░╚════════════════════════════════════════════════════════════╝░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                                 
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

File dialog

A file-open dialog: a name field, the file and directory lists, and action buttons. The lists fill themselves when the dialog is run modally.

  File  Edit  Window                                                  
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░╔═[■]════════════════ Open a File ═════════════════════╗░░░░░░░
░░░░░░░║                                                      ║░░░░░░░
░░░░░░░║  Name                                                ║░░░░░░░
░░░░░░░║   budget.csv                        ▐↓▌    Open   ▄  ║░░░░░░░
░░░░░░░║                                           ▀▀▀▀▀▀▀▀▀  ║░░░░░░░
░░░░░░░║  Files                                               ║░░░░░░░
░░░░░░░║   budget.csv        │                     Cancel  ▄  ║░░░░░░░
░░░░░░░║   config.toml       │                     ▀▀▀▀▀▀▀▀▀  ║░░░░░░░
░░░░░░░║   notes.md          │                                ║░░░░░░░
░░░░░░░║   readme.md         │                                ║░░░░░░░
░░░░░░░║   report.txt        │                                ║░░░░░░░
░░░░░░░║   archive/          │                                ║░░░░░░░
░░░░░░░║   images/           │                                ║░░░░░░░
░░░░░░░║   ../               │                                ║░░░░░░░
░░░░░░░║  ◄■▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒►              ║░░░░░░░
░░░░░░░║                                                      ║░░░░░░░
░░░░░░░║ /home/runner/work/tvision-rs/tvision-rs/examples/gall║░░░░░░░
░░░░░░░║ budget.csv     40              Oct 19,2026  12:32p   ║░░░░░░░
░░░░░░░└─════════════════════════════════════════════════════─┘░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                                 
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Change-directory dialog

A directory chooser with a navigable tree.

  File  Edit  Window                                            
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░╔═[■]══════════ Change Directory ══════════════╗░░░░░░░░
░░░░░░░░║                                              ║░░░░░░░░
░░░░░░░░║  Directory name                              ║░░░░░░░░
░░░░░░░░║  ◄s/tvision-rs/examples/gallery_fixture ▐↓▌  ║░░░░░░░░
░░░░░░░░║                                              ║░░░░░░░░
░░░░░░░░║  Directory tree                              ║░░░░░░░░
░░░░░░░░║   └─┬/                        ▲      OK   ▄  ║░░░░░░░░
░░░░░░░░║     └─┬home                   ▒    ▀▀▀▀▀▀▀▀  ║░░░░░░░░
░░░░░░░░║       └─┬runner               ▒              ║░░░░░░░░
░░░░░░░░║         └─┬work               ▒    Chdir  ▄  ║░░░░░░░░
░░░░░░░░║           └─┬tvision-rs       ▒    ▀▀▀▀▀▀▀▀  ║░░░░░░░░
░░░░░░░░║             └─┬tvision-rs     ▒              ║░░░░░░░░
░░░░░░░░║               └─┬examples     ■    Revert ▄  ║░░░░░░░░
░░░░░░░░║                 └─┬gallery_fix▒    ▀▀▀▀▀▀▀▀  ║░░░░░░░░
░░░░░░░░║                   └┬─archive  ▒              ║░░░░░░░░
░░░░░░░░║                    └─images   ▼              ║░░░░░░░░
░░░░░░░░║                                              ║░░░░░░░░
░░░░░░░░└─════════════════════════════════════════════─┘░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                           
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Editor window

A ready-made editor window: a file-backed editor wired to scroll bars and a line:column indicator.

  File  Edit  Window                                                        
░╔═[■]═══════════════ /tmp/rstv_gallery_sample.txt ═════════════1═[↑]═╗░░░░░
░║fn main() {                                                         ▲░░░░░
░║    println!("Hello, tvision-rs!");                                 ▓░░░░░
░║}                                                                   ▓░░░░░
░║                                                                    ▓░░░░░
░║// An editor window with                                            ▓░░░░░
░║// scroll bars and a line:col indicator.                            ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▓░░░░░
░║                                                                    ▼░░░░░
░└─══════ 1:1 ═════◄■▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒►─┘░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                                       
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Application chrome

The top menu bar, built from nested pull-downs with hot-keys and accelerators. File ▸ Recent is a sub-menu nested inside a sub-menu.

  File  Edit  Window                                    
 ┌─────────────┐ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 │ Open…    F3 │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 │ New      F4 │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 │ Recent    ► │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 ├ ┌────────────┐ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 │ │ report.txt │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 └ │ budget.csv │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░ │ notes.md   │ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░ └────────────┘ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                                   
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Context menu

A right-click pop-up, built from the same Menu data and wrapped in a MenuBox.

  File  Edit  Window                    
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░ ┌────────────┐ ░░░░░░░░░░░░░░░░░░
░░░░░░ │ Cut        │ ░░░░░░░░░░░░░░░░░░
░░░░░░ │ Copy       │ ░░░░░░░░░░░░░░░░░░
░░░░░░ │ Paste      │ ░░░░░░░░░░░░░░░░░░
░░░░░░ ├────────────┤ ░░░░░░░░░░░░░░░░░░
░░░░░░ │ Select All │ ░░░░░░░░░░░░░░░░░░
░░░░░░ └────────────┘ ░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F10 Menu  Alt-X Exit                   
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

Status line

The bottom status line of labelled hot-key items; each fires a command when clicked or keyed.

  File  Edit  Window                                    
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
 F2 Save  F3 Open  F10 Menu  Alt-X Exit                 
//! `gallery` — renders a single widget per run, for the documentation's widget
//! gallery. Each `// ANCHOR: <name>`-marked builder below is included verbatim
//! into the guide, so every documented widget snippet is real, compiling code,
//! and the same builder drives the captured screenshot.
//!
//! Usage:
//! ```text
//! cargo run --example gallery -- <name>   # show one widget
//! cargo run --example gallery             # list the available names
//! ```
//!
//! Adding a widget = write a builder, add a `specimen()` arm + a `NAMES` entry,
//! and register a `Screen` in `xtask/src/screens.rs`.

use std::{env, io};

use tvision_rs::widgets::table::SelectionMode;
use tvision_rs::{
    Button, ButtonFlags, ButtonRowAlign, CD_NORMAL, ChDirDialog, CheckBoxes, Color, ColorPicker,
    ColumnSpec, Command, Constraints, Context, CrosstermBackend, Desktop, Dialog, EditWindow,
    Event, FD_OPEN_BUTTON, FieldValue, FileDialog, FilterValidator, GrowMode, HistoryWindow,
    InputLine, Key, KeyEvent, Label, ListBox, MaskedInput, Memo, Menu, MenuBar, MenuBox, Node,
    Outline, OutlineViewer, Program, RadioButtons, Rect, RevealEyeConfig, RowKey, ScrollBar,
    ScrollBarOptions, Splitter, StaticText, StatusDef, StatusLine, SystemClock, THistory, Tab,
    Table, Terminal, TextDevice, Theme, VecModel, View, ViewId, Window, alt, delegate, history_add,
    ov_update,
};

/// How a specimen is shown. Most widgets are leaf controls hosted in a dialog on
/// the desktop; the `Menu` / `Status` variants replace the corresponding chrome
/// so those two can be showcased in place.
#[derive(Clone, Copy)]
enum Specimen {
    /// A view (a dialog or a window) placed on the desktop.
    OnDesktop(fn() -> Box<dyn View>),
    /// A dialog shown modally via `exec_view` — the faithful path for the
    /// self-managing file/directory dialogs, whose lists are filled by
    /// `reset_current` when the modal becomes current.
    Modal(fn() -> Box<dyn View>),
    /// A rich menu bar (the screenshot opens it with a keystroke).
    Menu(fn() -> Menu),
    /// A rich status line.
    Status(fn() -> Vec<StatusDef>),
}

/// Map a CLI name to its specimen. Keep `NAMES` in sync.
fn specimen(name: &str) -> Option<Specimen> {
    use Specimen::*;
    Some(match name {
        "button" => OnDesktop(button),
        "menubar" => Menu(menubar),
        "statusline" => Status(statusline),
        "contextmenu" => OnDesktop(contextmenu),
        "checkboxes" => OnDesktop(checkboxes),
        "radiobuttons" => OnDesktop(radiobuttons),
        "inputline" => OnDesktop(inputline),
        "masked_input" => OnDesktop(masked_input),
        "statictext" => OnDesktop(statictext),
        "scrollbar" => OnDesktop(scrollbar),
        "history" => OnDesktop(history),
        "dialog" => OnDesktop(dialog),
        "memo" => OnDesktop(memo),
        "colorpicker" => OnDesktop(colorpicker),
        "messagebox" => OnDesktop(messagebox),
        "window" => OnDesktop(window),
        "splitter" => OnDesktop(splitter),
        "editor" => OnDesktop(editor),
        "listbox" => OnDesktop(listbox),
        "table" => OnDesktop(table),
        "terminal" => OnDesktop(terminal),
        "outline" => OnDesktop(outline),
        "filedialog" => Modal(filedialog),
        "chdirdialog" => Modal(chdirdialog),
        _ => return None,
    })
}

/// Every registered widget name (for the no-arg listing and the xtask registry).
const NAMES: &[&str] = &[
    "button",
    "menubar",
    "statusline",
    "contextmenu",
    "checkboxes",
    "radiobuttons",
    "inputline",
    "masked_input",
    "statictext",
    "scrollbar",
    "history",
    "dialog",
    "memo",
    "colorpicker",
    "messagebox",
    "window",
    "splitter",
    "editor",
    "listbox",
    "table",
    "terminal",
    "outline",
    "filedialog",
    "chdirdialog",
];

// ===========================================================================
// Specimens — one `// ANCHOR: <name>` builder per widget.
// ===========================================================================

/// A dialog with a default `OK` button and a `Cancel` button. The `~` marks the
/// hot-letter; `default: true` makes `Enter` press `OK`.
fn button() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 36, 9), Some("Buttons".to_string()));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(4, 4, 16, 6),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(19, 4, 31, 6),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));
    Box::new(dlg)
}

/// A menu bar with `File`, `Edit`, and `Window` pull-downs. Each `~`-marked
/// letter is the hot-key; `command_key` adds the accelerator shown at the right.
/// `File ▸ Recent` is a nested sub-menu (a sub-menu inside a sub-menu).
fn menubar() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .command_key(
                "~N~ew",
                Command::custom("gallery.new"),
                KeyEvent::from(Key::F(4)),
                "F4",
            )
            .submenu("~R~ecent", alt('r'), |s| {
                s.command("report.txt", Command::custom("gallery.recent1"))
                    .command("budget.csv", Command::custom("gallery.recent2"))
                    .command("notes.md", Command::custom("gallery.recent3"))
            })
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A status line of labelled hot-key items. Clicking a label or pressing its key
/// fires the command; `~`-marked text is highlighted.
fn statusline() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F2~ Save", KeyEvent::from(Key::F(2)), Command::SAVE)
                .item(
                    "~F3~ Open",
                    KeyEvent::from(Key::F(3)),
                    Command::custom("gallery.open"),
                )
                .item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

/// A context menu — the pop-up box shown on a right-click, built from the same
/// `Menu` data as a menu bar and wrapped in a `MenuBox` (which sizes itself to
/// fit the items). At runtime `popup_menu(pos, menu, …)` opens one at the cursor.
fn contextmenu() -> Box<dyn View> {
    let menu = Menu::builder()
        .command("Cu~t~", Command::CUT)
        .command("~C~opy", Command::COPY)
        .command("~P~aste", Command::PASTE)
        .separator()
        .command("Select ~A~ll", Command::custom("gallery.select_all"))
        .build();
    Box::new(MenuBox::new(Rect::new(6, 2, 40, 16), menu))
}

/// Three independent check boxes hosted in a dialog. `cluster.value` is a
/// bitmask: bit 0 = first item, bit 1 = second, etc. Bit 0 and bit 2 are set
/// so items A and C start checked.
fn checkboxes() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Check Boxes".to_string()));
    let mut cb = CheckBoxes::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ption A".to_string(),
            "~O~ption B".to_string(),
            "~O~ption C".to_string(),
        ],
    );
    cb.cluster.value = 0b101; // items A and C checked
    dlg.insert_child(Box::new(cb));
    Box::new(dlg)
}

/// Three mutually-exclusive radio buttons. `cluster.value` is the selected
/// index; item 1 ("Two") starts selected.
fn radiobuttons() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 38, 9), Some("Radio Buttons".to_string()));
    let mut rb = RadioButtons::new(
        Rect::new(3, 3, 34, 6),
        vec![
            "~O~ne".to_string(),
            "~T~wo".to_string(),
            "T~h~ree".to_string(),
        ],
    );
    rb.cluster.value = 1; // "Two" selected
    dlg.insert_child(Box::new(rb));
    Box::new(dlg)
}

/// A labeled single-line text entry. The `Label` links to the `InputLine` via
/// its `ViewId` so that pressing `~N~` focuses the field.
fn inputline() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Input Line".to_string()));
    let mut il = InputLine::with_limit(Rect::new(10, 3, 40, 4), 64);
    il.data = "default text".to_string();
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~N~ame:",
        Some(il_id),
    )));
    Box::new(dlg)
}

/// A masked password field (`MaskedInput`): the value is shown as bullets while
/// the real text is kept intact, with a reveal eye in the last column (its own
/// Tab stop). Press-and-hold the eye, or focus it and press Space, to peek. The
/// eye glyphs (`⊝` hidden / `◉` revealed) come from the theme.
fn masked_input() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 9), Some("Masked Input".to_string()));
    let mut mi = MaskedInput::new(Rect::new(10, 3, 40, 4), 64, '•', RevealEyeConfig::default());
    mi.set_value(FieldValue::Text("s3cr3t".into()));
    let mi_id = dlg.insert_child(Box::new(mi));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 3, 10, 4),
        "~P~ass:",
        Some(mi_id),
    )));
    Box::new(dlg)
}

/// Static text supports word wrap, left-aligned lines, and the `\x03` prefix
/// to center individual lines.
fn statictext() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 12), Some("Static Text".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 40, 9),
        "\x03Centered Title\n\nLeft-aligned body text.\nSecond line of body.\nThird line here.",
    )));
    Box::new(dlg)
}

/// A vertical and a horizontal scroll bar with a visible thumb, framing the
/// right and bottom edges of the dialog the way they sit around a scrollable
/// view. The thumb position is set by writing the public fields before insertion.
fn scrollbar() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 44, 14), Some("Scroll Bars".to_string()));

    // Vertical bar down the right inner edge.
    let mut vsb = ScrollBar::new(Rect::new(40, 1, 41, 12));
    vsb.min_value = 0;
    vsb.max_value = 50;
    vsb.value = 10;
    vsb.page_step = 5;
    vsb.arrow_step = 1;
    dlg.insert_child(Box::new(vsb));

    // Horizontal bar along the bottom inner edge.
    let mut hsb = ScrollBar::new(Rect::new(1, 11, 40, 12));
    hsb.min_value = 0;
    hsb.max_value = 50;
    hsb.value = 20;
    hsb.page_step = 5;
    hsb.arrow_step = 1;
    dlg.insert_child(Box::new(hsb));

    Box::new(dlg)
}

/// An input line with a `THistory` dropdown icon, shown with its recall list
/// open. Clicking the `↓` icon drops down a [`HistoryWindow`] over the field;
/// here one is shown directly, listing the entries pre-loaded into channel 1.
fn history() -> Box<dyn View> {
    for entry in [
        "report.txt",
        "budget.csv",
        "notes.md",
        "config.toml",
        "readme.md",
    ] {
        history_add(1, entry);
    }

    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("History".to_string()));
    let il = InputLine::with_limit(Rect::new(3, 2, 40, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(THistory::new(Rect::new(40, 2, 43, 3), il_id, 1u8)));
    // The drop-down recall popup, listing channel 1, opened below the field.
    dlg.insert_child(Box::new(HistoryWindow::new(Rect::new(3, 3, 34, 12), 1u8)));
    Box::new(dlg)
}

/// A realistic settings dialog combining a labeled text field, check boxes,
/// and OK / Cancel buttons.
fn dialog() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 46, 14), Some("Settings".to_string()));

    // Name field with label
    let il = InputLine::with_limit(Rect::new(12, 2, 42, 3), 64);
    let il_id = dlg.insert_child(Box::new(il));
    dlg.insert_child(Box::new(Label::new(
        Rect::new(2, 2, 12, 3),
        "~N~ame:",
        Some(il_id),
    )));

    // Check boxes
    let mut cb = CheckBoxes::new(
        Rect::new(2, 5, 42, 8),
        vec![
            "~E~nable logging".to_string(),
            "~A~uto-save".to_string(),
            "~S~how hints".to_string(),
        ],
    );
    cb.cluster.value = 0b001; // "Enable logging" checked
    dlg.insert_child(Box::new(cb));

    // OK and Cancel buttons
    dlg.insert_child(Box::new(Button::new(
        Rect::new(5, 10, 17, 12),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(27, 10, 41, 12),
        "~C~ancel",
        Command::CANCEL,
        ButtonFlags::default(),
    )));

    Box::new(dlg)
}

/// A `Memo` editor with pre-filled text. Scroll-bar ids are omitted (`None`)
/// to keep the specimen self-contained.
fn memo() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(2, 1, 50, 14), Some("Memo".to_string()));
    let mut m = Memo::new(Rect::new(2, 2, 46, 11), None, None, None, 4096);
    m.editor
        .set_text(b"Initial memo text.\nSecond line.\nThird line of content.");
    dlg.insert_child(Box::new(m));
    Box::new(dlg)
}

/// A full-color picker with OK and Cancel buttons. The picker needs at least
/// 56 × 18 content area; the dialog is sized to give it comfortable margins.
///
/// Layout: dialog 62 × 23 cells. Picker occupies rows 2–18 (17 rows tall),
/// leaving row 19 blank and the button row at row 20 (`height − 3`).
fn colorpicker() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(1, 0, 63, 23), Some("Select Color".to_string()));
    let mut picker = ColorPicker::new(Rect::new(2, 2, 60, 19), Color::Rgb(30, 144, 255));
    // Open on the visual hue/saturation plane rather than the preset palette.
    picker.select_tab(Tab::Plane);
    dlg.insert_child(Box::new(picker));
    dlg.button_row(
        &[
            (
                "~O~K",
                Command::OK,
                ButtonFlags {
                    default: true,
                    ..Default::default()
                },
            ),
            ("~C~ancel", Command::CANCEL, ButtonFlags::default()),
        ],
        ButtonRowAlign::Right,
    );
    Box::new(dlg)
}

/// A simple information dialog — equivalent to a Turbo Vision `messageBox` —
/// built from public types: a `Dialog`, a `StaticText` message, and a default
/// OK `Button`.
fn messagebox() -> Box<dyn View> {
    let mut dlg = Dialog::new(Rect::new(5, 3, 45, 12), Some("Information".to_string()));
    dlg.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 38, 6),
        "\x03Operation completed successfully.",
    )));
    dlg.insert_child(Box::new(Button::new(
        Rect::new(14, 6, 26, 8),
        "~O~K",
        Command::OK,
        ButtonFlags {
            default: true,
            ..Default::default()
        },
    )));
    Box::new(dlg)
}

/// A titled `Window` with two lines of `StaticText` inside. The inner bounds
/// are inset by one cell on every side so the text clears the frame.
fn window() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 17), Some("Window".to_string()), 1);
    win.insert_child(Box::new(StaticText::new(
        Rect::new(2, 2, 47, 8),
        "This is a plain titled Window.\n\nIt can host any child views,\njust like a Dialog.",
    )));
    Box::new(win)
}

/// A `Splitter` laying out three panes inside a window, with `.joined()` so the
/// divider lines connect to the window frame (`┬ ┴ ┤`) and to each other (`├`).
/// The left column is a fixed-width sidebar; the right column is itself split
/// into two stacked rows. Drag a seam to resize; or enter resize mode (Ctrl-F5)
/// and Tab to a divider, then arrow-keys to move it.
fn splitter() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 56, 17), Some("Splitter".to_string()), 1);
    let ext = win.state().get_extent();
    let interior = Rect::new(1, 1, ext.b.x - 1, ext.b.y - 1);

    // Right column: two stacked panes (a horizontal seam between them).
    let right = Splitter::rows()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "list pane")),
            Constraints::flex(),
        )
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "form pane")),
            Constraints::flex(),
        );

    // Outer: a fixed sidebar beside the right column; `.joined()` connects all
    // the divider lines to each other and to the window frame.
    let split = Splitter::cols()
        .pane(
            Box::new(StaticText::new(Rect::new(0, 0, 1, 1), "tree pane")),
            Constraints::fixed(16),
        )
        .pane(Box::new(right), Constraints::flex())
        .joined();

    let split_id = win.insert_child(Box::new(split));
    if let Some(v) = win.child_mut(split_id) {
        v.change_bounds(interior);
    }
    Box::new(win)
}

/// An `EditWindow` opened on a small sample file written to a temp path. The
/// window includes scroll bars and a line:column indicator in the frame.
fn editor() -> Box<dyn View> {
    let path = std::env::temp_dir().join("rstv_gallery_sample.txt");
    let _ = std::fs::write(
        &path,
        "fn main() {\n    println!(\"Hello, tvision-rs!\");\n}\n\n// An editor window with\n// scroll bars and a line:col indicator.\n",
    );
    let win = EditWindow::new(Rect::new(1, 0, 71, 22), Some(path), 1);
    Box::new(win)
}

/// A `ListBox` with a vertical scroll bar, populated on the first event tick
/// via a thin wrapper view (the `new_list` call needs `&mut Context`).
struct ListBoxShowcase {
    dialog: Dialog,
    list_id: ViewId,
    populated: bool,
}

impl ListBoxShowcase {
    fn new() -> Self {
        let mut dlg = Dialog::new(Rect::new(2, 1, 46, 15), Some("List Box".to_string()));
        let vsb = ScrollBar::new(Rect::new(41, 2, 42, 12));
        let vsb_id = dlg.insert_child(Box::new(vsb));
        let lb = ListBox::new(Rect::new(2, 2, 41, 12), 1, None, Some(vsb_id));
        let list_id = dlg.insert_child(Box::new(lb));
        ListBoxShowcase {
            dialog: dlg,
            list_id,
            populated: false,
        }
    }
}

#[delegate(to = dialog)]
impl View for ListBoxShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.populated {
            self.populated = true;
            if let Some(v) = self.dialog.child_mut(self.list_id)
                && let Some(lb) = v.as_any_mut().and_then(|a| a.downcast_mut::<ListBox>())
            {
                lb.new_list(
                    vec![
                        "Alpha".into(),
                        "Beta".into(),
                        "Gamma".into(),
                        "Delta".into(),
                        "Epsilon".into(),
                        "Zeta".into(),
                        "Eta".into(),
                        "Theta".into(),
                    ],
                    ctx,
                );
                tvision_rs::widgets::list_viewer::update_steps(lb, ctx);
            }
        }
        self.dialog.handle_event(ev, ctx);
    }
}

fn listbox() -> Box<dyn View> {
    Box::new(ListBoxShowcase::new())
}

/// A multi-select `Table` in a resizable window, with both scroll bars on the
/// frame. Click a column label to sort (again to flip); click the [ ] box or
/// press Space to mark a row. Rows are keyed by their ID so focus and marks
/// follow the record through a re-sort or a `set_model` reload. The Image
/// column is `flex`: widen the window and it takes the spare width. Shrink
/// the window below the columns' `min_width`s and the columns scroll
/// horizontally (the bottom bar, or ←/→ past the cell cursor's stops) while
/// the check column stays put. Image and CPU % are editable: ←/→ move the cell
/// cursor between them, Enter, F2 or a double-click opens an editor (Enter
/// stores, Esc cancels, Tab moves on); CPU % takes only digits and a dot. No
/// wrapper view is needed: the table publishes its ranges to the bars itself.
fn table() -> Box<dyn View> {
    let mut win = Window::new(Rect::new(2, 1, 52, 16), Some("Table".to_string()), 1);
    let h_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: false,
        handle_keyboard: false,
    });
    let v_bar = win.standard_scroll_bar(ScrollBarOptions {
        vertical: true,
        handle_keyboard: false,
    });
    let rows = [
        ["web", "nginx", "running", "12.5"],
        ["db", "postgres", "running", "31.0"],
        ["cache", "redis", "exited", "0"],
        ["queue", "rabbitmq", "running", "4.25"],
        ["mail", "postfix", "paused", "0.5"],
        ["search", "opensearch", "running", "48.0"],
        ["backup", "restic", "exited", "0"],
        ["proxy", "haproxy", "running", "2.0"],
        ["metrics", "prometheus", "running", "9.75"],
        ["logs", "loki", "running", "6.5"],
    ];
    let keys = rows.iter().map(|r| RowKey::from(r[0])).collect();
    let rows = rows
        .iter()
        .map(|r| r.iter().map(|s| s.to_string()).collect())
        .collect();
    // The table fills the window's interior and grows with it.
    let mut inner = View::state(&win).get_extent();
    inner.grow(-1, -1);
    let mut table = Table::new(
        inner,
        vec![
            ColumnSpec::new("Name", 8).min_width(8),
            ColumnSpec::new("Image", 11)
                .min_width(10)
                .flex(1)
                .editable(true),
            ColumnSpec::new("State", 8).min_width(8),
            ColumnSpec::new("CPU %", 6)
                .min_width(6)
                .right()
                .editable(true)
                .validator(Box::new(|| Box::new(FilterValidator::new("0123456789.")))),
        ],
        Some(v_bar),
    )
    .with_h_bar(h_bar)
    .with_model(Box::new(VecModel::new(rows).with_keys(keys)))
    .with_selection_mode(SelectionMode::Multi);
    table.state_mut().grow_mode = GrowMode {
        hi_x: true,
        hi_y: true,
        ..Default::default()
    };
    win.insert_child(Box::new(table));
    Box::new(win)
}

/// A `Terminal` widget initialized on the first event tick and seeded with two
/// lines of output. The wrapper pattern lets `init` and `write_bytes` receive
/// the `&mut Context` they require.
struct TerminalShowcase {
    window: Window,
    term_id: ViewId,
    initialized: bool,
}

impl TerminalShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 58, 17), Some("Terminal".to_string()), 1);
        let term = Terminal::new(Rect::new(1, 1, 54, 15), None, None, 4096);
        let term_id = win.insert_child(Box::new(term));
        TerminalShowcase {
            window: win,
            term_id,
            initialized: false,
        }
    }
}

#[delegate(to = window)]
impl View for TerminalShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if !self.initialized {
            self.initialized = true;
            if let Some(v) = self.window.child_mut(self.term_id)
                && let Some(t) = v.as_any_mut().and_then(|a| a.downcast_mut::<Terminal>())
            {
                t.init(ctx);
                t.write_bytes(b"Hello from Terminal!\nLine two.\nLine three.\n", ctx);
            }
        }
        self.window.handle_event(ev, ctx);
    }
}

fn terminal() -> Box<dyn View> {
    Box::new(TerminalShowcase::new())
}

/// An `Outline` tree viewer with horizontal and vertical scroll bars,
/// initialized on the first event tick (mirrors `tvdir.rs`'s lazy-init guard).
struct OutlineShowcase {
    window: Window,
    outline_id: ViewId,
}

impl OutlineShowcase {
    fn new() -> Self {
        let mut win = Window::new(Rect::new(2, 1, 46, 21), Some("Outline".to_string()), 1);
        // Standard scroll bars sit on the window's right and bottom frame edges;
        // the outline fills the inner area (extent shrunk by one cell each side).
        let h_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: false,
            handle_keyboard: true,
        });
        let v_id = win.standard_scroll_bar(ScrollBarOptions {
            vertical: true,
            handle_keyboard: true,
        });
        let mut inner = View::state(&win).get_extent();
        inner.grow(-1, -1);
        let root = Node::new("Root")
            .with_expanded(true)
            .with_children(Box::new(
                Node::new("Child A")
                    .with_expanded(true)
                    .with_children(Box::new(
                        Node::new("Grandchild A1").with_next(Box::new(Node::new("Grandchild A2"))),
                    ))
                    .with_next(Box::new(
                        Node::new("Child B")
                            .with_expanded(true)
                            .with_children(Box::new(Node::new("Grandchild B1"))),
                    )),
            ));
        let ol = Outline::new(inner, Some(h_id), Some(v_id), Some(Box::new(root)));
        let outline_id = win.insert_child(Box::new(ol));
        OutlineShowcase {
            window: win,
            outline_id,
        }
    }
}

#[delegate(to = window)]
impl View for OutlineShowcase {
    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
        if let Some(v) = self.window.child_mut(self.outline_id)
            && let Some(ol) = v.as_any_mut().and_then(|a| a.downcast_mut::<Outline>())
            && ol.ov().limit.y == 0
        {
            ov_update(ol, ctx);
        }
        self.window.handle_event(ev, ctx);
    }
}

fn outline() -> Box<dyn View> {
    Box::new(OutlineShowcase::new())
}

/// A `FileDialog` with an `Open` button. The file list is read from the current
/// directory by `reset_current` when the dialog is shown modally. (The gallery
/// first `cd`s into a small fixture dir so the listing is reproducible; a real
/// app just builds the dialog.)
fn filedialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let fd = FileDialog::new("*.*", "Open a File", "~N~ame", FD_OPEN_BUTTON, 2);
    Box::new(fd)
}

/// A `ChDirDialog` (Change Directory). The directory tree reflects the current
/// directory, read by `reset_current` when the dialog is shown modally. (The
/// gallery `cd`s into a fixture dir first for a reproducible tree.)
fn chdirdialog() -> Box<dyn View> {
    enter_gallery_fixture();
    let cd = ChDirDialog::new(CD_NORMAL, 3);
    Box::new(cd)
}

/// Switch into a committed fixture directory (`examples/gallery_fixture`) so the
/// file/directory dialogs list fixed, reproducible content instead of whatever
/// happens to be in the working directory. Gallery scaffolding only — not part
/// of the widget API.
fn enter_gallery_fixture() {
    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/examples/gallery_fixture");
    let _ = std::env::set_current_dir(dir);
}

// ===========================================================================
// Default chrome (used whenever a specimen does not replace it).
// ===========================================================================

/// A representative File / Edit / Window menu bar.
fn default_menu() -> Menu {
    Menu::builder()
        .submenu("~F~ile", alt('f'), |m| {
            m.command_key(
                "~O~pen…",
                Command::custom("gallery.open"),
                KeyEvent::from(Key::F(3)),
                "F3",
            )
            .separator()
            .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
        })
        .submenu("~E~dit", alt('e'), |m| {
            m.command("Cu~t~", Command::CUT)
                .command("~C~opy", Command::COPY)
                .command("~P~aste", Command::PASTE)
        })
        .submenu("~W~indow", alt('w'), |m| {
            m.command("~T~ile", Command::TILE)
                .command("C~a~scade", Command::CASCADE)
        })
        .build()
}

/// A representative status line.
fn default_status() -> Vec<StatusDef> {
    StatusDef::list()
        .def_all(|d| {
            d.item("~F10~ Menu", KeyEvent::from(Key::F(10)), Command::MENU)
                .item("~Alt-X~ Exit", alt('x'), Command::QUIT)
        })
        .build()
}

// ===========================================================================
// Program assembly: the three factories consult the selected specimen.
// ===========================================================================

fn make_desktop(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y += 1; // below the menu bar
    r.b.y -= 1; // above the status line
    let mut desktop = Desktop::new(r, |br| Some(Desktop::init_background(br)));
    if let Specimen::OnDesktop(build) = spec {
        desktop.insert_view(build());
    }
    Box::new(desktop)
}

fn make_status(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.a.y = r.b.y - 1;
    let defs = match spec {
        Specimen::Status(build) => build(),
        _ => default_status(),
    };
    Box::new(StatusLine::new(r, defs))
}

fn make_menu(extent: Rect, spec: Specimen) -> Box<dyn View> {
    let mut r = extent;
    r.b.y = r.a.y + 1;
    let menu = match spec {
        Specimen::Menu(build) => build(),
        _ => default_menu(),
    };
    Box::new(MenuBar::new(r, menu))
}

fn main() -> io::Result<()> {
    let name = env::args().nth(1).unwrap_or_default();
    let Some(spec) = specimen(&name) else {
        eprintln!("usage: cargo run --example gallery -- <name>");
        eprintln!("widgets: {}", NAMES.join(", "));
        return Ok(());
    };

    let mut program = Program::new(
        Box::new(CrosstermBackend::new()?),
        Box::new(SystemClock::new()),
        Theme::classic_blue(),
        |r| Some(make_desktop(r, spec)),
        |r| Some(make_status(r, spec)),
        |r| Some(make_menu(r, spec)),
    );
    // Both `run` and `exec_view` idle after painting; the screenshot tooling
    // captures the static frame and then kills the session (no quit/close
    // command is ever sent). A `Modal` specimen is shown via `exec_view` so its
    // `reset_current` runs — that is what fills the file/directory lists.
    match spec {
        Specimen::Modal(build) => {
            let _ = program.exec_view(build());
        }
        _ => {
            let _ = program.run();
        }
    }
    Ok(())
}

The view tree

Everything you see on screen is a node in one tree. The desktop is a node; each window on it is a node; the frame, scrollbars, buttons and input lines inside a window are nodes. tvision-rs calls the core abstraction the View trait and the container type Group, keeping the Turbo Vision tree model in idiomatic Rust.

A trait and a state struct

Every widget in tvision-rs is defined by two things working together:

  • View: the behaviour. It is a trait whose methods cover everything the framework calls: draw paints the view, handle_event reacts to input, and a handful of others (set_state, valid, value / set_value) cover focus, validation and data transfer. handle_event and these four have default bodies.
  • ViewState: the data. A struct that every widget embeds (conventionally a field named state), holding origin, size, cursor, the state / option / grow / drag flags, the event mask and the help context.

Every widget embeds a ViewState and implements View. Only three methods are required: state, state_mut, and draw; the rest have defaults. That is the composition recipe, and the Writing your own View chapter walks it end to end.

Turbo Vision heritage: the C++ library built every widget by inheriting from TView. The View trait covers TView's virtual methods; ViewState covers its data members.

Flags became fields

The boolean properties of a view (visibility, focus, whether it responds to keyboard input) are organized into four structs of named booleans, one per logical family. You read self.state.state.visible directly; no bitmask arithmetic is needed.

Coming from C++ Turbo Vision, the flag word families map like this:

C++ flag wordtvision-rs struct
sfXxx (state)State
ofXxx (options)Options
gfXxx (grow mode)GrowMode
dmXxx (drag mode)DragMode

The propagating subset of state flags a parent flips on a child during focus and activation is the StateFlag enum (Active, Selected, Focused, Dragging).

Geometry

A view's rectangle is two corners: Rect holds a top-left a (inclusive) and bottom-right b (exclusive), each a Point. Coordinates are i32: signed, because origins go negative when a view scrolls offscreen, and faithful to magiblot's widening of the historical short to int. Rect carries the familiar chained mutators (grow, intersect, plus r#move and r#union, raw-named to dodge the Rust keywords).

A view's origin is relative to its owner. The tree resolves the absolute position as it descends; there is no up-pointer to walk.

Groups are the branch nodes

A Group is a View that owns child views. It is the port of TGroup and the node type of the tree. The desktop, every window and every dialog are groups. A group:

  • owns its children in a Vec in back-to-front paint order: children[0] is the bottom (drawn first), children.last() is the frontmost (drawn last);
  • draws its children back-to-front (painter's algorithm, with no damage tracking: the whole tree redraws and a diff finds the changes);
  • routes events to them and tracks which child is current (focused).

Turbo Vision heritage: TGroup stored children in a circular next/prev ring with a per-child owner back-pointer. tvision-rs replaces this with a plain Vec and handle-based addressing; children have no up-pointer.

Because a child has no pointer back to its parent, cross-references use a ViewId handle instead of a raw pointer. Each view's id is minted when it is inserted into a group and stamped into its own ViewState; the framework resolves a handle back to a view by walking down from the group. This is also how a window addresses one of its controls, and how a leaf view reaches a sibling; see Cross-view brokering & ViewId.

Where to go next

The event loop in depth

tvision-rs runs the entire application on one non-recursive event loop in Program. Every event (keystrokes, mouse motion, modal dialogs, window drags, mouse hold-tracking) routes through a single pass called pump_once. Modality and press-and-hold are capture handlers stacked on a LIFO capture stack (see Cross-view brokering & ViewId and the capture section below). Because the whole tree is owned behind a single &mut, exactly one thing at a time may borrow it: the single loop enforces this structurally.

Turbo Vision heritage: the C++ library had many loops. execView spun a nested blocking getEvent loop for every modal dialog; dragView spun another while you dragged a window; a pressed button spun its own while you held the mouse. Each re-entered the framework and re-borrowed the view tree, which Rust forbids. Every one of those nested loop bodies is now a capture handler.

run is the only outer loop

Program::run is the whole application loop. It pumps until something sets an end command, then asks the tree to validate that command; if it validates, return, otherwise clear it and keep pumping:

// Illustrative sketch — not a standalone program.
loop {
    self.end_state = None;
    while self.end_state.is_none() {
        self.pump_and_drive();        // one event, fully processed
    }
    let es = self.end_state.unwrap();
    if self.valid_end(es) {           // tree-wide valid() walk
        return es;
    }
}

Turbo Vision heritage: this mirrors TGroup::execute's while (!valid(endState)) pattern.

run_app is the same loop with one addition: any Command that survives all view routing is handed to your callback. That is where menu commands like "open the color picker" get serviced. Most applications call one of these two and never touch the machinery below.

One pass: pump_once

pump_once is one pass of the single loop. Each call goes once through these phases, in order:

PhaseWhat happens
ResizeQuery the terminal size; if it changed, relayout the whole tree. There is no Event::Resize; the backend is polled live.
Settle currencyApply any pending insert-time focus cascades so the event about to be dispatched sees a fully settled focus state.
Pick an eventDrain the internal queue first, else poll the backend with the frame-tick timeout; an idle pick may synthesize a mouse auto-repeat.
IdleNo event: fire expired timers as Event::Timer, refresh the status line's help context.
Pre-routeA KeyDown (always) or a MouseDown on the status line is offered to the status line first, so accelerators like F10/Alt-X fire even under a modal.
The dispatch gateDrop the event if it is a disabled command; otherwise offer it to the capture stack, then to normal view routing.
Deferred drainApply every queued effect once, in insertion order.
Cursor + redrawSet the hardware cursor, then redraw the whole tree and diff it to the screen.

The dispatch gate

Before an event reaches a view it passes a small gate. A command that is currently disabled is dropped here. tvision-rs uses a denylist, so unknown custom commands flow through untouched (see Commands & events). What survives is offered to the capture stack first; only if no handler consumes it does it go to the normal view-tree walk (program_handle_event). A modal handler that consumes every otherwise-unhandled event is the modal loop. A timer expiry skips the capture stack: C++ delivers it from idle inside the getEvent of every hold loop, so a drag or an open menu must not swallow it.

While a modal view runs, program_handle_event does not use the root route for keys, commands, pastes and the mouse wheel. It hands them to the innermost modal view alone (CaptureStack::modal_view), as C++ TGroup::execute does, and drops a command the modal leaves unhandled. The program-level steps (menu bar hot keys, Alt+1..9, the Command::QUIT catch, Tile and Cascade, run_app's callback) see none of these events. Mouse clicks and broadcasts keep the root route; broadcasts reach the whole tree.

The deferred drain

A view is borrowed downward during dispatch as &mut dyn View plus a Context; it cannot reach back up to the loop-owned capture stack, command set, or sibling views. So instead of acting inline it queues the effect, and the pump applies the whole queue in one pass after dispatch: capture pushes, command enable/disable, bounds changes, modal close, focus moves, and the cross-view broker syncs. This is the Deferred channel; it has its own page, Deferred effects. Two rules matter here: the drain runs even when the pre-route consumed the event, and it runs once: anything an effect re-queues waits for the next pump (a loop-until-empty could spin).

Because capture pushes are deferred, a freshly pushed handler sees the next event, not the one that pushed it. The push and the first handled event are always separated by at least one pump boundary.

The capture stack

The CaptureStack is the LIFO list of CaptureHandlers that implements modality, dragging, press-and-hold, and menu sessions: anything that needs to intercept events globally before normal routing. Each handler is offered every event and returns a CaptureFlow:

  • Pass: not mine; offer it to the next lower handler, then to the view tree.
  • Consumed: handled; stop routing, stay on the stack.
  • ConsumedPop: handled, and remove myself (for example a modal closing).

The return value is authoritative. Handlers do not signal "consumed" by clearing the event. A handler holds a ViewId, never a view reference. Concrete handlers include a bounds-gating modal frame, window dragging and keyboard resize, mouse hold-tracking, and the menu session. Before every dispatch the pump re-syncs each bounds-gating handler from the live tree (sync_gate_bounds), so a dialog you have just dragged stays clickable in its new position.

The Phase field

A focused-event dispatch (a KeyDown or Command) visits three legs of the view tree in order: the pre-process children, the focused child, then the post-process children. A view that participates in more than one leg, or needs to know which leg it is on, reads ctx.phase().

The three values of Phase:

PhaseWhich viewsTypical use
PreProcessChildren with options.pre_process = trueAlt-letter accelerators (menu bar), global hot-keys
FocusedThe current child only (no option gate)Ordinary key handling, text input
PostProcessChildren with options.post_process = truePlain-letter hot-keys on buttons, check-boxes, labels

The group sets the phase on the shared Context before each leg and restores the previous value after it, so a nested group that re-enters the three-phase router always sees its own legs and never the outer group's:

// Sketch of what Group::handle_event does for focused events
// (src/view/group.rs — the three-phase router body).
ctx.set_phase(Phase::PreProcess);
for child in pre_process_children { child.handle_event(ev, ctx); }

ctx.set_phase(Phase::Focused);
current_child.handle_event(ev, ctx);

ctx.set_phase(Phase::PostProcess);
for child in post_process_children { child.handle_event(ev, ctx); }

ctx.set_phase(saved);   // restore for the outer group

A leaf handler reads the phase to decide whether to act:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::event::Event;
use tv::view::{Phase, View, ViewState, Context, DrawCtx};
struct MyButton { state: ViewState }
impl View for MyButton {
    fn state(&self) -> &ViewState { &self.state }
    fn state_mut(&mut self) -> &mut ViewState { &mut self.state }
    fn draw(&mut self, _ctx: &mut DrawCtx) {}
fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
    if let Event::KeyDown(k) = ev {
        match ctx.phase() {
            Phase::PreProcess => {
                // Alt-letter accelerator: fires before the focused view sees it.
                if tv::is_alt_hotkey(k, 'O') { ev.clear(); /* open */ }
            }
            Phase::Focused => {
                // Focused key: Enter / Escape handled here.
                if k.key == tv::Key::Enter { ev.clear(); }
            }
            Phase::PostProcess => {
                // Plain-letter hot-key: fires after the focused view.
                if tv::is_plain_hotkey(k, 'O') { ev.clear(); }
            }
        }
    }
}
}
}

Sources: Phase in src/view/view.rs; Context::phase / set_phase in src/view/context.rs; the router body in src/view/group.rs.

Turbo Vision heritage: ports phaseType (views.h). In the C++ code the phase was an owner field (owner->phase); because tvision-rs views have no up-pointer the phase rides the Context instead (deviation D4).

Cursor shape: insert vs overwrite

When a view wants to show a hardware cursor it sets State::cursor_vis (via ViewState::show_cursor) and also sets the cursor shape: the normal caret for the insertion point (normal_cursor, the default) or a block for overwrite mode (block_cursor), controlled by State::cursor_ins.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::view::{View, ViewState, Context, DrawCtx};
use tv::event::Event;
struct MyEditor { state: ViewState, insert_mode: bool }
impl View for MyEditor {
    fn state(&self) -> &ViewState { &self.state }
    fn state_mut(&mut self) -> &mut ViewState { &mut self.state }
    fn draw(&mut self, _ctx: &mut DrawCtx) {}
fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
    if let Event::KeyDown(k) = ev {
        if k.key == tv::Key::Insert {
            self.insert_mode = !self.insert_mode;
            if self.insert_mode {
                self.state.normal_cursor();   // normal caret = insert point
            } else {
                self.state.block_cursor();    // block = overwrite
            }
            ev.clear();
        }
    }
}
}
}

After each pump_once the event loop walks the current-child chain from the root group downward via Group::cursor_request to find the deepest focused view that has cursor_vis = true. The result (or None if no view wants a cursor) is placed on the renderer before the redraw step:

// src/app/program.rs — end of pump_once
let cursor = group.cursor_request()   // descends through current children
    .filter(|p| root_extent.contains(*p)) // hidden past the screen edge
    .map(|p| p + group_origin)
    .map(|p| (p.x.max(0) as u16, p.y.max(0) as u16));
renderer.set_cursor(cursor);
renderer.set_caret_size(group.caret_size()); // same chain: block or normal
renderer.render(|buf| { /* whole-tree redraw */ });

View::caret_size follows the same current-child chain and reads cursor_ins on the focused view: CARET_INSERT (100, a block) when it is set, else CARET_NORMAL (1). While the cursor is shown, the renderer passes this size to Backend::set_caret_size. The crossterm backend shows CARET_INSERT as a blinking block and keeps the terminal's own caret shape for CARET_NORMAL, as the original's ncurses display does. It restores the terminal's caret shape on exit and suspend.

A view that wants no cursor leaves cursor_vis = false; it never calls show_cursor. A view that loses focus keeps whatever cursor_vis value it had, but the walk only descends through focused children, so the cursor is hidden until the view is focused again.

The walk also clips the cursor, as C++ TVCursor does. Each group on the chain returns None when it or its current child is hidden, when the cursor lies outside the child's extent, or when a visible sibling above the child in Z-order covers the cursor cell. So the cursor disappears when it is scrolled out of its field, when it is outside the window that holds it, past the screen edge, or under another window.

Sources: State::cursor_ins / block_cursor / normal_cursor / View::caret_size in src/view/view.rs; Group::cursor_request / Group::caret_size in src/view/group.rs; resetCursor walk in src/app/program.rs.

Turbo Vision heritage: ports sfCursorVis and sfCursorIns from views.h. The TView::resetCursor tree-walk is realized by Group::cursor_request, and TVCursor::decideCaretSize by View::caret_size.

Marking an event handled

A handler signals "I consumed this event, stop routing" by calling ev.clear() on the &mut Event it received. clear() sets the event to Event::Nothing, the consumed-event sentinel. Every subsequent routing step first tests ev.is_nothing() and skips the delivery if true, so no further handler sees it.

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::event::Event;
use tv::view::{View, ViewState, Context, DrawCtx};
struct MyView { state: ViewState }
impl View for MyView {
    fn state(&self) -> &ViewState { &self.state }
    fn state_mut(&mut self) -> &mut ViewState { &mut self.state }
    fn draw(&mut self, _ctx: &mut DrawCtx) {}
fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
    match ev {
        Event::Command(cmd) if *cmd == tv::command::Command::OK => {
            // Handle it, then consume so no other handler sees it.
            ev.clear();
        }
        _ => {}   // unhandled — leave ev alone; it will propagate
    }
}
}
}

"Who handled it" is recorded in-place on the event. There is no shared flag and no out-of-band consumed signal. After routing returns to the caller, an ev.is_nothing() test tells the caller whether anything consumed the event.

Sources: Event::clear / Event::is_nothing / Event::Nothing in src/event/mod.rs.

Turbo Vision heritage: ports clearEvent (views.h). The C++ convention was to assign what = evNothing; ev.clear() is the idiomatic Rust spelling of the same thing.

Background work each idle pass

An idle pass is a pump_once call where the backend returned no event and no mouse auto-repeat was due: the None => arm in the event-pick step. Idle passes occur at the frame-tick cadence (roughly 20 ms) whenever the user is not typing or moving the mouse.

On an idle pass the pump does three things before falling through to the normal redraw:

  1. Fires the command-set-changed broadcast. If the enabled/disabled command set changed since the last broadcast, a Command::COMMAND_SET_CHANGED broadcast is queued so buttons and menu items can re-gray themselves.
  2. Drains expired timers. Each timer whose deadline has passed is collected and queued as a typed Event::Timer(id). A view matches the id against its own timer handles to know which timer fired.
  3. Refreshes the status line. The status line gets the current help context, so it can show the items for that context. The help context comes from the open menu, if a menu is open. Otherwise it comes from the topmost modal view. With no modal view open, it comes from the application root, which follows the focus chain down to the focused view.

After pump_once returns, the outer pump_and_drive fires the optional idle hook registered with Program::set_on_idle:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
fn _demo(program: &mut tv::app::Program, rx: std::sync::mpsc::Receiver<String>) {
let refresh = tv::Command::custom("myapp.refresh");
program.set_on_idle(move |p| {
    // Called on every idle pass — roughly every 20 ms with no user input.
    // Keep this callback cheap: it runs on the loop's frame cadence.
    let mut got_data = false;
    while let Ok(_line) = rx.try_recv() {
        // ... store the line in state the views share ...
        got_data = true;
    }
    if got_data {
        p.broadcast(refresh, None); // only when there is something new
    }
});
}
}

The hook gets &mut Program. To reach the views it queues events: Program::broadcast(command, source) queues a broadcast, and Program::put_event(ev) queues any event. The hook does not dispatch them itself. The next pump pass takes the queued event before it polls the backend, and routes it like an input event. In C++, idle() sends its broadcasts at once with message(); here they arrive one pump pass later.

Only one idle hook is held at a time; a second set_on_idle call replaces the first. The hook fires during any loop level, including while a modal dialog is open, because pump_and_drive drives both the outer and inner (exec_view) loops.

For exact timing, meaning actions that must fire at a specific wall-clock instant, register a timer with Context::set_timer instead. The timer expires at the exact deadline and arrives as Event::Timer on an idle pass.

Sources: the None => arm of pump_once and Program::set_on_idle in src/app/program.rs.

Turbo Vision heritage: idle-pass logic ports TProgram::idle (tprogram.cpp). The idiomatic successor to overriding TProgram::idle is Program::set_on_idle.

Where events come from

Every event in tvision-rs enters the loop through a single acquisition path inside pump_once:

  1. Internal queue first. out_events (a VecDeque) is drained before polling the backend. Timer expirations, command re-posts, and events injected by capture handlers or deferred effects all land here and are processed in first-in-first-out order on the next pump passes.
  2. Backend poll if the queue is empty. renderer.backend_mut().poll_event(timeout) blocks for up to timeout (the frame-tick, typically 20 ms) and returns the next terminal event, or None on timeout.
  3. Mouse-auto synthesizer. If both the queue and the backend returned None, and a mouse button is held, MouseAutoState::synthesize may produce a synthetic Event::MouseAuto at the configured repeat cadence.
// src/app/program.rs — the event-pick step (pump_once, step 3)
let ev = match out_events.pop_front() {
    Some(e) => Some(e),
    None    => renderer.backend_mut().poll_event(timeout),
};
let ev = match ev {
    Some(e) => { mouse_auto.observe(&e, now); Some(e) }
    None    => mouse_auto.synthesize(now),
};

There is no app-level override of this path. Instead:

  • Periodic work: set_on_idle or a timer (Context::set_timer).
  • Inject an event programmatically: push to the internal queue (out_events.push_back(ev)) from a deferred effect or from top-level code.
  • Deterministic test events: push events to the HeadlessBackend's queue; poll_event pops them without blocking.

Sources: pump_once (the event-pick and mouse-auto steps) in src/app/program.rs.

Turbo Vision heritage: ports the role of TProgram::getEvent (tprogram.cpp). There is no virtual getEvent override point; the idiomatic substitutes are the timer queue, set_on_idle, and the headless event queue for tests.

Where to go next

Deferred effects

When a view handles an event, it can read and mutate itself freely, since it holds &mut self. What it cannot do is reach up or sideways through the view tree. During dispatch the tree is a live &mut borrow stack (root → desktop → window → the view being handled). Every ancestor above the current view is already &mut-borrowed on that stack, and a fresh find_mut(id) from the root would alias it. The borrow checker forbids it, by design: it makes the Turbo Vision "a view can call up its owner chain" pattern impossible to do unsafely.

So any action a view wants that touches loop-owned state it cannot borrow inline is deferred. The view does not perform the effect. It requests it through its Context, and the event loop applies it after dispatch unwinds and the root is free again.

What "loop-owned state" means

A downward-borrowed view cannot reach:

  • the program's capture stack (modal frames, drag handlers, menu sessions),
  • the command set (enable/disable, which the menus and status line mirror),
  • any other view addressed by ViewId, such as a parent, a sibling scrollbar, the clipboard editor in another window,
  • the modal loop itself (ending it with a result command).

A view that wants to move itself, close itself, focus a sibling, or end a modal dialog asks the loop to do it.

The Deferred queue

Context carries a single &mut Vec<Deferred>. The request methods on Context (request_close, request_bounds, request_focus, end_modal, enable_command, the scrollbar brokers, …) each push one Deferred variant onto it. The view never sees the apply step.

After the dispatch returns, pump_once takes the queue (std::mem::take, so any effect that itself queues a follow-up lands on the next pump, not this drain) and walks it once, in insertion order. Each variant matches to an arm that now holds the loop-owned state the view could not:

// Illustrative sketch — not a standalone program.
let effects: Vec<Deferred> = std::mem::take(deferred);
for effect in effects {
    match effect {
        Deferred::PushCapture(h)      => captures.push(h),
        Deferred::EnableCommand(cmd)  => { /* mutate the live command set */ }
        Deferred::ChangeBounds(id, r) => { if let Some(v) = group.find_mut(id) { v.change_bounds(r); } }
        Deferred::Close(id)           => { /* remove from the owning group */ }
        Deferred::EndModal(cmd)       => { /* set Program::end_state */ }
        Deferred::OpenModal { view, requester, then_command } => {
            // View-launched modal: stash into pending_modal with RouteModalAnswer
            // completion; pump_and_drive runs it via the existing exec_view machinery.
            // On close the pump delivers the modal's value() to `requester` via
            // View::set_modal_data (not on cancel), then the close command via
            // View::set_modal_answer, and re-injects `then_command`.
            /* program.pending_modal = Some((view, RouteModalAnswer { answer_to: requester, then_command, deliver_data: true })) */
        }
        // … one arm per variant
    }
}

The variants fall into a few disjoint families by which state they touch: capture stack, command set, view tree, loop end_state. Because no single dispatch ever queues two conflicting effects on the same piece of state, draining in insertion order is order-equivalent: same-family items keep their relative order, and cross-family order never changes the result. One ordering fact is load-bearing: PushCapture applies after dispatch, so a freshly pushed handler sees the next event, never the one that pushed it.

This drain lets a button request end_modal(Command::OK) from deep inside a dialog, a window request its own Close, a dragged frame request new ChangeBounds, a scroller stay in sync with a sibling scrollbar it can never touch directly, and a list view launch a custom modal via OpenModal (reusing the existing modal machinery). The cross-view (ViewId-addressed) cases are the subject of Cross-view brokering & ViewId; the drain's place in the loop is in The event loop in depth.

Adding a new deferred effect

With the single-enum design a new capability is additive and local: it changes no signature and no call site. To add one:

  1. Add a variant to Deferred, carrying whatever data the apply step needs (typically a ViewId plus parameters). Note which state family it touches.
  2. Add a request method to Context that pushes that variant. This is the view-side entry point.
  3. Add the match arm to the pump_once drain that performs the effect against the now-reachable loop-owned state.

Posted events and broadcasts stay outside the queue. They are not deferred effects: they feed back into the input stream and are routed as events at the top of the next pump instead of being applied to state at the bottom of this one. Deferred means "mutate loop/tree state after this dispatch"; posting means "produce an event to route later."

The conceptual rationale and the C++ patterns each variant replaces are covered from the porting angle in The Deferred channel.

Cross-view brokering & ViewId

A scroller needs to know how far its scrollbars have moved; a list box needs to push its position back into them. In tvision-rs, ownership is a downward tree of Box<dyn View>, and every up- or sideways link is a handle, a ViewId, in place of a raw pointer. The event loop resolves handles and performs the actual cross-view reads and writes at a safe point when no other borrow is active. See Pointers & infoPtr → handles for the broader handle design.

Turbo Vision heritage: in C++ the two views held raw TView* pointers at each other and called across directly. Rust forbids that aliased mutable access; the broker pattern replaces it.

ViewId as identity

A ViewId is a Copy, globally-unique identity: internally one NonZeroU64, minted from a single monotonic process counter when a view is inserted into its group (Group::insert), and stamped into the view's own ViewState. It is not an index into any store. You can stash it freely (in a sibling link, a focus stack, a capture handler) because it borrows nothing. Use Option<ViewId> for "no link"; the NonZeroU64 gives that a free niche, so it costs no extra size.

Resolving a handle back to the live view is a tree-walk: View::find_mut(id) recurses through the groups and hands back a &mut dyn View, or None. A handle whose view has since been removed resolves to None. There is no dangling slot to alias, so no generational validation is needed.

Why a leaf can't reach its sibling

During event handling a leaf view holds only &mut Context (the downward borrow). It cannot reach back up to its parent group, let alone sideways to a sibling: the borrow checker would be holding two &mut into the same tree. So a scroller that wants to read its scrollbars, or write new parameters into them, has no inline way to do it.

The pump is the broker

The leaf does not act directly. It requests the cross-view read or write as a deferred effect, and the event loop, which owns the whole tree, performs it at deferred-apply time, when the entire tree is reachable through the root group. The pump is the broker.

The pattern is the same each time: resolve each participant in its own find_mut, so only one &mut is live at a time, then either call through the View trait (virtual dispatch) or downcast to the concrete type via as_any_mut() depending on what the effect needs.

// Illustrative sketch — not a standalone program.
// At deferred-apply, inside the pump, `group` is the whole tree:
let hv = h_bar_id
    .and_then(|id| group.find_mut(id))   // resolve one bar
    .and_then(|view| view.value())       // read its value via the value protocol
    .and_then(field_int);                // -> Option<i32>
// ...read the v-bar the same way, then call the target through the View trait:
if let Some(view) = group.find_mut(target) {
    view.apply_scroll_sync(hv, vv, &mut ctx);  // virtual dispatch — no downcast
}

Reads cross the seam through the value protocol (View::value() → FieldValue::Int), so the broker never needs to know the sibling's concrete type to read a number. Writes use a defaulted View trait method when the effect can be expressed generically. The callee overrides what it needs without the pump knowing the concrete type.

The scroll-family read-syncs (Scroller, all list-viewer variants, Outline viewer, and Editor) share a single hook View::apply_scroll_sync(h, v, ctx) and a single deferred variant Deferred::ScrollSync { target, h, v }. Each widget overrides apply_scroll_sync to interpret the Option<i32> deltas per its own semantics (Scroller and Outline use unwrap_or(0); Editor preserves None to skip an axis). For composite widgets such as the text editor, the #[delegate(to = field)] macro forwards apply_scroll_sync to the inner view automatically, so the pump calls it without knowing the wrapper.

Two further syncs, Deferred::IndicatorSetValue and Deferred::PageStackSync, are also downcast-free but keep their own hooks (View::set_indicator_value and View::apply_page_sync) because their payloads are not scroll deltas and the shared (h, v) hook would not fit (§2.1).

A downcast (as_any_mut() + downcast_mut) is used only where the effect requires the concrete struct and no trait hook fits: ScrollBarSetParams (the write direction, scroller → ScrollBar) and SplitterDivider (Splitter's divider-move op). These remain as downcast sites by design.

Each cross-view interaction is its own deferred variant (ScrollSync, ScrollBarSetParams, IndicatorSetValue, PageStackSync, and so on), so adding a new brokered relationship means adding a variant instead of threading a new pointer.

Avoiding feedback loops

A read-sync that writes back (the list viewer pushes its new position into the v-bar) could re-enter forever. It does not, because the scrollbar's parameter setter, ScrollBar::set_params, is change-guarded: it re-broadcasts cmScrollBarChanged only when the value actually changes. Writing back the value the bar already holds is a silent no-op, and the cycle goes quiet on the next pump.

Broadcast as a message

Beyond the scroller/list synchronization use-case, broadcasts are the general "shout to the tree" primitive in tvision-rs. Any view can post a broadcast via Context::broadcast(command, source) and any other view can handle it. The canonical pattern has two flavors:

1. "Who handled this?" probe: a broadcast where the sender watches whether any recipient clears the event. The scroller itself uses this: it does not clear cmScrollBarChanged on receipt (it returns at once); the broadcast propagates to every child in the group. Another common probe is cmCommandSetChanged: the status line and menu bar handle it to regray their items without any explicit callback.

2. "Find topmost of type": a broadcast cleared by the first handler that matches some condition. Because broadcasts are delivered top-to-bottom (frontmost child first), the highest Z-order handler wins:

// Post a broadcast; clear it in the handler that claims it:
ctx.broadcast(Command::MY_QUERY, None);

// In a view's handle_event:
if let Event::Broadcast { command, .. } = ev {
    if *command == Command::MY_QUERY {
        // Handle, then consume so lower views don't see it.
        ev.clear();
    }
}

Because "consumed" in tvision-rs means Event::Nothing (clearing the event in place, no return value), there is no separate "handled" flag to check. If the event is still live after the delivery, it was not handled by any child.

A broadcast also carries an optional source: Option<ViewId>, which names the subject of the broadcast. The sender is not recorded there. The scrollbar sets itself as source when it broadcasts cmScrollBarChanged; a scroller with two bars uses source to tell which bar fired without downcasting.

The "find the right one" idiom uses this filtering:

// Inside a view that reacts to its own scrollbar and ignores the other:
if let Event::Broadcast { command, source }  = ev {
    if *command == Command::SCROLL_BAR_CHANGED && *source == Some(self.v_scroll_bar_id) {
        // This is our bar — handle the scroll.
        // Do NOT clear — broadcasts are conventionally left live.
    }
}

Leaving the broadcast live is deliberate. Several handlers can react to one broadcast, and the loop delivers it to every child. A handler that does clear a broadcast uses it as a "claim" signal. Both patterns are valid; the convention for pure-notification broadcasts is to leave them live.

Source: src/view/context.rs (Context::broadcast), src/view/group.rs (broadcast arm of route_event).

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.

Writing your own View

Everything on the screen is a View: a button, a window, the desktop background. This page closes the How It Works part. Once you can write a View, the rest of the framework is a set of ready-made views you can use or replace. The page walks the path twice: first a trivial leaf built from scratch, then how to wrap an existing widget and let a macro write the boilerplate.

The shape of a view

Every widget in tvision-rs combines two parts: a View trait that the framework calls, and a ViewState struct you embed to carry the per-view data: geometry, the state/option flags, the help context. You embed a ViewState field in your struct and impl View for your type. See Inheritance → trait + composition for the full background.

The trait has exactly three methods you must supply: state, state_mut, and draw. Every other method (handle_event, set_state, value, calc_bounds, …) has a default, so a static, non-interactive view needs only those three. The first two are pure boilerplate that hands back the embedded state, so in practice the only code you write is draw plus whatever behaviour you want to customise.

A trivial leaf view

Here is a complete view that fills its rectangle and prints a centered label, following the same pattern the real StaticText widget uses:

#![allow(unused)]
fn main() {
use tvision_rs::{DrawCtx, Rect, Role, View, ViewState};

#[allow(dead_code)]
struct Banner {
    state: ViewState,
    text: String,
}

#[allow(dead_code)]
impl Banner {
    fn new(bounds: Rect, text: impl Into<String>) -> Self {
        Banner { state: ViewState::new(bounds), text: text.into() }
    }
}

impl View for Banner {
    fn state(&self) -> &ViewState { &self.state }
    fn state_mut(&mut self) -> &mut ViewState { &mut self.state }

    fn draw(&mut self, ctx: &mut DrawCtx) {
        let style = ctx.style(Role::StaticText);
        // Paint the whole view-local extent, then write the label.
        ctx.fill(self.state.get_extent(), ' ', style);
        let x = (self.state.size.x - self.text.chars().count() as i32) / 2;
        ctx.put_str(x, 0, &self.text, style);
    }
}
}

Points to note:

  • Construct state with ViewState::new(bounds), never ViewState::default() for a real view. new applies the correct initial defaults (visible, the dmLimitLoY drag limit). An all-zero state would be invisible.
  • Draw in view-local coordinates. DrawCtx clips and offsets for you; the view's own extent is always 0,0 .. size.x,size.y (get_extent).
  • Colors come from a Role. There are no palette indices. Ask the theme for a role and get a Style back. See Theming & colors.

Insert it into a group (a window, the desktop) and the event loop draws it on the next pump. A leaf that overrides nothing else is inert: it ignores events, carries no transferable value, and is not selectable.

Adding behaviour

To react to input, override handle_event (the base is a no-op and the event passes through). A leaf cannot mutate loop-owned state directly; it asks for an effect through its &mut Context. Closing yourself, enabling a command and focusing a sibling all go through the Deferred channel, and cross-view reads/writes through brokering. Match on the Event enum (see Events → enum + match) and clear the event once you have consumed it so it does not route further.

Other commonly overridden hooks: value / set_value to make a data control that participates in dialog gather/scatter, size_limits to impose a minimum size, and set_state to react when you gain or lose focus. A view that launches a modal and needs its typed result overrides set_modal_data to load the ordered FieldValue::List the pump read out of the modal's fields via View::value(). This is virtual dispatch with no framework downcast (see Dialogs & data § Delivering a modal's result).

Wrapping an existing view: #[delegate]

Most "custom views" specialise an existing widget instead of starting from bare ViewState. To do that in tvision-rs you embed the widget (for example a Dialog) and impl View for your wrapper type. The View trait has roughly two dozen methods, and every one you did not override has to be forwarded to the inner field. The #[delegate] macro writes those forwarders.

Turbo Vision heritage: in C++ you would subclass (class MyDialog : public TDialog) and inherit every virtual method for free. Rust has no inheritance; embed-and-delegate via #[delegate] is the equivalent.

Re-exported as tvision_rs::delegate, it goes on the impl View block: write only the methods that differ, and the macro injects a forwarder (self.<field>.method(args)) for every method you did not write.

#![allow(unused)]
fn main() {
use tvision_rs::delegate;
use tvision_rs::{DrawCtx, Scroller, View};

#[allow(dead_code)]
struct MyTerminal {
    scroller: Scroller,
}

#[delegate(to = scroller)]
impl View for MyTerminal {
    // Only the methods that differ are written by hand…
    fn draw(&mut self, ctx: &mut DrawCtx) { /* custom rendering */ }
    // …everything else (state, state_mut, handle_event, calc_bounds, …)
    // is forwarded to `self.scroller` automatically.
}
}

Do not return a ViewState of your own from state/state_mut in a #[delegate] impl: the inner field owns the view's one ViewState, and every forwarded method (set_state, change_bounds, calc_bounds, ...) works on it. A state that returns a field of your wrapper would be a second state those methods ignore: the view would receive keys while state().state.focused stays false. The macro rejects such an override at compile time (a plain self.scroller.state() forwarder is accepted, but redundant).

The attribute reads the trait name from the impl Trait for Type line and the field from to = <field>; it never needs the method list spelled out. A skip(method, …) clause leaves a named method at its trait default instead of forwarding it. This is for cases where forwarding would be wrong (for example a wrapper whose own size_limits must win over the inner group's). The full rationale, including the path resolution that makes generated forwarders compile under any consumer alias, is in the design note docs/design/delegation-macros.md.

If you add a new defaulted method to the View trait itself, you must also add it to the macro's spec table (tvision-rs-macros/src/specs.rs). Otherwise delegating types silently fall back to the default instead of forwarding. The required methods are caught at compile time; defaulted ones are not. As a consumer writing your own views you will rarely touch the trait, so this is mainly a note for the library's own maintainers.

Local and global coordinates

A view always draws in its own local coordinate space: the top-left corner of its own extent is (0, 0). When the router delivers a mouse event down the tree, it subtracts each child's origin as it descends, so the position you receive in handle_event is already local. There is no public make_local / make_global helper; the subtraction lives inside Group::route_event (src/view/group.rs):

// Inside route_event, before delivering to child i:
ev.offset(-child.origin.x, -child.origin.y);

This means a MouseDown arriving at (35, 7) in the parent's space arrives as (3, 2) in a child whose origin is (32, 5). Converting a position you received in handle_event back to the parent's space (for example to hit-test against a sibling) means adding your own origin:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{Event, View, ViewState};
struct MyView { state: ViewState }
impl View for MyView {
  fn state(&self) -> &ViewState { &self.state }
  fn state_mut(&mut self) -> &mut ViewState { &mut self.state }
  fn draw(&mut self, ctx: &mut tv::DrawCtx) {}
fn handle_event(&mut self, ev: &mut Event, ctx: &mut tv::Context) {
    if let Event::MouseDown(m) = ev {
        // m.position is already in this view's local space.
        let local = m.position;
        // Convert to parent (owner) space, e.g. to compare with a sibling's bounds:
        let in_owner = local + self.state.origin;
        let _ = in_owner;
    }
}
}
}

Because DrawCtx also clips to the view's own extent, you can write to any position within 0 .. size without affecting neighboring views.

Turbo Vision heritage: TView::makeLocal / makeGlobal walked the owner chain to convert between coordinate spaces. In tvision-rs the router handles the descent; there is no equivalent pair of methods because views have no up-pointer to walk back up.

Overriding set_state

The framework flips a small set of StateFlags on a view during focus and activation: Active, Selected, Focused, Dragging, Visible. To react when one of these changes, override View::set_state. The default implementation sets the flag on ViewState and, for Focused, broadcasts RECEIVED_FOCUS / RELEASED_FOCUS. Always call through to the inner/default behaviour first so the flag is set before your side effects run:

#![allow(unused)]
fn main() {
use tvision_rs as tv;
use tv::{Context, Event, Role, StateFlag, View, ViewState};
struct MyView { state: ViewState }
impl View for MyView {
  fn state(&self) -> &ViewState { &self.state }
  fn state_mut(&mut self) -> &mut ViewState { &mut self.state }
  fn draw(&mut self, _ctx: &mut tv::DrawCtx) {}
fn set_state(&mut self, flag: StateFlag, enable: bool, ctx: &mut Context) {
    // 1. Let the base update the flag and broadcast focus events.
    self.state.set_flag(flag, enable);
    if flag == StateFlag::Focused {
        let source = self.state.id();
        ctx.broadcast(
            if enable { tv::Command::RECEIVED_FOCUS } else { tv::Command::RELEASED_FOCUS },
            source,
        );
    }
    // 2. React to the new state — e.g. enable/disable a command when focus changes.
    //    The framework's whole-tree redraw picks up the changed state automatically;
    //    no explicit draw call is needed.
    if flag == StateFlag::Focused && enable {
        ctx.enable_command(tv::Command::OK);
    }
}
}
}

The same pattern lets you disable a command while unfocused (call ctx.disable_command) or show/hide sibling views (via ctx.request_set_visible(sibling_id, enable)). Because you hold only &mut Context and no &mut Group, effects that reach beyond this view go through the deferred channel. See Deferred effects for the full list.

Source: src/view/view.rs (View::set_state default), src/view/group.rs (Group::set_state propagation to children).

A custom view's colors

Colors come from a Role; raw palette indices are not used. Ask DrawCtx for a role and get back a Style, a foreground/background color pair with optional modifiers:

#![allow(unused)]
fn main() {
use tvision_rs::{DrawCtx, Rect, Role, View, ViewState};

#[allow(dead_code)]
struct Highlighted { state: ViewState }

impl View for Highlighted {
    fn state(&self) -> &ViewState { &self.state }
    fn state_mut(&mut self) -> &mut ViewState { &mut self.state }

    fn draw(&mut self, ctx: &mut DrawCtx) {
        // Pick a role appropriate to the widget's semantic meaning.
        let normal = ctx.style(Role::Normal);
        let focused = ctx.style(Role::Focused);
        let style = if self.state.state.focused { focused } else { normal };
        ctx.fill(self.state.get_extent(), ' ', style);
    }
}
}

The Role enum is closed; all roles are first-party. The mapping from role to Style lives in the active Theme. Custom views pick the role closest to their semantic meaning:

Widget kindGood starting role
Background / fillerRole::Normal
Focused editable fieldRole::Focused
Inactive editable fieldRole::Normal
Caption / labelRole::StaticText
Frame (active window)Role::FrameActive
Frame (passive window)Role::FramePassive
Disabled controlRole::Disabled

For more on how roles map to colors and how to swap themes at runtime, see Theming & colors. Source: src/theme.rs, src/color.rs.

Turbo Vision heritage: C++ views looked up a palette-index entry (mapColor) and received a raw terminal attribute byte. tvision-rs replaces every palette lookup with a named Role (deviation D7), so swapping the whole theme repaints the UI without any per-widget change.

Where to go next

  • The view tree: how groups own and lay out their children.
  • Deferred effects: how a leaf requests changes to loop state.
  • Controls: the ready-made views you will reach for before writing your own.
  • Theming & colors: the full role catalog and how to build a custom theme.

How the API docs are organized

The API reference is the per-type half of this site: every public struct, trait, enum, and method, generated by rustdoc straight from the source. The Guide you are reading now explains the ideas; the API reference is where you look up the exact signature. Use the Guide ⇄ API toggle in the top bar to move between them. Type names in the Guide link to their rustdoc page.

The module map

The crate is laid out as one module per concern. The reference for a type lives in the module that owns it, so once you know the layout you can navigate by guessing. Everything below is also re-exported at the crate root (so use tv::Button works); the documentation lives in the owning module:

ModuleWhat lives there
appProgram, Application, the run loop
viewthe View trait, ViewState, Context, Deferred
widgetsthe controls: Button, check boxes, radio buttons, input lines, labels, list boxes, tables, scroll bars, editors
windowWindow and its scroll-bar options
dialogdialogs, message boxes, gather/scatter
desktopthe Desktop and its background
menumenu bar and pull-down menus
statusthe status line and its help-context ranges
eventthe Event enum and Key
commandCommand and CommandSet
themeTheme and Role
keymapconfigurable key mapping
validateinput-line validators
datathe FieldValue value protocol
screenDrawBuffer, Cell, the cell buffer
backendthe Backend trait, CrosstermBackend, HeadlessBackend

The remaining modules (capture, color, frame, help, text, timer) hold the supporting machinery the chapters in How It Works walk through.

Finding a type

  • Follow a Guide link. Every type the Guide names is a link into the reference.
  • Use the rustdoc search box (press S, or click the search field). Type a name, for example Button or set_value, and rustdoc jumps to it.
  • Start at the crate root and drill down by module if you want to browse what a concern offers.

Coming from C++ Turbo Vision?

If you are translating a known TXxx class or cmXxx/sfXxx constant, go via the symbol map, a lookup table from the C++ name to the tv:: type, which then links into the reference. The reasoning behind each rename lives in The Idiomatic Port.

C++ Turbo Vision → tv:: symbol map

A lookup table for translating a C++ Turbo Vision symbol into its tvision-rs equivalent (the tvision-rs crate, imported as tv). This is the what; the why lives in The Idiomatic Port and the summary in Differences from C++ Turbo Vision.

Two mechanical rules cover most of the table:

  • Drop the T prefix and namespace under tv::: TButton → tv::Button.
  • cmFoo / hcFoo constant families become associated consts on an open newtype: cmOK → tv::Command::OK, hcNoContext → tv::HelpCtx::NO_CONTEXT.

Core types

C++ Turbo Visiontvision-rs (Rust)notes
TViewView (trait) + ViewState (data)behaviour is a trait; data is composed in, not inherited
TGroupGroupowns Vec<Box<dyn View>>
TFrameFrame
TWindowWindow
TDialogDialog
TDeskTopDesktop
TProgramProgramthe engine: tree + event loop + backend
TApplicationApplicationthin wrapper over Program

See The application skeleton for the Program / Application split.

Controls & widgets

C++ Turbo Visiontvision-rs (Rust)
TButtonButton
TStaticTextStaticText
TParamTextParamText
TLabelLabel
TInputLineInputLine
TClusterCluster
TCheckBoxesCheckBoxes
TRadioButtonsRadioButtons
TScrollBarScrollBar
TScrollerScroller
TListViewerListViewer (trait)
TListBoxListBox
TSortedListBoxSortedListBox
TOutlineOutline / OutlineViewer
TEditorEditor
TEditWindowEditWindow
TMenuBarMenuBar
TMenu / TMenuItemMenu / MenuItem
TStatusLine / TStatusItemStatusLine / StatusItem
TValidator familyValidator trait + impls

The full set is in Controls and Menus, status line & help.

Events, keys & commands

C++ Turbo Visiontvision-rs (Rust)notes
TEvent / event.what == evXEvent enum, matchedevKeyDown → Event::KeyDown(..), evCommand → Event::Command(..)
KeyDownEventKeyEvent
MouseEventTypeMouseEvent
kbEnter, kbF1, …Key enum (Key::Enter, Key::F(1))combined codes decompose
kbCtrlC, kbShiftTabbase Key + KeyModifiersKey::Char('c') + ctrl
clearEvent(event)*ev = Event::Nothing
cmOK, cmCancel, …Command assoc constsopen newtype, namespaced
TCommandSet (256-bit)CommandSetProgram stores the disabled set (denylist)
message(rcvr, evBroadcast, cmX, p)ctx.broadcast(Command::X, source)source: Option<ViewId> stands in for p; queued, not synchronous
putEventctx.put_event(ev); from outside a view Program::put_event / Program::broadcastevents queue in order; none is overwritten
TEventQueue::doubleDelayProgram::set_double_delay_msdefault 440 ms
message(...) expecting a resulttargeted query → Option<T>

How events route is covered in Events → enum + match and Commands & events.

State, options & layout flags

The ushort flag words become named booleans, reached through the Context and a view's ViewState.

C++ Turbo Visiontvision-rs (Rust)
state & sfFocusedself.state().focused / StateFlag::Focused
options & ofSelectableself.state().options.selectable (Options)
growMode / dragModeGrowMode / DragMode
helpCtx / hcNoContextViewState.help_ctx / HelpCtx::NO_CONTEXT
owner / current / selectedViewId handles

The flag-word translation is detailed in Flag words → struct-of-bools, the handle model in Pointers & infoPtr → handles.

Color, drawing & backend

C++ Turbo Visiontvision-rs (Rust)notes
getColor / getPalettectx.theme.style(Role::…)Role / Theme
TColorAttrStyle
TColorDesiredColor4-variant enum
hardcoded glyph tablesfields on theme::Glyphs, via ctx.glyphs()
TDrawBufferDrawBuffer
THardwareInfo / TScreenBackend traitCrosstermBackend / HeadlessBackend

See Palettes & glyphs → Theme/Role, The draw model, and Drawing & backends.

C++ Turbo Visiontvision-rs (Rust)notes
execView (from a Program/Application method)Program::exec_view_withresult returned by value from an extract closure
execView (from within a view's handleEvent)Context::request_exec_viewqueues Deferred::OpenModal; record (getData) routed to requester via View::set_modal_data unless cancelled, close command via View::set_modal_answer
dragView / press-trackingcapture-stack handlerssee The event loop
getData / setData / dataSizetyped value / set_valuecurrency is FieldValue

The modal model is in Modal execView → one loop + capture, the data protocol in Dialogs & data.

Dropped or replaced

C++ Turbo Visiontvision-rs (Rust)
drawHide / drawShow / drawUnder* / buffered groupdropped (whole-tree redraw + diff)
TStreamable / TResourceFiledropped (serde if revived)
TColorDialog and its selector classesreplaced by ColorPicker / Program::color_dialog
forEach / firstThat / TSortedCollectioniterators / Vec<T: Ord>

Rationale for each removal is in Dropped & changed.


Anything not in this table ports verbatim: same name (minus the T), same method, same behaviour. For the differences that do change a symbol, see Differences from C++ Turbo Vision. Types and methods with no C++ counterpart, such as Table, Splitter or Keymap, are not in this table; they are listed on Extensions beyond Turbo Vision.

Differences from C++ Turbo Vision

tvision-rs is a faithful port of magiblot's C++ Turbo Vision: class structure, method names, control flow, and behaviour are reproduced as-is, except in the places where a line-by-line port is impossible or unwise in Rust. Each such place is a numbered difference. If a behaviour is not on this list, it was ported straight from the C++.

Each difference carries a tag: most are forced (Rust won't compile the direct port) or chosen (the direct port compiles, but a modern construct fits better); a few are tagged by scope (minor / moderate) where the change is small and self-contained.

This page is the at-a-glance list. Every entry links to the Part II chapter that covers it and, where one type carries the difference, to that type's API reference. Other pages cite an entry by its stable anchor (for example difference D2).

Porting contributors: see the project repository.

D1 · Names & namespacing

chosen. The T prefix is dropped and every type lives under the tv:: namespace (TButton → tv::Button); methods become snake_case. The cm*/hc* constant families become type-scoped associated constants on open newtypes (Command, HelpCtx) so apps can mint their own values. → Constant families

D2 · Inheritance → trait + composition

forced. The class tree becomes a View trait with default methods plus a ViewState struct held by composition; "subclass TWindow" becomes embed-and-delegate: hold a Window, forward the methods you don't change. → Inheritance

D3 · Pointers → handles + downward context

forced. Raw TView* pointers become process-global ViewId handles plus a downward-passed Context; up/sideways links resolve by tree-walk, never by reference. → Pointers & infoPtr → handles

D4 · Events → enum + match

chosen. TEvent's tagged union and bitmasks become an Event enum that is matched, not masked; message() splits into a targeted query and an Event::Broadcast. TKey/kb* become a closed Key enum plus KeyModifiers. → Events

D5 · Flag words → struct-of-bools

chosen. The ushort flag words (state, options, growMode, dragMode) become #[derive(Default)] structs of bools, with a verb-enum set_state over them (StateFlag, Options). → Flag words

D6 · Attribute bytes → typed Color/Style

chosen. Packed TColorAttr/TColorDesired bytes become a typed four-variant Color enum plus Style; the per-cell retain-0 overloads are dropped. → The draw model

D7 · Palettes & glyphs → Theme

chosen. Palette chains and scattered glyph literals become a Theme owning a state→Role style map and a Glyphs set; getColor/getPalette become ctx.theme.style(Role::…). → Palettes & glyphs → Theme

D8 · Whole-tree redraw + diff

chosen. Per-write occlusion and damage tracking become a whole-tree redraw into a back buffer plus a diff-bounded terminal flush; occlusion becomes the painter's algorithm, and shadows are cast during the draw. → The draw model

D9 · Modal loops → one loop + capture stack

forced. Nested blocking modal loops (execView, dragView) become one non-recursive event loop plus a LIFO capture stack; modality, drag, and press-tracking are handlers, not loops. execView from a Program method becomes Program::exec_view_with (result by value); execView from within a view becomes Context::request_exec_view (queues Deferred::OpenModal; reuses the existing pending_modal + RouteModalAnswer machinery; the modal's record is routed back via set_modal_data unless the close command is Command::CANCEL, then the close command via set_modal_answer). As in C++, keys, commands, pastes and the mouse wheel go to the modal view alone while it runs, and a command it leaves unhandled is dropped; status-line keys still pre-route. Remaining difference: broadcasts queued under a modal reach the whole tree, not only the modal view. → Modal execView

D10 · Data transfer → typed value protocol

forced. Flat-record memcpy data transfer (getData/setData/dataSize) becomes a typed value()/set_value() protocol over a FieldValue. → Dialogs & data

See The data-movement model for the whole-design overview.

D11 · Platform layer → Backend trait

chosen. The platform layer (THardwareInfo, ncurses/win32 strategies) becomes a small object-safe Backend trait, with a production CrosstermBackend and a test HeadlessBackend that unlocks snapshot testing. → Drawing & backends

D12 · Persistence → dropped

chosen. TStreamable persistence and resource files are dropped; reach for serde if persistence is ever wanted. → Dropped & changed

D13 · Text → Unicode grapheme model

minor. Per-char, CP437 text becomes a Unicode grapheme model (unicode-width + unicode-segmentation) that clusters combining marks into one cell; unprintables render as �. → Dropped & changed

D14 · DOS drives & paths → native Linux filesystem

moderate. The file dialog's DOS drives and \ paths become a native Linux / filesystem: no drive letters, the root is /, and subdirectories are listed via std::fs::read_dir. → Dropped & changed

D15 · DOS timestamps → std::fs mtime, UTC

minor. DOS findfirst local-time stamps become std::fs mtime computed in UTC, packed into the same DOS ftime word so the file-info-pane unpack ports verbatim. → Dropped & changed

D16 · Virtual sizeLimits floor → settable min_size

minor. A C++ window subclass raises its minimum size by overriding the virtual sizeLimits, which the drag, keyboard-resize and zoom paths call. With embed-and-delegate (D2) the inner window cannot see a wrapper's override, so the floor is a field on the window instead: Window::set_min_size (also on Dialog) raises it from the 16×6 default, and every clamp path reads it. The wrapper sets it once at construction, as FileDialog (49×19), ChDirDialog (48×18) and EditWindow (24×6) do. → Inheritance

Underlying mechanisms

The Deferred channel and the cross-view sibling broker are not numbered differences but the substrate that several of these (notably D3 and D9) rely on; see Part IV.

The screenshot tooling

Every colored screen in this guide is the actual terminal output of a running example, captured live and rendered as selectable HTML. The hello screen you saw earlier is one of these. This page explains the pipeline and how to add or regenerate a screen.

The pipeline

A screen is produced entirely by the xtask crate, in pure Rust:

run example in a fixed-size tmux pane
  → tmux send-keys            (drive it into the desired state)
  → tmux capture-pane -e -p   (colored ANSI + UTF-8 box drawing)
  → repo-owned ANSI→HTML converter   (themed <pre class="tv-screen">)
  → written to docs/book/src/screens/<name>.html   (committed)
  → embedded into a guide page with {{#include}}

Compared with embedded PNGs, the captured ANSI is selectable, copy-pasteable, scalable, small and diffable in git. It also supports interactive shots: send keystrokes to open a menu or dialog, then capture the result.

The ANSI→HTML converter is repo-owned (no external aha dependency). It resolves the base SGR colors through Color::BIOS_RGB, so an embedded screenshot uses exactly the palette the running crate uses. It also handles the bright colors, bold/underline/reverse, the xterm 256-color cube, and 24-bit truecolor.

The screen registry

Each documented screen is one entry in the SCREENS table in xtask/src/screens.rs. An entry names the example to run, the terminal size, the keystrokes to drive it, and a settle delay:

// Illustrative sketch — not a standalone program.
Screen {
    name: "hello",       // output file stem → src/screens/hello.html
    example: "hello",    // cargo run --example hello
    cols: 80,
    rows: 25,
    keys: &[],           // tmux send-keys arguments, applied in order
    settle_ms: 700,      // wait after launch / between keystrokes for repaint
}

Each entry in keys is sent with its own tmux send-keys call, in order, so you drive the app the way a user would: &["F10", "Down", "Enter"] opens the menu, moves down, and selects an item before the capture is taken. The capture waits settle_ms after launch and between keystrokes, giving the app time to repaint.

The blank-capture guard

A capture can come back empty if the app had not finished painting yet (or died on launch). Writing that blank pane would clobber the committed screenshot, so the capture step runs a looks_blank check: a pane that contains only whitespace and escape sequences (no glyphs) is rejected as an error. The committed file is left untouched, and the message suggests a longer settle_ms. The detached tmux session is always killed afterward, even on error, so no sessions leak.

Adding or regenerating a screen

  1. Add (or reuse) a runnable example under examples/.

  2. Add a Screen entry to SCREENS in xtask/src/screens.rs, with the keys that drive it into the state you want to show.

  3. Regenerate:

    $ cargo xtask screens
    

    This pre-builds every referenced example, then captures each into docs/book/src/screens/<name>.html. (cargo xtask docs runs the same step as the first stage of the full site build, and skips it with a warning if tmux is unavailable; the committed screens stay usable.)

  4. Embed it in a guide page:

    {{#include ../screens/<name>.html}}
    
  5. Commit both the new HTML under docs/book/src/screens/ and your screens.rs change. The generated files are checked in, so a plain mdbook build (or a reviewer without tmux) still renders the guide with screenshots.

If a regeneration reports a blank capture, bump that screen's settle_ms and run cargo xtask screens again.