Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Windows & the desktop

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

The desktop

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

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

use std::io;

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

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

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

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

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

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

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

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

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

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

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

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

Opening windows

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

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

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

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

Z-order, focus and window commands

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

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

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

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

Fullscreen windows

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

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

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

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

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

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

Composable primitives

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

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

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

Tiling and cascading

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

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

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

Splitter: resizable panes

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

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

Axes and panes

use tvision_rs::{Splitter, Constraints};

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

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

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

Constraints

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

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

Divider styles

DividerStyle controls how a seam looks and behaves:

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

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

Live drag and keyboard resize

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

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

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

Nested splitters

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

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

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

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

Joined linework

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

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

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

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

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

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

Limiting move and resize

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

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

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

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

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

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

Grow modes: anchoring edges

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

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

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

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

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

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

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

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

Bringing a window to the front

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

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

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

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

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

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

Source: src/view/group.rs (Group::focus_child, Group::make_first, Group::put_in_front_of, and the top_select option check).

Turbo Vision heritage: TGroup::makeFirst / putInFrontOf performed the same move in the circular doubly-linked sibling ring. tvision-rs stores children in a Vec and implements raise-to-top as a swap to the last slot (deviation D3).

See also