D.A.B.Tv0.0.33 Tutorial API DABT Tools ↗ GitHub ↗

Core: lifecycle, layout & runtime

The always-loaded core (lib/tui.sh, lib/tui_api.sh, lib/state.sh, lib/markup/tui_factory.sh): starting the app, building the pane tree, tabs, runtime (factory) widgets, output, background process streaming, live updates, getters, logging and the event/result variables everything else reads. ← API index for the full module list and a task-oriented tour with examples.

Each function has its own page; the summary tables link to them, and the full entries follow each table. Functions return 0 unless their entry says otherwise. Getters print to stdout, so call them in $(...); the fork-free alternatives that set variables are noted on each entry.

Lifecycle

tui.start is the usual entry point. tui.init + tui.run are the manual form for apps that build their UI in code.

Function Summary
tui.start Runs a markup-driven app: validates the page, initializes the terminal, loads FILE and runs the main loop until the app quits.
tui.start_cached Like tui.start, but first records every page the app can reach into the page cache, so later page switches replay instead of parsing.
tui.init Takes over the terminal and prepares an empty root pane.
tui.run Runs the main loop (input, dispatch, render, ticks) until tui.stop is called, then restores the terminal.
tui.stop Asks the main loop to exit after the current iteration.
tui.cleanup Restores the terminal: mouse tracking and bracketed paste off, style reset, cursor shown, main screen, unread input drained, original stty settings back.
tui.require Sources an optional bundled library once per process.
tui.tick.add Registers FN to run once per main-loop iteration.
tui.tick.remove Unregisters a tick listener. Unknown names are ignored.
tui.on_resize Marks the terminal as resized; the main loop re-lays out on its next iteration.

tui.start

tui.start FILE

Runs a markup-driven app: validates the page, initializes the terminal, loads FILE and runs the main loop until the app quits.

Parameters

  • FILE: the first page (XML).

Returns: 1 when FILE is unreadable, fails validation or fails to load; otherwise returns after the app quits.

Notes

  • Validates FILE and its includes before the terminal is taken over. Errors are printed to stderr and abort the start, unless TUI_IGNORE_INVALID_XML=1 (set by dabt --ignore-invalid-xml). TUI_VALIDATE=0 skips validation.
  • Sets TUI_THEMES_DIR to the page’s themes/ folder (else the defaults’ themes/) when it is not already set.
  • The terminal is restored on every exit path: normal quit, INT/TERM, or a load failure.
  • Uses the page cache for later tui.goto calls but does not pre-warm it; see tui.start_cached.

Example

#!/usr/bin/env bash
TUI_APP_NAME=my_app                 # before sourcing: names the config folder and log file
source /path/to/lib/tui.sh
tui.start "$APP/config/home.xml"

See also: tui.start_cached, tui.init, tui.run

tui.start_cached

tui.start_cached FIRST_PAGE

Like tui.start, but first records every page the app can reach into the page cache, so later page switches replay instead of parsing.

Parameters

  • FIRST_PAGE: the page to open. Every *.xml next to it and every shipped default page (share/defaults/pages/) is warmed too.

Returns: as tui.start.

Notes

  • Files whose name starts with _ (fragments for <include>) are skipped.
  • All warmed pages are validated before the terminal is taken over, not only FIRST_PAGE.
  • Only pages that are missing from the on-disk cache or changed since are re-recorded, behind a progress banner. The cache lives in tui.cache.disk_dir.

See also: tui.cache.warm_with_spinner, tui.load_cached

tui.init

tui.init

Takes over the terminal and prepares an empty root pane.

Notes

  • Applies the saved config, switches to raw input (stty -echo -icanon -isig -ixon -iexten), enters the alternate screen, hides the cursor, and turns on mouse tracking and bracketed paste.
  • Because of -isig, ctrl+c and ctrl+z arrive as keys instead of signals.
  • Records the run in app.meta, starts enabled plugins and fires the init hook.
  • tui.start calls it. Call it yourself only when building the UI in code; pair it with tui.run.

See also: tui.cleanup

tui.run

tui.run

Runs the main loop (input, dispatch, render, ticks) until tui.stop is called, then restores the terminal.

Notes

  • Fires the ready hook once, before the first frame.
  • Installs INT/TERM traps (clean up and exit 1) and a WINCH trap for resizes.
  • Polls input every 0.05 s while tick listeners exist, else every 0.2 s (TUI_INPUT_POLL_TIMEOUT, TUI_INPUT_IDLE_TIMEOUT); polls with shorter TUI_INPUT_SETTLE_TIMEOUT (0.01 s) while a pane render or a timer-driven widget draw is queued.
  • Restores the terminal before it returns, so code after tui.run prints to the normal screen.

Example

source lib/tui.sh
tui.init
tui.vsplit root top:1 bottom:3
tui.output bottom "hello"
tui.run

See also: tui.start

tui.stop

tui.stop

Asks the main loop to exit after the current iteration.

Notes

  • Fires the quit hook first.
  • Never asks for confirmation. Bind tui.action.quit instead to respect the confirm.quit setting.

See also: tui.run

tui.cleanup

tui.cleanup

Restores the terminal: mouse tracking and bracketed paste off, style reset, cursor shown, main screen, unread input drained, original stty settings back.

Notes

  • tui.run and the signal traps already call it. Call it yourself only when you called tui.init without tui.run.

See also: tui.init

tui.require

tui.require LIBRARY

Sources an optional bundled library once per process.

Parameters

  • LIBRARY: terminal_renderer, terminal_controls or tui_scan.

Returns: 1 and a message on stderr for an unknown name.

Notes

  • Callback files are re-sourced on every page visit. Use tui.require there instead of source so a large library is loaded only once.

Example

tui.require terminal_renderer
tui.output stats "$(table_string 'Name|Size' 'a.txt|1k')"

tui.tick.add

tui.tick.add FN

Registers FN to run once per main-loop iteration.

Parameters

  • FN: function name, called with no arguments.

Notes

  • Adding the same FN twice is a no-op.
  • Listeners survive page changes. Remove page-specific listeners with tui.tick.remove, or use tui.every, which is cleared on page change.
  • While any listener exists the loop polls input every 0.05 s instead of 0.2 s, so an idle app stays cheap only when nothing is registered.
  • Never assign _TUI_TICK_FN for this: it is a single slot, and overwriting it stops other tick users such as tui.exec.
  • A listener registered while a plugin loads is removed when that plugin is disabled.

See also: tui.every

tui.tick.remove

tui.tick.remove FN

Unregisters a tick listener. Unknown names are ignored.

Parameters

tui.on_resize

tui.on_resize

Marks the terminal as resized; the main loop re-lays out on its next iteration.

Notes

  • Installed as the WINCH handler by tui.run. You rarely call it yourself.
  • A drag-resize is coalesced: the loop waits until no resize arrived for about 40 ms, then lays out once and fires the resize hook.

Layout (panes)

Panes form a tree rooted at root. Splits divide a pane among children by integer weight; leaves hold widgets or output. Pane names are used in bash variable names, so use letters, digits and _ only.

Function Summary
tui.hsplit Splits PARENT into side-by-side child panes.
tui.vsplit Splits PARENT into stacked child panes, top to bottom.
tui.grid Lays NAME... out as a grid of cells inside PARENT, row by row.
tui.fixed Lays children out as fixed-size cells that flow left to right and wrap, like keys on a keyboard.
tui.pane_title Sets the title drawn in the pane’s top border.
tui.pane_border Sets the border style of a pane.
tui.pane_pad Sets blank columns (HPAD) and rows (VPAD) on each side inside the pane.
tui.pane_gap Gets or sets the gap between children of a split pane.
tui.pane_fuse Fuses a pane with its siblings so neighbouring borders share one line.
tui.pane_divider Sets the border style of the line a fused pane shares with its neighbour.
tui.pane_divider_class Sets the theme class that colours the line a fused pane shares with its neighbour.
tui.pane_title_pos Sets which border line carries a pane’s title.
tui.pane_title_align Sets where along its border line a pane’s title sits.
tui.pane_resizable Allows a pane to be resized on one or both axes, by mouse handle or keyboard.
tui.pane_handle Chooses the mouse handle that resizes a resizable pane.
tui.resize Grows PANE by DW columns and DH rows (negative values shrink) with the same clamping as a drag.
tui.resize.reset Restores the split weights recorded before the first resize, for the split holding PANE and every split above it.
tui.collapse Collapses (on), expands (off) or toggles (default) a collapsible pane, then lays out again.
tui.collapsed Reports whether a pane is collapsed.
tui.pane_align Sets the default horizontal alignment for widgets in the pane.
tui.pane_valign Sets the default vertical anchor for widgets in the pane. Default: top.
tui.pane_minsize Sets the smallest size at which the pane shows its content. Below it, the pane shows a min space = WxH notice instead.
tui.pane_maxsize Caps the size a split gives the pane.
tui.pane_scroll Enables scrolling of the pane’s output and resets its scroll position to the top left.
tui.pane_scroll_into_view Sets whether focus scrolls a vertically scrolling pane to reveal the focused widget. Default: true.
tui.scroll.to Scrolls the pane that holds widget TARGET (or the pane TARGET itself) so the widget sits at the specified viewport position.
tui.scroll.reset Scrolls a scrolling pane back to its top-left corner, repainting only when it was elsewhere.
tui.pane_strict_fit Turns the automatic content-fit check of a leaf pane on (default) or off.
tui.pane_size Stores the usable content size of a pane (inside border and padding) in variables, without a subshell.
tui.capture Runs CMD and stores its standard output in VAR, like VAR="$(CMD ARGS...)" but without a subshell.
tui.content_area Prints the content rectangle of a pane as ROW COL HEIGHT WIDTH (1-based, inside border and padding).
tui.pane.focus Makes PANE the keyboard pane: the target of scroll keys, drawn with a highlighted border.
tui.relayout Recomputes geometry and repaints in one synchronized frame. Use it after changing borders, padding, titles or splits while the app runs.
tui.clear_pane Blanks the pane’s content rectangle on screen.
tui.render Repaints every pane, widget and output now, as one buffered frame.
tui.redraw Same as tui.render.
tui.frame.request Asks for a relayout and repaint at the end of the current input-loop iteration.

tui.hsplit

tui.hsplit PARENT NAME[:WEIGHT]...

Splits PARENT into side-by-side child panes.

Parameters

  • PARENT: an existing pane (root at first).
  • NAME[:WEIGHT]: one per child, left to right. WEIGHT is a positive integer share of the width. Default: 1.

Notes

  • Pane names become part of bash variable names: use letters, digits and _ only.
  • Each child starts with a single border and no title. The last child absorbs rounding leftovers.

Example

tui.hsplit root nav main:3      # nav gets 1/4 of the width, main 3/4

See also: tui.vsplit, tui.grid, tui.fixed

tui.vsplit

tui.vsplit PARENT NAME[:WEIGHT]...

Splits PARENT into stacked child panes, top to bottom.

Parameters

  • PARENT: an existing pane.
  • NAME[:WEIGHT]: one per child. WEIGHT is a positive integer share of the height. Default: 1.

Notes

  • Same rules as tui.hsplit: identifier-safe names, single border by default.

Example

tui.vsplit main header:1 body:5 status:1

See also: tui.hsplit

tui.grid

tui.grid PARENT ROWS COLS FIT ROW_WEIGHTS COL_WEIGHTS NAME...

Lays NAME... out as a grid of cells inside PARENT, row by row.

Parameters

  • ROWS, COLS: grid size. Either may be "" and is then computed from the number of names; both empty gives a near-square grid.
  • FIT: what happens to cells with no name. pack (default when "") keeps them as empty panes; stretch lets the row’s other cells absorb them.
  • ROW_WEIGHTS, COL_WEIGHTS: space-separated weights, e.g. "1 2". "" = all 1.
  • NAME...: cell pane names, row-major.

Notes

  • All six leading parameters are positional; pass "" for the ones you skip.
  • Built from a tui.vsplit into rows named PARENT_row0, PARENT_row1, … and an tui.hsplit per row. Blank pack cells are named PARENT_rowR_cC_blank.
  • tui.get.split on PARENT prints v.

Example

tui.grid dash 2 3 pack "" "2 1 1" cpu mem disk net io load

See also: tui.factory.grid, tui.fixed

tui.fixed

tui.fixed PARENT CELL_W CELL_H CHILD[:SPAN[:nl]]...

Lays children out as fixed-size cells that flow left to right and wrap, like keys on a keyboard.

Parameters

  • CELL_W, CELL_H: size of one cell in columns and rows.
  • CHILD: pane name. SPAN makes it that many cells wide (default 1). A third field (any text, e.g. nl) starts a new row before this child.

Notes

  • Sizes never stretch with the window. Children that don’t fit get a 0×0 rectangle and are not drawn.
  • Children start with no border.
  • tui.get.split on PARENT prints f.

Example

tui.fixed keys 6 3 esc f1 f2 f3 tab:2:nl q w e

See also: tui.grid

tui.pane_title

tui.pane_title PANE TEXT

Sets the title drawn in the pane’s top border.

Notes

  • A ^ marks the next character as an accent, drawn in the title_key theme class (bold red without a rule): "^1cpu", "^menu". ^^ is a literal caret.
  • Not drawn when the pane has no border.
  • While the app runs, a changed title repaints just the pane’s border; no tui.relayout is needed. An unchanged title costs nothing, so it is safe to call from a timer.

tui.pane_border

tui.pane_border PANE STYLE

Sets the border style of a pane.

Parameters

  • STYLE: single, double, heavy or none. Any other value draws single.

Notes

  • A parent pane draws its border only when it was set with this function and there is room for it; leaf panes draw a single border by default.
  • A border that doesn’t fit (leaf under 3×5 cells) is dropped automatically.
  • While the app runs, call tui.relayout to apply it; the border changes the content area.

See also: tui.get.border

tui.pane_pad

tui.pane_pad PANE HPAD VPAD

Sets blank columns (HPAD) and rows (VPAD) on each side inside the pane.

Parameters

  • HPAD, VPAD: cell counts. "" leaves that value unchanged.

Notes

  • On a parent pane: the gap between its frame and its children. On a leaf: shrinks the area for widgets and output.
  • Padding is clamped so at least one row and column remain.
  • While the app runs, call tui.relayout to apply it.

See also: tui.get.pad, tui.pad

tui.pane_gap

tui.pane_gap PANE [GAP]

Gets or sets the gap between children of a split pane.

Parameters

  • GAP: cell count left blank between children on the split axis. Omit to get the current value.

Notes

See also: tui.pane_pad

tui.pane_fuse

tui.pane_fuse PANE BOOL

Fuses a pane with its siblings so neighbouring borders share one line.

Parameters

  • PANE - pane id.
  • BOOL - boolean (true|false), default false. Any other value is ignored with a warning and the call returns 1.

Notes

  • A split fuses only when every child is a fuse pane and the split has no gap. Fused siblings overlap by one cell and the shared line gets the matching junction glyphs.
  • Markup: fuse="true". Call tui.relayout to apply it while the app runs.

See also: tui.pane_border

tui.pane_divider

tui.pane_divider PANE STYLE

Sets the border style of the line a fused pane shares with its neighbour.

Parameters

  • PANE - pane id.
  • STYLE - enum (single double heavy), optional. Empty uses the pane’s own border style.

Notes

  • Markup: divider="double". Only matters on a fused pane.

See also: tui.pane_border

tui.pane_divider_class

tui.pane_divider_class PANE CLASS

Sets the theme class that colours the line a fused pane shares with its neighbour.

Parameters

  • PANE - pane id.
  • CLASS - text, optional. Empty uses the pane’s border colour.

Notes

  • Markup: divider_class="name". Only matters on a fused pane.

See also: tui.pane_border

tui.pane_title_pos

tui.pane_title_pos PANE POS

Sets which border line carries a pane’s title.

Parameters

  • PANE - pane id.
  • POS - enum (top bottom), default top.

Notes

  • Markup: title_pos="bottom". An invalid value is ignored with a warning.

See also: tui.pane_border

tui.pane_title_align

tui.pane_title_align PANE ALIGN

Sets where along its border line a pane’s title sits.

Parameters

  • PANE - pane id.
  • ALIGN - enum (left center right), default left. A title longer than the line is cut.

Notes

  • Markup: title_align="center". An invalid value is ignored with a warning.

See also: tui.pane_border

tui.pane_resizable

tui.pane_resizable PANE MODE

Allows a pane to be resized on one or both axes, by mouse handle or keyboard.

Parameters

  • PANE - pane id.
  • MODE - enum (x y both none). x resizes width, y resizes height, both allows both axes, none switches resizing off.

Notes

  • Markup: resizable="x|y|both". Works on any pane. A resize moves weight between the pane and a sibling: its next sibling, or the previous one for the last child of a split (keyboard and drag alike) in proportion to the weights they hold now, within their min_*/max_*.
  • Mouse zones need tui.pane_handle; without one alt+r still starts the keyboard resize mode.
  • An invalid value is ignored with a warning (return 1).

See also: tui.resize, tui.action.resize_mode

tui.pane_handle

tui.pane_handle PANE KIND

Chooses the mouse handle that resizes a resizable pane.

Parameters

  • PANE - pane id.
  • KIND - enum (corner edge divider none), default none. Selects the mouse handle style for resizing.

Notes

  • edge and divider drag a border the pane shares with a sibling; divider is the shared line of a fused split. A pane that has a next sibling drags its trailing border (its last column / row); the last child of a split drags its leading border (its first column / row, shared with the previous sibling), so it can be resized too. A pane with resizable but no handle stays keyboard-only. corner is the pane’s bottom-right cell: it moves the nearest ancestor h-split edge horizontally and the nearest v-split edge vertically.
  • A double press on a handle resets the pane (tui.resize.reset). The zones are rebuilt with every layout.
  • Markup: handle="corner|edge|divider|none"; it needs resizable. An invalid value is ignored with a warning (return 1).

See also: tui.pane_resizable

tui.resize

tui.resize PANE DW DH

Grows PANE by DW columns and DH rows (negative values shrink) with the same clamping as a drag.

Parameters

  • PANE - pane id.
  • DW - integer (cells); 0 leaves that axis alone.
  • DH - integer (cells); 0 leaves that axis alone.

Returns: 0 when something moved, 1 when every move was clamped flat or no split of that axis holds the pane.

Notes

  • Ignores resizable: the attribute gates the user’s mouse and keyboard, not the app. The layout generation is bumped, the layout recomputed and on_resize callbacks (FN PANE W H) run for panes that changed size.

See also: tui.resize.reset, tui.pane_resizable

tui.resize.reset

tui.resize.reset PANE

Restores the split weights recorded before the first resize, for the split holding PANE and every split above it.

Parameters

  • PANE - pane id.

Returns: 1 when nothing had been resized.

Notes

  • The record is dropped on a page load, so a reset returns to the weights the page was built with. A double press on a handle calls it.

See also: tui.resize

tui.collapse

tui.collapse PANE [toggle|on|off]

Collapses (on), expands (off) or toggles (default) a collapsible pane, then lays out again.

Parameters

  • PANE - pane id. Must have collapsible="true" (or be a <details>) in an h or v split.
  • MODE - enum (toggle on off), optional, default toggle.

Returns: 1 when PANE is not collapsible, the mode is unknown or nothing changed.

Notes

  • A collapsed pane shrinks along its parent’s split axis to collapse_to (title, 0 or rail); the freed space goes to the siblings with an fr weight and expanding restores the previous size spec. The widgets of a collapsed pane, including those in panes nested inside it, are hidden: not drawn, focusable or hit-testable, and focus inside the pane moves to the next focusable widget. A rail shows each button’s collapsed_text instead.
  • In an exclusive <accordion> expanding a pane collapses its siblings. on_toggle callbacks (FN PANE STATE, STATE is collapsed or expanded) run for every pane that changed, on_resize callbacks for every pane that changed size.
  • A collapsible pane has a collapse button: a 2-cell control drawn on its border at the corner of the edge that moves. In an h split that is the top of the right edge (the left edge for the last pane), in a v split the left end of the bottom edge (the top edge for the last pane). The arrow points where the edge moves (◀ for an expanded first pane, ▶ for an expanded last pane, ▲ / ▼ in a v split) and flips while collapsed. It stays visible on a rail or title bar; collapse_to="0" has none. A click on it calls this with toggle; alt+c (tui.action.collapse_toggle) does it from the keyboard.
  • Theme classes: .collapse_button (base), .collapse_button:hover (the pointer is over it) and .collapse_button:collapsed (the pane is collapsed; hover wins over it, field by field). A pane picks another class with collapse_class="NAME" (NAME, NAME:hover, NAME:collapsed; the validator warns when no theme defines it). Resizable borders use .resize_handle:hover the same way. Every bundled theme defines all of them.
  • Keyboard: alt+c is shown in the footer as alt+c Collapse / alt+c Expand while the focus is inside a collapsible pane (it does not fire while a text input has focus: the input owns it). collapse_key="KEY" (any key name of the bind table, e.g. ctrl+1, f5) binds a direct toggle for that pane that works from anywhere on the page, also from a text input; the bind is dropped with the page. The validator reports an unknown key name and a key used twice on the page (also against a <bind key>) as errors.

See also: tui.collapsed, tui.resize

tui.collapsed

tui.collapsed PANE

Reports whether a pane is collapsed.

Parameters

  • PANE - pane id.

Returns: 0 while PANE is collapsed, 1 otherwise (also for a pane that is not collapsible).

Notes

  • Reads _TUI_P_COLLAPSED[PANE], the one place the state is kept.

See also: tui.collapse

tui.pane_align

tui.pane_align PANE left|center|right|fill

Sets the default horizontal alignment for widgets in the pane.

Notes

  • A widget’s own tui.align wins. Without either, widgets are left-aligned and buttons centered.
  • Affects widgets only, not text from tui.output.

tui.pane_valign

tui.pane_valign PANE top|middle|bottom

Sets the default vertical anchor for widgets in the pane. Default: top.

Notes

  • A widget’s ROW counts from the anchor: with bottom, row 0 is the last line and higher rows go up.
  • A widget’s own tui.valign wins.

tui.pane_minsize

tui.pane_minsize PANE [MIN_W] [MIN_H]

Sets the smallest size at which the pane shows its content. Below it, the pane shows a min space = WxH notice instead.

Parameters

  • MIN_W, MIN_H: columns and rows. Empty leaves that value unchanged.

Notes

  • Leaf panes also get an automatic minimum from their content unless tui.pane_strict_fit is false.

See also: tui.pane_maxsize

tui.pane_maxsize

tui.pane_maxsize PANE [MAX_W] [MAX_H]

Caps the size a split gives the pane.

Parameters

  • MAX_W, MAX_H: columns and rows. Empty leaves that value unchanged.

Notes

  • Space the cap takes away is passed to the pane’s last sibling. When the capped pane is itself the last child, that space stays empty.

See also: tui.pane_minsize

tui.pane_scroll

tui.pane_scroll PANE none|v|h|both

Enables scrolling of the pane’s output and resets its scroll position to the top left.

Notes

  • Scrolling applies to tui.output content: wheel, j/k, page keys and a draggable scrollbar.
  • Calling it again, even with the same mode, jumps back to the top.

See also: tui.get.scroll, tui.action.scroll

tui.pane_scroll_into_view

tui.pane_scroll_into_view PANE true|false

Sets whether focus scrolls a vertically scrolling pane to reveal the focused widget. Default: true.

Notes

  • Applies to panes created with scroll_into_view="true|false" in markup.
  • When enabled, the pane scrolls automatically to keep the focused widget visible in the viewport.

See also: tui.pane_scroll

tui.scroll.to

tui.scroll.to TARGET [top|center|bottom]

Scrolls the pane that holds widget TARGET (or the pane TARGET itself) so the widget sits at the specified viewport position.

Parameters

  • TARGET: a widget id or pane id
  • Position (optional): top, center, or bottom
    • For widgets: positions the widget’s top, middle, or bottom row at that viewport edge
    • For panes: positions the start (top), middle, or end of content at that edge
    • Omitted (default): performs the minimal scroll needed to show it; for panes, equivalent to top

Returns

  • 0 on success
  • 1 for an unknown id, a non-scrolling pane, or an invalid position

Notes

  • The offset is clamped to the valid range [0, max] for the pane’s content.
  • Repaints only when the offset actually changed: full redraw for widget panes, targeted update for output panes.
  • If the UI is not running, only sets the offset without drawing.

See also: tui.pane_scroll, tui.get.scroll

tui.scroll.reset

tui.scroll.reset PANE

Scrolls a scrolling pane back to its top-left corner, repainting only when it was elsewhere.

Returns: 1 for an unknown pane.

Notes

  • tui.tabs.activate calls it for the tab group’s content pane when another tab is activated.
  • tui.md.show calls it when it shows a different document.

See also: tui.scroll.to, tui.pane_scroll

tui.pane_strict_fit

tui.pane_strict_fit PANE true|false

Turns the automatic content-fit check of a leaf pane on (default) or off.

Notes

  • With the check on, a pane whose widgets need more room than it has shows the min space notice. false falls back to the explicit tui.pane_minsize only; use it for panes where clipping is fine (tab headers do this).

tui.pane_size

tui.pane_size PANE

Stores the usable content size of a pane (inside border and padding) in variables, without a subshell.

Returns: 1 for an unknown pane.

Sets: TUI_PANE_ROWS, TUI_PANE_COLS.

Example

tui.pane_size status
printf -v rule '%*s' "$TUI_PANE_COLS" ''
tui.set_text status "${rule// /─}"      # a rule exactly as wide as the pane

See also: tui.get.dimensions

tui.capture

tui.capture VAR CMD [ARGS...]

Runs CMD and stores its standard output in VAR, like VAR="$(CMD ARGS...)" but without a subshell.

Parameters

  • VAR - name of the variable that receives the output; trailing newlines are stripped, as $( ) does.
  • CMD - a function or command; it runs in the current shell.

Returns: the exit status of CMD.

Notes

  • A fork costs 1 ms or more on a busy machine. Use this in callbacks that run on page visits, ticks and input.
  • CMD shares the shell: variables it sets stay set, and it must not rely on $( ) isolation.
  • Calls can be nested.

Example

tui.capture banner banner_string "DABT"
tui.output out "$banner"

tui.content_area

tui.content_area PANE

Prints the content rectangle of a pane as ROW COL HEIGHT WIDTH (1-based, inside border and padding).

Notes

  • Does not check that PANE exists. Prefer tui.get.content_area, which returns 1 for an unknown pane.

tui.pane.focus

tui.pane.focus PANE

Makes PANE the keyboard pane: the target of scroll keys, drawn with a highlighted border.

Parameters

  • PANE: pane id, or "" to clear.

Notes

  • Focusing a widget also moves pane focus to the widget’s pane.
  • Only the two affected borders are redrawn.

See also: tui.get.pane_focus, tui.action.focus_pane

tui.relayout

tui.relayout [PANE]

Recomputes geometry and repaints in one synchronized frame. Use it after changing borders, padding, titles or splits while the app runs.

Parameters

  • PANE: a leaf pane to repaint alone, without clearing the screen. Omitted (or a parent pane): lay out and repaint everything.

Notes

  • Before tui.run it only recomputes geometry.

Example

tui.pane_border side double
tui.relayout

tui.clear_pane

tui.clear_pane PANE

Blanks the pane’s content rectangle on screen.

Notes

  • Writes to the terminal directly and does not change the pane’s content; the next repaint draws it again. Use tui.output_clear to empty the content.

tui.render

tui.render

Repaints every pane, widget and output now, as one buffered frame.

Notes

  • Expensive. Content functions (tui.output, tui.set_text, tui.update) already queue their own repaint, coalesced per frame; don’t call tui.render after them or from timers.
  • Does not recompute geometry; use tui.relayout after layout changes.

See also: tui.redraw

tui.redraw

tui.redraw

Same as tui.render.

tui.frame.request

tui.frame.request

Asks for a relayout and repaint at the end of the current input-loop iteration.

Notes

  • Any number of requests inside one event produce one frame. Use it instead of tui.relayout in handlers that change several things.
  • A direct tui.render satisfies a pending request.

See also: tui.relayout, tui.render

Page state

A page can keep state while the user visits other pages. In markup: keep_value="true" on a widget (value, cursor, scroll, selection), keep_collapsed="true" and keep_size="true" on a pane, or keep_state="true" on <tui> for every widget and pane of the page. persist="session" (the default) keeps it for this run; persist="disk" (on a widget, a pane or <tui>) implies the keeping and also writes the fields to $TUI_HOME/state/store, so they are back the next time the app starts. State is saved when the page is left and restored after it is built again, also after tui.page.refresh rebuilt panes. The store is _TUI_STORE["PAGE|ID|FIELD"].

The disk file is data only (# dabt-state 1, then one escaped PAGE TAB ID TAB FIELD TAB VALUE line per entry; fields value cursor scroll sel collapsed size focus). It is read with read -r and never sourced, so TUI_HOME is not a code-execution boundary; lines that do not parse are skipped. It is loaded on first use, written when a page is left or the app exits (only if something changed) and by tui.store.flush. tui.page.reset, tui.page.reset_field and tui.page.reset_all also remove the matching disk entries.

Focus can be kept too. keep_focus="true" on a widget: when it has the focus as a page is left and the next page has a widget with the same id, focus lands on it before the first render (and a keep_focus widget is focused again when you return to its page). <tui focus_on_enter="ID|keep|first"> sets where focus lands on entry: first (the default), keep (the id focused when the page was last left, kept in the store as field focus) or the id of a widget; an id that does not exist falls back to first.

Function Summary
tui.store.set Stores one field of a widget or pane in the page-state store.
tui.store.get Reads one stored field into REPLY.
tui.store.unset Drops stored state: one field, every field of one id, or a whole page.
tui.store.has Reports whether anything is stored for a page, or for one id.
tui.store.register_type Sets which fields a widget type keeps.
tui.page.reset Forgets the stored state of a page and puts the current page back to its first-build state.
tui.page.reset_field Puts one kept widget or pane back to its first-build state.
tui.page.reset_all Empties the whole store (every page) and resets the current page.
tui.page.resettable Reports whether a reset would change anything on the current page.
tui.store.flush Writes the disk image of the page-state store to tui.store.file now.
tui.store.file Prints the path of the file that holds the persist="disk" page state: $TUI_HOME/state/store.

tui.store.set

tui.store.set PAGE ID FIELD VALUE

Stores one field of a widget or pane in the page-state store.

Parameters

  • PAGE: the page file’s basename, e.g. workspace.xml.
  • ID: widget or pane id (a | or % in it is escaped, so ids never collide).
  • FIELD: value, cursor, scroll, sel, collapsed or size.
  • VALUE: the text to keep.

Notes

  • The store is one associative array, _TUI_STORE["PAGE|ID|FIELD"], kept for the session. Pages fill it themselves when keep_value, keep_collapsed, keep_size or keep_state is set; call this to preload or edit state. It changes memory only; the disk file (persist="disk") is written from the live widgets when a page is left, see tui.store.flush.

See also: tui.store.get, tui.page.reset

tui.store.get

tui.store.get PAGE ID FIELD

Reads one stored field into REPLY.

Parameters

  • PAGE: the page file’s basename.
  • ID: widget or pane id.
  • FIELD: the field name.

Returns: 0 with the value in REPLY, 1 when nothing is stored.

Notes

  • Fork-free.

See also: tui.store.set

tui.store.unset

tui.store.unset PAGE [ID [FIELD]]

Drops stored state: one field, every field of one id, or a whole page.

Parameters

  • PAGE: the page file’s basename.
  • ID: optional: only this widget or pane.
  • FIELD: optional: only this field.

Notes

See also: tui.store.set, tui.page.reset

tui.store.has

tui.store.has PAGE [ID]

Reports whether anything is stored for a page, or for one id.

Parameters

  • PAGE: the page file’s basename.
  • ID: optional: only this widget or pane.

Returns: 0 when something is stored, 1 otherwise.

See also: tui.store.get

tui.store.register_type

tui.store.register_type TYPE FIELD...

Sets which fields a widget type keeps.

Parameters

  • TYPE: the widget type, as in _TUI_W_TYPE.
  • FIELD: value, cursor, scroll, sel, or a field of your own.

Notes

  • Built in: input, password, textarea (value cursor scroll), checkbox, progress (value), select (value sel), list, table (sel scroll).
  • A field of your own needs _tui_store.get.FIELD ID (sets _SF, rc 1 = nothing to keep) and _tui_store.put.FIELD ID VALUE.

See also: tui.store.set

tui.page.reset

tui.page.reset [PAGE]

Forgets the stored state of a page and puts the current page back to its first-build state.

Parameters

  • PAGE: optional page basename; default the current page. Another page only loses its stored state.

Notes

  • Every kept widget and pane returns to the value, selection, scroll and collapsed state it had when the page was first built; every resized split returns to its weights before the first resize. Then the page is laid out again, on_resize callbacks run and a repaint is requested.
  • Bound to alt+shift+r (tui.action.page_reset).

See also: tui.page.reset_field, tui.page.reset_all, tui.page.resettable

tui.page.reset_field

tui.page.reset_field ID

Puts one kept widget or pane back to its first-build state.

Parameters

  • ID: a widget or pane the page keeps state for.

Returns: 1 when the page keeps nothing for ID.

See also: tui.page.reset

tui.page.reset_all

tui.page.reset_all

Empties the whole store (every page) and resets the current page.

See also: tui.page.reset

tui.page.resettable

tui.page.resettable

Reports whether a reset would change anything on the current page.

Returns: 0 when a split was resized or a kept field differs from its first-build value, 1 otherwise.

Notes

  • The footer item Reset page and the palette command of the same name use it as their when predicate.

See also: tui.page.reset

tui.store.flush

tui.store.flush

Writes the disk image of the page-state store to tui.store.file now.

Notes

  • Only the fields of items marked persist="disk" are in the file; session state never is.
  • The file is data only: the first line is # dabt-state 1, then one PAGE TAB ID TAB FIELD TAB VALUE line per entry with \\, \t, \n and \r escaped. It is read line by line and never sourced.
  • The write goes to store.tmp.PID (mode 0600, in a 0700 folder) and is renamed over the old file.
  • Pages and app exit write it on their own when something changed; call this to write at a moment of your choosing.

Returns: 0 on success, 1 when TUI_HOME is unset or the file cannot be written.

See also: tui.store.file, tui.page.reset_all

tui.store.file

tui.store.file

Prints the path of the file that holds the persist="disk" page state: $TUI_HOME/state/store.

Returns: 0, or 1 (printing nothing) when TUI_HOME is unset.

See also: tui.store.flush

Tabs

A tab group is a header pane with one button per tab and a content pane that the active tab’s action fills. In markup: <tabs>, see ../guide/grid-layouts-and-tabs.md.

Function Summary
tui.tabs.add Registers one tab before the group is built.
tui.tabs.compact Picks the header style of a tab group. Call it before tui.tabs.build.
tui.tabs.build Builds the header row for registered tabs and activates the default tab (or the first).
tui.tabs.activate Makes a tab active: focuses its header button and calls its action as ACTION TAB_ID.

tui.tabs.add

tui.tabs.add TAB_ID TEXT ACTION [DEFAULT]

Registers one tab before the group is built.

Parameters

  • TAB_ID: widget id of the tab’s header button.
  • TEXT: header caption.
  • ACTION: function called as ACTION TAB_ID whenever the tab is activated. It fills the content pane.
  • DEFAULT: true to activate this tab when the group is built. Any other value counts as not default.

See also: tui.tabs.build

tui.tabs.compact

tui.tabs.compact TABS_ID [true|false]

Picks the header style of a tab group. Call it before tui.tabs.build.

Parameters

  • TABS_ID: the group id passed to tui.tabs.build.
  • true (default): one-row, borderless headers styled with .tab_header_compact. false: framed headers (.tab_header), which need 3 rows.

tui.tabs.build

tui.tabs.build TABS_ID HEADER_PANE CONTENT_PANE TAB_ID...

Builds the header row for registered tabs and activates the default tab (or the first).

Parameters

  • TABS_ID: a name for the group.
  • HEADER_PANE: leaf pane that receives a one-row grid of header buttons.
  • CONTENT_PANE: the pane the tab actions fill.
  • TAB_ID...: tabs registered with tui.tabs.add, in display order.

Notes

  • Header cells are named HEADER_PANE_TAB_ID_cell and skip the content-fit check, so long captions clip instead of showing the size notice.
  • The active tab is shown with the header button’s focus style.
  • The framework does not clear CONTENT_PANE between tabs; each action replaces what it needs.

Example

tui.tabs.add tab_log  "Log"   show_log true
tui.tabs.add tab_conf "Config" show_conf
tui.tabs.compact main_tabs
tui.tabs.build main_tabs tab_bar tab_body tab_log tab_conf

See also: tui.tabs.activate

tui.tabs.activate

tui.tabs.activate TAB_ID

Makes a tab active: focuses its header button and calls its action as ACTION TAB_ID.

Notes

  • Does nothing for a tab that is not part of a built group.

Factory (runtime widgets)

Constructors for layouts whose shape is only known at runtime. Ids are generated and tracked per namespace, so one call tears everything down again.

Function Summary
tui.factory.label Creates a label with a generated id, tracked under namespace NS.
tui.factory.button Creates a button with a generated id, tracked under namespace NS. ACTION is called as ACTION ID.
tui.factory.input Creates a single-line input with a generated id, tracked under namespace NS.
tui.factory.checkbox Creates a checkbox with a generated id, tracked under namespace NS.
tui.factory.grid Builds a grid of COUNT cells with generated pane ids, for layouts whose size is only known at runtime.
tui.factory.clear Removes every widget and pane created under namespace NS and turns its grid parents back into empty leaf panes.

tui.factory.label

tui.factory.label NS PANE ROW TEXT

Creates a label with a generated id, tracked under namespace NS.

Sets: _TUI_FACTORY_LAST_ID to the new id (__f_NS_N).

Notes

  • The id is not printed: stdout is the screen. Read _TUI_FACTORY_LAST_ID right after the call.
  • _TUI_FACTORY_LAST_ID and _TUI_FACTORY_GRID_CELLS are the only underscore names app code may read.

See also: tui.label, tui.factory.clear

tui.factory.button

tui.factory.button NS PANE ROW TEXT [ACTION]

Creates a button with a generated id, tracked under namespace NS. ACTION is called as ACTION ID.

Sets: _TUI_FACTORY_LAST_ID.

Example

for f in *.log; do
    tui.factory.button files list_pane "$((row++))" "$f" open_file
done

See also: tui.button

tui.factory.input

tui.factory.input NS PANE ROW [PLACEHOLDER] [LABEL] [SUBMIT]

Creates a single-line input with a generated id, tracked under namespace NS.

Sets: _TUI_FACTORY_LAST_ID.

See also: tui.input

tui.factory.checkbox

tui.factory.checkbox NS PANE ROW LABEL [CHECKED] [ACTION]

Creates a checkbox with a generated id, tracked under namespace NS.

Sets: _TUI_FACTORY_LAST_ID.

See also: tui.checkbox

tui.factory.grid

tui.factory.grid NS PARENT COUNT [COLS] [FIT] [ROW_WEIGHTS] [COL_WEIGHTS]

Builds a grid of COUNT cells with generated pane ids, for layouts whose size is only known at runtime.

Parameters

  • COUNT: number of cells.
  • COLS: columns. Omitted: near-square.
  • FIT, ROW_WEIGHTS, COL_WEIGHTS: as in tui.grid.

Sets: _TUI_FACTORY_GRID_CELLS (array of cell ids, in order).

Example

tui.factory.clear tiles
tui.factory.grid tiles board "${#items[@]}" 4
for i in "${!items[@]}"; do
    tui.factory.button tiles "${_TUI_FACTORY_GRID_CELLS[$i]}" 0 "${items[$i]}" pick
done
tui.relayout

See also: tui.factory.clear

tui.factory.clear

tui.factory.clear NS

Removes every widget and pane created under namespace NS and turns its grid parents back into empty leaf panes.

Notes

  • Safe on a namespace that is empty or already cleared.
  • Does not repaint. Call tui.relayout after rebuilding.
  • Everything is also dropped on page change.

Content and output

Text content of leaf panes. Repaints are queued and coalesced, so several updates in one callback cost one frame.

Function Summary
tui.output Replaces the pane’s content with text, or with stdin when no TEXT is given.
tui.output_append Appends lines to the pane’s content, from arguments or stdin.
tui.output_clear Empties the pane’s content and repaints the pane immediately.
tui.set_text Replaces the pane’s content like tui.output, but skips the work when TEXT equals what it set last time.
tui.set_canvas Sets the pane’s content to a ready-made frame: one line per row, each already as wide as the pane’s content area. The pane draws the lines as they are, in its own style.
tui.canvas.source Names the function that keeps the frame of a canvas pane, for an animation that draws changes with tui.canvas.patch instead of sending the whole frame.
tui.canvas.fresh Returns 0 while the last canvas frame (or patch) is still what the screen shows, because nothing else has painted since. Returns 1 otherwise.
tui.canvas.patch Draws BYTES over the canvas at once, in one flush: absolute cursor moves and cells, for example only the cells an animation changed.

tui.output

tui.output PANE [TEXT...]
some_command | tui.output PANE

Replaces the pane’s content with text, or with stdin when no TEXT is given.

Parameters

  • TEXT...: joined with spaces, then split on newlines. ANSI escapes are kept.

Notes

  • The repaint is queued and coalesced with other changes in the same frame.
  • PANE must be a valid bash identifier (letters, digits, _): the content is stored in a variable named after it.
  • Reading stdin (cmd | tui.output) costs a pipeline fork; for text updated in a loop use tui.set_text.
  • Don’t mix tui.output and tui.set_text on the same pane: tui.set_text skips text it thinks is already shown.

Example

tui.output log "line one"
tui.output log "$(ls -la)"
df -h | tui.output disk

See also: tui.output_append, tui.pane_scroll

tui.output_append

tui.output_append PANE [TEXT...]
some_command | tui.output_append PANE

Appends lines to the pane’s content, from arguments or stdin.

Notes

  • Content is kept in memory without a limit. For a long-running log, trim it yourself or use tui.exec.

See also: tui.output

tui.output_clear

tui.output_clear PANE

Empties the pane’s content and repaints the pane immediately.

tui.set_text

tui.set_text PANE TEXT

Replaces the pane’s content like tui.output, but skips the work when TEXT equals what it set last time.

Notes

  • Fork-free. Use it for anything updated from timers or tick functions.
  • The cache is per pane and cleared on page change. After changing the pane through another function, the next tui.set_text with the old text is skipped; don’t mix them on one pane.

Example

refresh() { tui.sys.cpu; tui.set_text cpu "CPU ${TUI_SYS_CPU}%"; }
tui.every 1 refresh

tui.set_canvas

tui.set_canvas PANE TEXT

Sets the pane’s content to a ready-made frame: one line per row, each already as wide as the pane’s content area. The pane draws the lines as they are, in its own style.

Parameters

  • PANE: pane id.
  • TEXT: the rows, separated by newlines. ANSI colours are allowed. Rows past the content area are dropped, and a row narrower than the area leaves the cells after it as they were, so write blanks.

Notes

  • Nothing is measured or cut, which makes it much cheaper than tui.set_text with coloured text, and it is drawn at once, not debounced. Use it for animation (the Home page’s matrix rain is drawn this way, at over 20 frames a second).
  • The pane’s style returns after every ESC[0m inside a line, so a styled cell does not turn the cells after it into the terminal’s default colours.
  • The pane does not report itself too small for its content: no width is measured, and any width remembered from earlier text is dropped.
  • Skipped when TEXT equals what it set last time. While nothing else has painted since the last frame, only the rows that differ from it are sent (a blinking cursor is one row). Cleared on page change.
  • For an animation that changes a few cells, tui.canvas.patch sends only those cells.

Example

tick() {
	local frame="" r
	for ((r = 0; r < 5; r++)); do frame+=$'\e[32m'"$(printf '%*s' 30 '' | tr ' ' '#')"$'\e[0m\n'; done
	tui.set_canvas screen "${frame%$'\n'}"
}
tui.every 0.2 tick

tui.canvas.source

tui.canvas.source PANE FN

Names the function that keeps the frame of a canvas pane, for an animation that draws changes with tui.canvas.patch instead of sending the whole frame.

Parameters

  • PANE: pane id.
  • FN: called as FN PANE before every full paint of the pane (a page render, a resize, a layer closing over it). It sets _TUI_PANE_RAW[PANE] to the whole frame as tui.set_canvas takes it.

Notes

  • Cleared on page change.

tui.canvas.fresh

tui.canvas.fresh

Returns 0 while the last canvas frame (or patch) is still what the screen shows, because nothing else has painted since. Returns 1 otherwise.

Notes

  • Only then can a patch be drawn over the canvas: after any other paint the cells under it are not known.

tui.canvas.patch

tui.canvas.patch PANE BYTES

Draws BYTES over the canvas at once, in one flush: absolute cursor moves and cells, for example only the cells an animation changed.

Parameters

  • PANE: pane id.
  • BYTES: the cells to draw, with absolute cursor moves. Nothing is measured or cut.

Notes

  • Use it only while tui.canvas.fresh returns 0; otherwise send the whole frame with tui.set_canvas.
  • The caller keeps the frame in step (see tui.canvas.source). The Home page paints its banner this way: a blinking cursor is one small write, not the whole hero.
  • The rows tui.set_canvas remembers are dropped, so its next frame sends every row.

Background painters

Painters run in background processes and draw directly to the terminal with absolute cursor moves, so their frames cost the main loop nothing and a hover or focus highlight is never queued behind them. A painter receives updates from the main loop through small state files and sleeps without forking.

Function Summary
tui.async.start Forks FN with ARG… into the background as a painter: a function running in its own process that paints directly to the terminal with absolute cursor moves, so its frames cost the main loop nothing.
tui.async.stop Ends the painter named NAME, if it exists.
tui.async.stop_all Ends every painter and removes the state directory.
tui.async.active Returns 0 while a painter is running; 1 when none are running, or when NAME is given and that painter is not running.
tui.async.put The main loop’s way to send a small value to a painter: writes VALUE to a temporary file that the painter can read with tui.async.get.
tui.async.get Inside a painter: reads a value sent by the main loop via tui.async.put into VAR.
tui.async.wait Inside a painter: sleeps without forking, by waiting on a pipe that is held open and never written. Returns immediately after the timeout, or when the main process exits.
tui.async.emit Inside a painter: sends FRAME to the terminal. A painter’s stdout is closed, so this is the only way it draws.
tui.async.covered Inside a painter: returns 0 while something is open over the page (a modal, the command palette, a dialog, or a layer); 1 when the page is fully visible.

tui.async.start

tui.async.start NAME FN [ARG...]

Forks FN with ARG… into the background as a painter: a function running in its own process that paints directly to the terminal with absolute cursor moves, so its frames cost the main loop nothing.

Parameters

  • NAME: identifier for this painter. A second start with the same NAME kills the first.
  • FN: the function to run.
  • ARG...: arguments passed to FN.

Notes

  • The painter runs with the process’s own copy of the page state as it was at fork time, and its stdin is /dev/null.
  • The painter process is trapped to exit cleanly on TERM, HUP and INT signals.
  • The parent process id is stored in _TUI_ASYNC_PARENT; a painter can check kill -0 "$_TUI_ASYNC_PARENT" to detect when the main process is gone and exit itself.
  • Painters are stopped by tui.async.stop, tui.async.stop_all, and automatically on app exit.

Example

counter_painter() {
	local count=0
	while kill -0 "$_TUI_ASYNC_PARENT" 2>/dev/null; do
		tui.async.get "counter.count" count
		count=${count:-0}
		printf '\e[2;5H%d' "$count"
		tui.async.wait 0.1
	done
}

# Start the painter
tui.async.start counter counter_painter

# In the main loop: update the counter
tui.async.put counter count 5

See also

tui.async.stop

tui.async.stop NAME

Ends the painter named NAME, if it exists.

Parameters

Notes

  • Returns 0 whether or not a painter by that name exists.
  • Sends SIGTERM to the process and waits for it to exit.
  • Called automatically by tui.async.stop_all, and on app exit.

See also

tui.async.stop_all

tui.async.stop_all

Ends every painter and removes the state directory.

Notes

  • Called automatically on app exit.
  • Cleans up temporary files and pipes used for painter communication.

See also

tui.async.active

tui.async.active [NAME]

Returns 0 while a painter is running; 1 when none are running, or when NAME is given and that painter is not running.

Parameters

  • NAME: optional. When given, check only that painter. When omitted, check whether any painter is running.

Notes

  • This is a check function: it returns an exit code, not a value. Use it in if statements or as a condition.
  • A painter can use kill -0 "$_TUI_ASYNC_PARENT" to detect when the main process is gone.

Example

# Check if a specific painter is running
if tui.async.active background_task; then
	echo "Background task is still running"
fi

# Check if any painter is running
if tui.async.active; then
	echo "At least one painter is running"
fi

See also

tui.async.put

tui.async.put NAME KEY VALUE

The main loop’s way to send a small value to a painter: writes VALUE to a temporary file that the painter can read with tui.async.get.

Parameters

  • NAME: the painter’s identifier, as given to tui.async.start.
  • KEY: the key name for this value.
  • VALUE: the value to send (typically a size, mask, or flag).

Notes

  • The file is stored at $_TUI_ASYNC_DIR/$NAME.$KEY. Use short values: the file is read with read -r, so long values are truncated.
  • Intended for passing configuration or state updates: rectangles, masks, coordinates, small strings.
  • Multiple calls with the same NAME and KEY overwrite the previous value.

Example

# Tell the painter to draw a 20x10 rectangle
tui.async.put my_painter viewport "20x10"

# Update the painter with new mask data
tui.async.put my_painter mask "1010101010"

See also

tui.async.get

tui.async.get KEY VAR

Inside a painter: reads a value sent by the main loop via tui.async.put into VAR.

Parameters

  • KEY: the key to read. Use NAME.KEY format, where NAME is the painter’s identifier from tui.async.start.
  • VAR: the variable to store the value in (passed by name, not reference).

Notes

  • Returns 0 always. If the key does not exist, VAR is set to an empty string.
  • The file is read with IFS= read -r, so trailing whitespace and newlines are preserved, but the line is truncated at the first newline by the shell’s read builtin.
  • Typically used inside the painter loop to receive updates from the main process.

Example

painter_fn() {
	local count
	while kill -0 "$_TUI_ASYNC_PARENT" 2>/dev/null; do
		tui.async.get "mypaint.count" count
		count=${count:-0}
		printf '\e[2;5H%d' "$count"
		tui.async.wait 0.1
	done
}

See also

tui.async.wait

tui.async.wait SECONDS

Inside a painter: sleeps without forking, by waiting on a pipe that is held open and never written. Returns immediately after the timeout, or when the main process exits.

Parameters

  • SECONDS: the timeout in seconds (can be fractional, e.g. 0.1).

Notes

  • More efficient than sleep inside a painter: it does not fork a new process.
  • The wait is interrupted when the main process exits (if the painter checks kill -0 "$_TUI_ASYNC_PARENT" next).
  • Use in painter loops to control frame rate without blocking the terminal.

Example

painter_fn() {
	while kill -0 "$_TUI_ASYNC_PARENT" 2>/dev/null; do
		# Draw current frame
		printf '\e[2;1H%s' "Frame painted at $(date)"
		# Wait 100 milliseconds before the next frame
		tui.async.wait 0.1
	done
}

See also

tui.async.emit

tui.async.emit FRAME [PREFIX]

Inside a painter: sends FRAME to the terminal. A painter’s stdout is closed, so this is the only way it draws.

Parameters

  • FRAME: absolute cursor moves and cells, as small as possible (changes only).
  • PREFIX: the style the frame starts with. It is repeated at the start of each piece when the frame is cut in pieces.

Notes

  • The frame goes out through the same writer as the main loop’s frames, one write call per piece, so it never lands inside what the main loop is writing and the main loop’s never inside it.
  • A painter can skip a frame when tui.async.get gen VAR shows the main loop has written since the painter’s last frame, so a highlight never queues behind an animation.

See also

tui.async.covered

tui.async.covered

Inside a painter: returns 0 while something is open over the page (a modal, the command palette, a dialog, or a layer); 1 when the page is fully visible.

Notes

  • A painter should paint nothing while covered: rendering on top of a modal or dialog would corrupt what is on top.
  • Use in the painter loop to skip drawing when covered returns 0.
  • The covered state is updated by the main loop as modals and layers open and close.

Example

painter_fn() {
	while kill -0 "$_TUI_ASYNC_PARENT" 2>/dev/null; do
		# Only paint when the page is visible
		if ! tui.async.covered; then
			printf '\e[5;10H%s' "Visible"
		fi
		tui.async.wait 0.5
	done
}

See also

Process streaming (tui.exec)

Function Summary
tui.exec Runs a shell command in a pseudo-terminal and streams its output into a pane while the UI stays responsive.
tui.exec.cancel_pane Kills and dismisses every tui.exec instance targeting PANE, running or finished, and empties the pane.

tui.exec

tui.exec CMD OUT_PANE [CTL_PANE]

Runs a shell command in a pseudo-terminal and streams its output into a pane while the UI stays responsive.

Parameters

  • CMD: command line, run by script -q -e -c CMD.
  • OUT_PANE: pane that shows the output.
  • CTL_PANE: optional pane that gets Cancel, Save Output, View Command, Retry and Back buttons plus an input box that sends a line to the process’s stdin.

Returns: 1 when CMD or OUT_PANE is empty.

Notes

  • Several instances may run at once, also into the same pane. Each gets an instance id (e1, e2, …); later instances in a shared pane print a ── [eN] started ── separator.
  • Needs the util-linux script. BSD/macOS script takes different options.
  • Running instances are killed on page change and on exit.
  • Save Output writes exec_output_<id>_<timestamp>.log into the current directory.
  • To restart cleanly in a pane (one process at a time), call tui.exec.cancel_pane first.

Example

tui.exec "ping -c 5 example.com" out ctl

tui.exec.cancel_pane

tui.exec.cancel_pane PANE

Kills and dismisses every tui.exec instance targeting PANE, running or finished, and empties the pane.

Example

on_visit_shell() {
    tui.exec.cancel_pane term      # one shell per visit, not one more per visit
    tui.exec "bash -i" term
}

Live updates

Timers, clocks, watches and the system samplers share one tick listener, cost no fork per update, and are cleared on page change and exit.

Function Summary
tui.every Calls FN repeatedly on a timer from the main loop.
tui.after Calls FN ID once, SEC seconds from now.
tui.every.cancel Removes a timer created by tui.every, tui.after, tui.clock or tui.monitor. Unknown ids are ignored.
tui.every.pause Stops a timer from firing until tui.every.resume is called.
tui.every.resume Resumes a paused timer. It fires on the next loop iteration, then at its normal interval.
tui.every.clear Removes every timer, including clocks and monitors. Watches from tui.watch keep running.
tui.every.list Prints one line per timer.
tui.clock Shows a live clock in a pane, updated on every whole second.
tui.watch Runs a shell command every SEC seconds in the background and shows its latest output in a pane, like watch.
tui.watch.stop Stops a watch and kills its background process. Unknown ids are ignored.
tui.watch.now Restarts a watch so its command runs again right away.
tui.monitor Shows a ready-made system dashboard in a pane: CPU, memory and swap gauges, a CPU history sparkline, memory in MB, load average and uptime.
tui.sys.cpu Samples CPU usage since the previous call, fork-free.
tui.sys.mem Samples memory and swap usage from /proc/meminfo, fork-free.
tui.sys.load Reads the load averages from /proc/loadavg.
tui.sys.uptime Reads the system uptime from /proc/uptime.
tui.hist.push Appends a value to a named rolling series, dropping the oldest beyond MAX.
tui.hist.get Prints a series, oldest first. With VAR the series is stored in that variable instead, which costs no subshell.

tui.every

tui.every SEC FN [ID]

Calls FN repeatedly on a timer from the main loop.

Parameters

  • SEC: interval in seconds; decimals allowed (0.25). Values below 0.05 are raised to 0.05.
  • FN: function, called as FN ID.
  • ID: timer id for tui.every.cancel and friends. Default: FN.

Notes

  • The first call happens on the next loop iteration, not after SEC. Use tui.after for a delayed start.
  • Registering an existing ID again replaces that timer and resumes it if paused. Pass distinct IDs to run one function on two timers.
  • Timers are removed on page change. Register them again from the page’s on_visit.
  • After a terminal resize every timer runs on the next iteration, so size-dependent output re-fits at once.
  • FN runs inside the main loop: keep it fork-free (tui.set_text, tui.sys.*). Slow work belongs in tui.watch.
  • Everything FN updates (tui.update, tui.set_label, bound datasets) is drawn once, in one write, after it returns, and at most once per frame (TUI_FRAME_BUDGET_US, default 16666 = 60 fps) however many timers fire. Values that did not change are not drawn. Button and key reactions are never held to the frame budget.
  • A timer that is late by whole intervals loses those ticks instead of catching up, and one that ran longer than its interval rests as long as it ran. With _TUI_PERF_TRACKING=1, tui.perf.report shows ticks_dropped, paced_deferred and a tick:ID span per timer (the slowest one is the culprit).
  • Timers registered while a plugin loads are removed when that plugin is disabled.

Example

refresh_stats() {
    tui.sys.cpu; tui.sys.mem
    tui.set_text stats "CPU ${TUI_SYS_CPU}%  MEM ${TUI_SYS_MEM_PCT}%"
}
tui.every 2 refresh_stats

See also: tui.after, tui.tick.add, tui.watch

tui.after

tui.after SEC FN [ID]

Calls FN ID once, SEC seconds from now.

Parameters

Notes

  • The timer is removed before FN runs, so FN may schedule itself again with the same ID.
  • Cancelled by page change like every timer.

Example

tui.notify "Saved" success
tui.after 3 clear_status

tui.every.cancel

tui.every.cancel ID

Removes a timer created by tui.every, tui.after, tui.clock or tui.monitor. Unknown ids are ignored.

tui.every.pause

tui.every.pause ID

Stops a timer from firing until tui.every.resume is called.

tui.every.resume

tui.every.resume ID

Resumes a paused timer. It fires on the next loop iteration, then at its normal interval.

tui.every.clear

tui.every.clear

Removes every timer, including clocks and monitors. Watches from tui.watch keep running.

tui.every.list

tui.every.list

Prints one line per timer.

Output: ID<TAB>INTERVALms<TAB>FN, e.g. refresh_stats 2000ms refresh_stats.

tui.clock

tui.clock PANE [FORMAT] [FONT] [ID]

Shows a live clock in a pane, updated on every whole second.

Parameters

  • FORMAT: strftime format. Default: %H:%M:%S.
  • FONT: a banner font (block5, seg3, box3, blk3, half2) for big digits, styled with the pane’s colors. Empty: plain text.
  • ID: timer id. Default: clock_PANE.

Notes

  • Stops itself when PANE no longer exists.
  • Loads terminal_renderer.sh on first use of a font.

Example

tui.clock header_clock "%a %H:%M" seg3

tui.watch

tui.watch PANE CMD [SEC] [ID]

Runs a shell command every SEC seconds in the background and shows its latest output in a pane, like watch.

Parameters

  • CMD: shell code, evaluated with eval in a background subshell.
  • SEC: interval. Default: 2. Minimum 0.05.
  • ID: watch id. Default: watch_PANE.

Returns: 1 when PANE or CMD is empty.

Notes

  • The UI never waits for CMD. Only the newest complete output is shown; stderr is discarded.
  • Starting a watch with an existing ID restarts it.
  • Stopped on page change, on exit, and when PANE no longer exists.

Example

tui.watch disk "df -h /" 5

See also: tui.watch.stop, tui.watch.now

tui.watch.stop

tui.watch.stop ID

Stops a watch and kills its background process. Unknown ids are ignored.

tui.watch.now

tui.watch.now ID

Restarts a watch so its command runs again right away.

Returns: 1 for an unknown id.

Example

on_refresh() { tui.watch.now watch_disk; }

tui.monitor

tui.monitor PANE [SEC] [ID]

Shows a ready-made system dashboard in a pane: CPU, memory and swap gauges, a CPU history sparkline, memory in MB, load average and uptime.

Parameters

  • SEC: refresh interval. Default: 1.
  • ID: timer id. Default: monitor_PANE.

Notes

  • Linux only: reads /proc.
  • Gauges size themselves to the pane width.

tui.sys.cpu

tui.sys.cpu

Samples CPU usage since the previous call, fork-free.

Sets: TUI_SYS_CPU (integer percent).

Returns: 1 when /proc/stat can’t be read.

Notes

  • The first call measures since boot. Call it once to prime, then read it on a timer.
  • Linux only.

tui.sys.mem

tui.sys.mem

Samples memory and swap usage from /proc/meminfo, fork-free.

Sets: TUI_SYS_MEM_PCT, TUI_SYS_MEM_USED_MB, TUI_SYS_MEM_TOTAL_MB, TUI_SYS_SWAP_PCT.

Notes

  • “Used” is total minus available, so file cache does not count as used. Linux only.

tui.sys.load

tui.sys.load

Reads the load averages from /proc/loadavg.

Sets: TUI_SYS_LOAD1, TUI_SYS_LOAD5, TUI_SYS_LOAD15 (decimal strings, e.g. 0.42).

tui.sys.uptime

tui.sys.uptime

Reads the system uptime from /proc/uptime.

Sets: TUI_SYS_UPTIME (seconds), TUI_SYS_UPTIME_STR (2d 03h 14m).

tui.hist.push

tui.hist.push NAME VALUE [MAX]

Appends a value to a named rolling series, dropping the oldest beyond MAX.

Parameters

  • VALUE: one word; values are stored space-separated.
  • MAX: series length. Default: 60.

Example

tui.sys.cpu; tui.hist.push cpu "$TUI_SYS_CPU" 120

See also: tui.hist.get

tui.hist.get

tui.hist.get NAME [VAR]

Prints a series, oldest first. With VAR the series is stored in that variable instead, which costs no subshell.

Output: values separated by spaces, no trailing newline. Charts such as linechart expect commas: v=$(tui.hist.get cpu); linechart "cpu:${v// /,}".

Getters

Read-only. Pane getters return 1 for an unknown pane.

Function Summary
tui.exists Succeeds when a widget, a pane or a layer has that id. Prints nothing and does not fork, so it is safe in a callback that runs often.
tui.get.dimensions Prints the size of the terminal or of a pane.
tui.get.terminal Prints the terminal size as ROWS COLS.
tui.get.position Prints the top-left corner of a pane as ROW COL (1-based). Returns 1 for an unknown pane.
tui.get.rect Prints the outer rectangle of a pane as ROW COL HEIGHT WIDTH. Returns 1 for an unknown pane.
tui.get.content_area Prints the usable rectangle inside border and padding as ROW COL HEIGHT WIDTH. Returns 1 for an unknown pane.
tui.get.border Prints the border actually drawn: single, double, heavy or none. Returns 1 for an unknown pane.
tui.get.title Prints the pane title (empty when none). Returns 1 for an unknown pane.
tui.get.pad Prints the pane padding as HPAD VPAD. Returns 1 for an unknown pane.
tui.get.split Prints how a pane is split: h, v, f (fixed) or empty for a leaf. Returns 1 for an unknown pane.
tui.get.children Prints the child pane ids on one line, space-separated (empty for a leaf). Returns 1 for an unknown pane.
tui.get.parent Prints the id of the pane that contains PANE. Returns 1 for root or an unknown pane.
tui.get.panes Prints every pane id, one per line; with leaves, only panes without children.
tui.get.lines Prints the number of output lines a pane holds (0 for none or an unknown pane).
tui.get.scroll Prints the scroll state as MODE V_OFFSET H_OFFSET LINES MAX_WIDTH, e.g. v 12 0 240 80. Returns 1 for an unknown pane.
tui.get.style Prints one resolved style field of a pane or widget.
tui.get.widgets Prints widget ids in draw order, one per line: all of them, or only those in PANE.
tui.get.type Prints the widget type: label, button, input, checkbox, password, textarea, list, table, select or progress. Returns 1 for an unknown id.
tui.get.pane Prints the pane a widget lives in. Returns 1 for an unknown id.
tui.get.action Prints the action function of a widget (empty when none or unknown).
tui.get.checked Prints nothing; returns 0 when ID is a checked checkbox, else 1.
tui.get.focused Prints the id of the focused widget (empty when none).
tui.get.hovered Prints the id of the widget (default) or pane under the mouse pointer (empty when none).
tui.get.pane_focus Prints the keyboard pane: the scroll target with the highlighted border (empty when none).
tui.get.page Prints the absolute path of the current page file (empty before a page is loaded).
tui.get.page_name Prints the name of the current page: its file name without the directory and the extension (nav_1 for /app/config/nav_1.xml). Empty before a page is loaded. tui.get.page prints the full path.
tui.get.pages Prints the pages linked by a <button page="…"> so far, sorted, one per line as PAGE<TAB>TITLE.
tui.get.event Prints the current input event on one line: type=… key=… x=… y=… pane=… widget=… button=….
tui.get.classes Prints every key the loaded theme defines, sorted, one per line.
tui.get.class.style Prints one field of a theme class, without a pane or widget.
tui.get.raw_input Prints the bytes the terminal sent for the last key or mouse press, with control characters in caret notation: ^[ is ESC, ^? is DEL, ^A is ctrl+a. Pointer motion is not recorded.
tui.errors.capture Sends the process’s standard error to a file that the tick loop reads, so nothing a command or bash itself complains about (file: line 12: x: bad array subscript) is drawn over the screen. tui.init turns it on and tui.cleanup turns it off.
tui.errors.list Prints the last 50 captured errors, one per line: TIME<TAB>MESSAGE<TAB>CONTEXT.
tui.errors.count Prints how many distinct error messages were captured in this run.

tui.exists

tui.exists ID

Succeeds when a widget, a pane or a layer has that id. Prints nothing and does not fork, so it is safe in a callback that runs often.

Returns: 0 when the id exists, 1 when it does not or ID is empty.

Notes

  • Use it to guard a callback that may run on a page where the widget is not (a poll that updates a tile of another page). tui.get.type only answers for widgets.

Example

tui.exists lbl_sent && tui.set_label lbl_sent "requests: $count"

tui.get.dimensions

tui.get.dimensions [-r|--rows] [-c|--columns] [--content] [PANE]

Prints the size of the terminal or of a pane.

Parameters

  • -r, --rows / -c, --columns: print only that number.
  • --content: the pane’s usable area inside border and padding.
  • PANE: omitted = the terminal.

Output: ROWS COLS, or one number with -r/-c.

Returns: 1 for an unknown pane.

Example

read -r rows cols <<<"$(tui.get.dimensions --content chart)"
cols=$(tui.get.dimensions -c)          # terminal width

See also: tui.pane_size (same numbers without a subshell)

tui.get.terminal

tui.get.terminal

Prints the terminal size as ROWS COLS.

tui.get.position

tui.get.position PANE

Prints the top-left corner of a pane as ROW COL (1-based). Returns 1 for an unknown pane.

tui.get.rect

tui.get.rect PANE

Prints the outer rectangle of a pane as ROW COL HEIGHT WIDTH. Returns 1 for an unknown pane.

tui.get.content_area

tui.get.content_area PANE

Prints the usable rectangle inside border and padding as ROW COL HEIGHT WIDTH. Returns 1 for an unknown pane.

tui.get.border

tui.get.border PANE

Prints the border actually drawn: single, double, heavy or none. Returns 1 for an unknown pane.

Notes

  • This is the effective style: a border that does not fit, or an unset border on a parent pane, prints none.

tui.get.title

tui.get.title PANE

Prints the pane title (empty when none). Returns 1 for an unknown pane.

tui.get.pad

tui.get.pad PANE

Prints the pane padding as HPAD VPAD. Returns 1 for an unknown pane.

tui.get.split

tui.get.split PANE

Prints how a pane is split: h, v, f (fixed) or empty for a leaf. Returns 1 for an unknown pane.

Notes

  • A pane built with tui.grid prints v: a grid is a vertical split into rows.

tui.get.children

tui.get.children PANE

Prints the child pane ids on one line, space-separated (empty for a leaf). Returns 1 for an unknown pane.

tui.get.parent

tui.get.parent PANE

Prints the id of the pane that contains PANE. Returns 1 for root or an unknown pane.

tui.get.panes

tui.get.panes [leaves]

Prints every pane id, one per line; with leaves, only panes without children.

tui.get.lines

tui.get.lines PANE

Prints the number of output lines a pane holds (0 for none or an unknown pane).

tui.get.scroll

tui.get.scroll PANE

Prints the scroll state as MODE V_OFFSET H_OFFSET LINES MAX_WIDTH, e.g. v 12 0 240 80. Returns 1 for an unknown pane.

tui.get.style

tui.get.style ID FIELD [STATE]

Prints one resolved style field of a pane or widget.

Parameters

  • FIELD: fg, bg or mods.
  • STATE: normal (default), focus, border, title, hover, checked, unchecked. A state with no rules falls back to normal.

Returns: 2 and a message on stderr for any other FIELD.

See also: tui.style.sgr (fork-free), tui.get.class.style

tui.get.widgets

tui.get.widgets [PANE]

Prints widget ids in draw order, one per line: all of them, or only those in PANE.

tui.get.type

tui.get.type ID

Prints the widget type: label, button, input, checkbox, password, textarea, list, table, select or progress. Returns 1 for an unknown id.

tui.get.pane

tui.get.pane ID

Prints the pane a widget lives in. Returns 1 for an unknown id.

tui.get.action

tui.get.action ID

Prints the action function of a widget (empty when none or unknown).

tui.get.checked

tui.get.checked ID

Prints nothing; returns 0 when ID is a checked checkbox, else 1.

Notes

  • Use it in a condition: if tui.get.checked chk_a; then .... tui.get prints the value as 0/1.

tui.get.focused

tui.get.focused

Prints the id of the focused widget (empty when none).

tui.get.hovered

tui.get.hovered [widget|pane]

Prints the id of the widget (default) or pane under the mouse pointer (empty when none).

tui.get.pane_focus

tui.get.pane_focus

Prints the keyboard pane: the scroll target with the highlighted border (empty when none).

tui.get.page

tui.get.page

Prints the absolute path of the current page file (empty before a page is loaded).

tui.get.page_name

tui.get.page_name

Prints the name of the current page: its file name without the directory and the extension (nav_1 for /app/config/nav_1.xml). Empty before a page is loaded. tui.get.page prints the full path.

tui.get.pages

tui.get.pages

Prints the pages linked by a <button page="…"> so far, sorted, one per line as PAGE<TAB>TITLE.

Notes

  • PAGE is the path as written in the page attribute; TITLE is the button caption.
  • The command palette uses this list to offer page commands.

tui.get.event

tui.get.event

Prints the current input event on one line: type=… key=… x=… y=… pane=… widget=… button=….

Notes

  • Meant for debugging. In handlers read the TUI_EVENT_* variables directly (see the module intro).

tui.get.classes

tui.get.classes

Prints every key the loaded theme defines, sorted, one per line.

Notes

  • Pseudo-states appear as CLASS_focus, CLASS_hover, …
  • Fork-free alternative: tui.class.names.

tui.get.class.style

tui.get.class.style CLASS FIELD [STATE]

Prints one field of a theme class, without a pane or widget.

Parameters

  • CLASS: class name without the dot.
  • FIELD: fg, bg or mods.
  • STATE: normal (default) or a pseudo-state such as focus; falls back to the plain class.

Returns: 2 for an invalid FIELD.

Example

accent=$(tui.get.class.style brand fg)

See also: tui.class.style (fork-free)

tui.get.raw_input

tui.get.raw_input

Prints the bytes the terminal sent for the last key or mouse press, with control characters in caret notation: ^[ is ESC, ^? is DEL, ^A is ctrl+a. Pointer motion is not recorded.

Notes

  • Meant for debugging key names: ^[[55;4u is alt+shift+7 as a kitty-style sequence, ^[7 is alt+7. The Debug > Feature lab shows it under “last input”.
  • The paste, focus and resize events are not recorded.

Example

tui.capture raw tui.get.raw_input

tui.errors.capture

tui.errors.capture on|off

Sends the process’s standard error to a file that the tick loop reads, so nothing a command or bash itself complains about (file: line 12: x: bad array subscript) is drawn over the screen. tui.init turns it on and tui.cleanup turns it off.

What happens to an error

  • It is written to the log at level error with where it happened, the key and action being handled, the page and the focus.
  • It is shown once as an error notification (at most one a second), with (see the log).
  • The same message again is only counted and logged again at the 10th, 100th and 1000th time.
  • When the app quits, the terminal gets one line: how many errors were logged and where.

Notes

  • TUI_ERR_TRACE=1 also traces every command (slow) so each error carries the call stack of the command that failed: stack: inner < mid < outer @ file:line.
  • TUI_ERR_CAPTURE=0 leaves stderr alone, for debugging the framework itself.

Example

TUI_ERR_TRACE=1 ./my_app.sh   # then: tail the log for "stack:" lines

tui.errors.list

tui.errors.list

Prints the last 50 captured errors, one per line: TIME<TAB>MESSAGE<TAB>CONTEXT.

tui.errors.count

tui.errors.count

Prints how many distinct error messages were captured in this run.

Logging and perf

Function Summary
tui.debug.bar Shows or hides the debug status strip above the footer and gives its row back to the page when hidden.
tui.debug.segment Registers a segment of the debug strip; FN sets _DBG_SEG to its text, and an empty text hides it.
tui.debug.segment.toggle Switches one debug-strip segment on or off.
tui.debug.init Starts the debug strip and binds F12 and a command-palette entry to its toggle; tui.init calls it when TUI_DEBUG is set.
tui.debug.devtools Opens or closes the dev-tools dock above the debug strip, or moves the keyboard to or from it; dabt --debug binds F11 to it.
tui.debug.event Counts the event NAME and appends it to the debug ring buffer; does nothing unless debugging is on (dabt --debug).
tui.debug.enable Turns debugging on, and perf tracking with it.
tui.debug.reset Clears the debug ring buffer and the event counters.
tui.log Appends a line to the app’s log file. stdout is the screen, so logs go to a file.
tui.log.debug Same as tui.log MSG debug; dropped without any work when the log level is above debug (tui.log.level). See tui.log.
tui.log.info Same as tui.log MSG info; dropped without any work when the log level is above info (tui.log.level). See tui.log.
tui.log.warn Same as tui.log MSG warn; dropped without any work when the log level is above warn (tui.log.level). See tui.log.
tui.log.error Same as tui.log MSG error; dropped without any work when the log level is above error (tui.log.level). See tui.log.
tui.log.level Prints the log level, or sets it. Lines below the level are not written.
tui.log.file Prints the path tui.log writes to today.
tui.perf.mean_render_ms Prints the mean frame render time in milliseconds over the last SECONDS.
tui.perf.report Prints one line per tracked span (span<TAB>name<TAB>mean_us<TAB>p95_us<TAB>count) and one line per counter (counter<TAB>name<TAB>total).
tui.perf.reset Clears every tracked span and counter.

tui.debug.bar

tui.debug.bar [on|off|toggle]

Shows or hides the debug status strip above the footer and gives its row back to the page when hidden.

Notes

  • Without an argument it toggles. dabt --debug starts with the strip on and binds F12 to the toggle.

tui.debug.segment

tui.debug.segment ID FN [left|right]

Registers a segment of the debug strip; FN sets _DBG_SEG to its text, and an empty text hides it.

Parameters

  • ID - segment name; registering the same ID again replaces it.
  • FN - called on every strip repaint, so it must not fork.
  • left|right - the side of the strip, default left.

Example

_seg_jobs() { _DBG_SEG="jobs ${#_MY_JOBS[@]}"; }
tui.debug.segment jobs _seg_jobs left

tui.debug.segment.toggle

tui.debug.segment.toggle ID

Switches one debug-strip segment on or off.

tui.debug.init

tui.debug.init

Starts the debug strip and binds F12 and a command-palette entry to its toggle; tui.init calls it when TUI_DEBUG is set.

tui.debug.devtools

tui.debug.devtools [open|close|toggle|focus|blur]

Opens or closes the dev-tools dock above the debug strip, or moves the keyboard to or from it; dabt --debug binds F11 to it.

Notes

  • Tabs: Events (live event log), Pages (page cache and loads), Perf (span timings), Counters (perf counters and event totals).
  • The dock takes about 30% of the terminal (at least 8 rows) from the page; m maximises it.
  • While it has focus: ←→ or 1-4 switch tab, ↑↓ pgup pgdn home end scroll, p pauses the Events tab, f cycles the category filter, c clears events, esc gives the keyboard back to the app and leaves the dock open.
  • Those keys are bound on focus and unbound on blur, so the app’s own keys work again once the dock is blurred.

tui.debug.event

tui.debug.event NAME [DETAIL]

Counts the event NAME and appends it to the debug ring buffer; does nothing unless debugging is on (dabt --debug).

Parameters

  • NAME - CATEGORY.what, e.g. cache.page.miss; the text before the first dot is the category.
  • DETAIL - free text kept with the event.

Notes

  • With categories set (--debug=cache,render) events of other categories are dropped.
  • Hot paths guard the call with ((TUI_DEBUG)) to skip the function call when debugging is off.

Example

((TUI_DEBUG)) && tui.debug.event cache.page.miss "$page"

tui.debug.enable

tui.debug.enable [CATEGORIES]

Turns debugging on, and perf tracking with it.

Parameters

  • CATEGORIES - comma list of event categories to keep (cache,render); empty keeps all.

Example

tui.debug.enable cache

tui.debug.reset

tui.debug.reset

Clears the debug ring buffer and the event counters.

tui.log

tui.log MSG [LEVEL]

Appends a line to the app’s log file. stdout is the screen, so logs go to a file.

Parameters

  • MSG: the message.
  • LEVEL: debug, info, warn or error; shown in brackets. Any other text counts as info for the filter and is shown as written. Default: info.

Output: nothing on screen. The file gets [HH:MM:SS] [LEVEL] MSG, unless LEVEL is below the log level (tui.log.level, default info): then nothing is written.

Notes

  • The file is ~/.config/DABT/apps/<TUI_APP_NAME>/logs/<yyyy-mm-dd>_<TUI_APP_NAME>.log (dabt when no app name is set). Set TUI_LOG_DIR before sourcing tui.sh to use another folder. tui.log.file prints the current path.
  • One file per day; an app running past midnight continues in the next day’s file.
  • Fork-free once the folder exists. A log folder that can’t be created or written is ignored silently; logging never fails the caller.
  • Logs are never rotated or deleted.

Example

tui.log "export started: $file"
tui.log.warn "config missing, using defaults"

See also: tui.log.level, tui.log.debug, tui.log.info, tui.log.warn, tui.log.error

tui.log.debug

tui.log.debug MSG

Same as tui.log MSG debug; dropped without any work when the log level is above debug (tui.log.level). See tui.log.

tui.log.info

tui.log.info MSG

Same as tui.log MSG info; dropped without any work when the log level is above info (tui.log.level). See tui.log.

tui.log.warn

tui.log.warn MSG

Same as tui.log MSG warn; dropped without any work when the log level is above warn (tui.log.level). See tui.log.

tui.log.error

tui.log.error MSG

Same as tui.log MSG error; dropped without any work when the log level is above error (tui.log.level). See tui.log.

tui.log.level

tui.log.level [NAME]

Prints the log level, or sets it. Lines below the level are not written.

Parameters

  • NAME: debug, info, warn, error or off. Without it the current level is printed.

Output: the current level when called without NAME. An unknown NAME prints the valid names to stderr, returns 1 and keeps the old level.

Notes

  • The start-up value is TUI_LOG_LEVEL (default info, in tui_configuration.sh). Change it later with this function: assigning TUI_LOG_LEVEL after tui.sh is loaded has no effect.
  • debug logs every page-build step: thousands of lines on a first launch and about 12 ms per page build. Use it while developing; leave it at info otherwise.
  • A dropped line costs one function call and one comparison. Nothing is formatted or written, and the log folder is not even created.

Example

tui.log.level debug     # while chasing a page-build problem
tui.log.level info

See also: tui.log, tui.log.file

tui.log.file

tui.log.file

Prints the path tui.log writes to today.

Output: e.g. /home/me/.config/DABT/apps/my_app/logs/2026-09-24_my_app.log.

Notes

  • The file may not exist yet: it is created by the first log line.

Example

tui.view "Log" "$(tail -n 200 "$(tui.log.file)" 2>/dev/null)"

tui.perf.mean_render_ms

tui.perf.mean_render_ms SECONDS [VAR]

Prints the mean frame render time in milliseconds over the last SECONDS.

With VAR the value is stored in that variable instead of printed, so the call needs no subshell.

Output: an integer, or nothing when tracking is off or no frame fell in the window.

Notes

  • Tracking is off by default. Set _TUI_PERF_TRACKING=1 to turn it on (used by the debug page and tools/debug/).

tui.perf.report

tui.perf.report

Prints one line per tracked span (span<TAB>name<TAB>mean_us<TAB>p95_us<TAB>count) and one line per counter (counter<TAB>name<TAB>total).

Notes

  • Tracking is off by default. Set _TUI_PERF_TRACKING=1 to turn it on.
  • TUI_PERF_LOG=FILE dumps this same report to FILE once, at exit.

tui.perf.reset

tui.perf.reset

Clears every tracked span and counter.

Background work

Work that takes noticeable time runs in a separate process, so the interface stays responsive; a spinner tells the user something is happening, and the result is shown only once it is complete. Changing a page that is already on screen (addons, generated content) does not go through a process at all: tui.page.refresh rebuilds just the panes that changed, within the budget of a page switch.

Function Summary
tui.job.run Runs WORKFN ARG... in the background and keeps the interface running. When it has finished, DONEFN ID RC OUTFILE is called in the main shell. If the work is still going after MS milliseconds, a spinner with TEXT shows in the top-right corner of the frame, so the user can see that something is happening.
tui.job.cancel Stops the background job ID started with tui.job.run. Its DONEFN is not called, its files are removed, and the spinner goes away if it was the last job.
tui.job.running Tells whether the background job ID is still pending, that is started with tui.job.run and its DONEFN not yet called.
tui.page.refresh Re-applies the addons on disk (and re-runs templates and loops) on the page that is on screen, and rebuilds only the panes whose content changed. A page switch has 100 ms; so does this.
tui.page.rebuild Builds the page FILE again in the background and shows it when it is complete. The options are those of tui.job.run, which runs it.

tui.job.run

tui.job.run [--delay MS] [--silent] [--label TEXT] ID WORKFN DONEFN [ARG...]

Runs WORKFN ARG... in the background and keeps the interface running. When it has finished, DONEFN ID RC OUTFILE is called in the main shell. If the work is still going after MS milliseconds, a spinner with TEXT shows in the top-right corner of the frame, so the user can see that something is happening.

Parameters

  • --delay MS: how long to wait before the spinner appears. Default $TUI_JOB_SPINNER_MS (100). Work that finishes sooner shows no spinner. 0 shows it at once.
  • --silent: never show the spinner, for work nobody waits for (background polling). --quiet is the same.
  • --label TEXT: the words next to the spinner. Default Working....
  • ID: names the job. Starting a job with an ID that is still pending cancels the earlier one first.
  • WORKFN: a function; it runs in a separate process.
  • DONEFN: a function; called with the job ID, the exit status of WORKFN, and the path of a file holding what WORKFN printed.

Returns: 1 for a missing or undefined function or a --delay that is not a whole number.

Notes

  • Because WORKFN is a separate process, it cannot change the main shell’s variables. Hand a result back as output: whatever it prints becomes OUTFILE, and it may write more files named "${TUI_JOB_PREFIX}name". Its error output goes to "${TUI_JOB_PREFIX}err". Nothing it prints reaches the terminal.
  • DONEFN is where the result goes on screen. Nothing is drawn before it runs, so a page or a list built by WORKFN appears all at once, never half-finished. The spinner is already gone when DONEFN runs, and the screen is repainted afterwards if DONEFN did not redraw it.
  • $TUI_JOB_PREFIX is also set while DONEFN runs, so it can read those files. They are removed when the app exits.
  • WORKFN starts with an empty job table, so a job it starts itself is its own: it cannot cancel the main shell’s job of the same ID, and its temp files carry the process id so they never collide with the main shell’s.
  • Several jobs can run at once. One spinner is shown for all of them, with (+N) for the others.

Example

build_report() { sleep 2; printf 'sales: 42\nreturns: 3\n'; }   # slow work, runs in the background
show_report() {                                                # $1 id, $2 exit status, $3 output file
    (($2 == 0)) && tui.set_text report "$(<"$3")" || tui.notify "Report failed" error
}
on_refresh() { tui.job.run --label "Building report..." report build_report show_report; }

See also: tui.job.cancel, tui.job.running, tui.page.rebuild

tui.job.cancel

tui.job.cancel ID

Stops the background job ID started with tui.job.run. Its DONEFN is not called, its files are removed, and the spinner goes away if it was the last job.

Returns: 1 when no job has that ID.

Notes

  • The job’s own process is stopped. A program that WORKFN started (for example sleep) can keep running until it ends.

See also: tui.job.running

tui.job.running

tui.job.running ID

Tells whether the background job ID is still pending, that is started with tui.job.run and its DONEFN not yet called.

Returns: 0 while the job is pending, 1 otherwise.

Example

tui.job.running report && return   # a refresh is already on its way

See also: tui.job.cancel

tui.page.refresh

tui.page.refresh

Re-applies the addons on disk (and re-runs templates and loops) on the page that is on screen, and rebuilds only the panes whose content changed. A page switch has 100 ms; so does this.

Returns: 0 when the screen is up to date, also when nothing changed.

Notes

  • Every page remembers the tree it was built from, so a refresh starts from that instead of parsing the page’s files again, which alone would take longer than the budget. It compares the result with what is on screen pane by pane and rebuilds a pane when its own attributes, its widgets or the weights of its child panes changed. Everything below a rebuilt pane is rebuilt with it. Typed text, ticked boxes and focus in the panes that did not change stay as they are.
  • The cost follows what changed, not the size of the page: on the Addons demo page (150 x 45), enabling one addon takes about 45 ms plus the redraw, five at once about 70 ms, and a refresh with nothing changed about 30 ms. Rebuilding generated widgets costs roughly 1.5 to 3 ms each.
  • When a change cannot be applied this way, the page is rebuilt in the background instead (tui.page.rebuild, with the spinner of tui.job.run). That happens when something outside the panes changed (a widget written directly under <tui>), when the root pane or a pane without an id would have to be rebuilt, or when the changed part contains <tabs> or another tag the incremental build does not handle. Give panes an id if addons are to change what is inside them.
  • A widget written outside all panes with pane="x" ties pane x (and the panes above it) to a full rebuild. Nest widgets inside their pane to keep them refreshable.
  • Afterwards the cached copy of the page is brought up to date by a quiet background job; a visit to the page before that finishes rebuilds it.

Example

cp new_banner.xml "$TUI_APP_CONF/addons/banner.xml"   # switch an addon on
: >"$TUI_APP_CONF/addons/old_addon.xml"               # switch one off (an empty file adds nothing)
tui.page.refresh                                      # the screen follows

See also: tui.page.rebuild, tui.addon.dir

tui.page.rebuild

tui.page.rebuild [--delay MS] [--label TEXT] FILE

Builds the page FILE again in the background and shows it when it is complete. The options are those of tui.job.run, which runs it.

Parameters

  • FILE: a page file. Use $_TUI_MARKUP_FILE for the page on screen.

Returns: 1 when FILE cannot be read.

Notes

  • The build is the same headless build the start-up warm-up does. Its result becomes the cached page, and if FILE is still the page on screen the app goes to it with a single redraw. The focused widget stays focused when it still exists.
  • If the user has moved to another page in the meantime, nothing is drawn; the next visit of FILE uses the new build.
  • A failed build keeps the old page and shows the reason in a toast.
  • It rebuilds the whole page, so it takes as long as a cold build. To apply an addon file you just wrote, use tui.page.refresh, which rebuilds only what changed and falls back to this function when it cannot.
  • --quiet only refreshes the cached copy of the page: no spinner, nothing drawn.

Example

regenerate_includes                                        # a file the page includes changed on disk
tui.page.rebuild --label "Updating page..." "$_TUI_MARKUP_FILE"

See also: tui.cache.forget, tui.addon.dir

Registry

Function Summary
tui.register Registers one or more handlers FN for NAME under KIND.
tui.registered Looks up NAME’s handlers under KIND into $_TUI_REGISTERED (space-joined, registration order).
tui.register.style_contract Registers NAME’s style contract (registry kind style): the pseudo-states it can enter and the framework classes it draws with, e.g. "states:hover focus" "classes:.list_sel".
tui.addon.dir Adds a directory whose *.xml files hold addons, so a plugin can ship its own page changes. The app’s own TUI_APP_CONF/addons is always read.
tui.addon.undir Forgets a folder that was registered with tui.addon.dir. Its addons stop applying to pages loaded from now on.
tui.cache.forget Drops everything cached for the page FILE, so its next visit builds it fresh.

tui.register

tui.register KIND NAME FN...

Registers one or more handlers FN for NAME under KIND.

Parameters

  • KIND - tag, widget, layout, validator, pseudo, expr, hook or style.
  • NAME - the tag/widget type/class name the handler is for.

Notes

  • A later registration for the same KIND/NAME is appended, not replaced - read tui.registered’s last word for “last wins”, or iterate the whole list for handlers that all run (hooks).
  • Made while $_TUI_REGISTRY_CURRENT_PLUGIN is set, a registration is attributed to that plugin, so disabling it can remove exactly what it added.

tui.registered

tui.registered KIND NAME

Looks up NAME’s handlers under KIND into $_TUI_REGISTERED (space-joined, registration order).

Output: returns non-zero and empties $_TUI_REGISTERED when nothing is registered.

Example

tui.registered widget list && echo "$_TUI_REGISTERED"

tui.register.style_contract

tui.register.style_contract NAME DESC...

Registers NAME’s style contract (registry kind style): the pseudo-states it can enter and the framework classes it draws with, e.g. "states:hover focus" "classes:.list_sel".

Notes

  • One contract table serves the CSS lint, the XSD generator and tui.class, instead of a state list hard-coded in each.
  • Every existing widget type and chrome element’s contract is registered by lib/tui_registry.sh itself.

tui.addon.dir

tui.addon.dir DIR

Adds a directory whose *.xml files hold addons, so a plugin can ship its own page changes. The app’s own TUI_APP_CONF/addons is always read.

Parameters

  • DIR: a directory path. A directory that does not exist is ignored.

Notes

  • Files are read in name order; priority inside each addon decides the order they are applied in. An empty file is a switched-off addon.
  • Called from a plugin’s on_enable, the folder is removed again when the plugin is disabled (tui.addon.undir).
  • Pages already built are not changed. Call tui.page.refresh to apply the folder to the page on screen.

Example

plugin.stats.on_enable() {
    tui.addon.dir "$(tui.plugin.dir stats)/addons"
    tui.page.refresh
}

See also: tui.addon.undir, tui.page.refresh

tui.addon.undir

tui.addon.undir DIR

Forgets a folder that was registered with tui.addon.dir. Its addons stop applying to pages loaded from now on.

Notes

  • A plugin does not need to call it: the folder a plugin registered in on_enable is removed when the plugin is disabled.
  • The screen does not change by itself; call tui.page.refresh to take the addons off the page that is showing.

See also: tui.addon.dir

tui.cache.forget

tui.cache.forget FILE

Drops everything cached for the page FILE, so its next visit builds it fresh.

Parameters

  • FILE: the page’s absolute path, as the loader keeps it ($_TUI_MARKUP_FILE while that page is the current one).

Notes

  • Once the app has started, cached pages are trusted without checking file times. Use this after something a page depends on changed while the app was running, for example an addon file you just wrote, and then tui.goto the page.

Example

cp new_banner.xml "$TUI_APP_CONF/addons/banner.xml"
tui.cache.forget "$_TUI_MARKUP_FILE"
tui.goto home.xml

See also: tui.addon.dir

Event and result variables

Variable Set by Meaning
TUI_EVENT_TYPE dispatcher key, mouse (wheel and drag included), paste.
TUI_EVENT_KEY dispatcher Normalised key name (ctrl+q, wheel:down).
TUI_EVENT_X, TUI_EVENT_Y mouse Pointer column / row (1-based).
TUI_EVENT_PANE, TUI_EVENT_WIDGET dispatcher Pane / widget under the pointer or focused.
TUI_EVENT_ZONE, TUI_EVENT_ZONE_ID, TUI_EVENT_ZONE_ARG dispatcher Mouse events: kind, id and argument of the topmost hit zone under the pointer (scrollbar + pane + v/h, widget/hitbox + widget id, divider, handle, chevron, title), empty over plain pane area.
TUI_EVENT_BUTTON, TUI_EVENT_RAWBTN mouse Button name / raw SGR button code.
TUI_EVENT_COUNT dispatcher Number of identical scroll events merged into this dispatch.
TUI_EVENT_PASTE paste Bracketed-paste text.
TUI_PANE_ROWS, TUI_PANE_COLS tui.pane_size Pane content size.
TUI_SGR, TUI_FG, TUI_BG, TUI_MODS tui.class.sgr, tui.style.sgr Resolved style.
TUI_CLASSES tui.class.names Sorted theme keys.
TUI_SYS_* tui.sys.* System samples.
_TUI_FACTORY_LAST_ID, _TUI_FACTORY_GRID_CELLS tui.factory.* Last generated ids (public by documented exception).

Settings read when tui.sh is sourced: TUI_APP_NAME (config folder and log name, default dabt), TUI_HOME, TUI_LOG_DIR, TUI_CONFIG_FILE, TUI_VALIDATE=0 (skip page validation), TUI_IGNORE_INVALID_XML=1 (start despite validation errors).