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 nameEach builder returns a
Box<dyn View>(or aMenu/ 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
Menu bar
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(())
}