Full-screen terminal programs: widgets, layout, focus, keys, mouse and resizing, drawn into a buffer and repainted only where something changed.
import tui
tui builds full-screen terminal programs: file managers, dashboards, installers, editors, anything that takes over the window instead of printing lines. It is retained mode: you build a tree of long-lived widgets once, change their state when something happens, and the Screen turns key presses, clicks and resizes into events, and widget drawings into frames. It repaints only the cells that changed, so a large screen stays fast over a slow connection. It sits on top of term and uses os.signal to learn about window resizes.
The library started as basalam by Parsa and is now part of the standard library.
The pieces:
•
Screen owns the terminal, the widget tree, the focus and the event loop. NewTerminalScreen sizes it to the terminal; NewScreen gives a fixed size and never touches the terminal, which is how you test.
•
Widgets are structs that embed BaseWidget and override what they need: render to draw, HandleEvent to react, focusable to take keys. Ready-made ones: Text, Input, Button, Checkbox, List, Progress, Separator, Table, TableView, Panel and Modal.
•
Layout containers (Row, Column, Grid, Stack) give their children positions, so you never compute coordinates by hand.
•
Events go first to the focused widget and bubble up to its parents until one consumes them; whatever nobody consumes reaches the optional Keymap and then your loop.
A complete program
A widget, a screen, and the event loop. start switches the terminal to raw mode and the alternate screen; the defer screen.close() right after it puts the terminal back on every exit path, so a crash never leaves the user's shell broken. next_event waits for the next key, click, tick or resize; dispatch hands it to the widgets; present draws what changed. A key the widgets did not consume is yours: here q quits. This program needs a real terminal, so the page only compiles it.
tui-guide-hello.salam
import term
import tui
structHello:
pub use tui.BaseWidget
pub presses: int = 0pubfuncRender(buf: tui.Buffer, bounds: tui.Rect):
buf.PutStr(
bounds.x + 2, bounds.y + 1, "Hello from tui!", tui.Style { bold = true, fg = tui.Cyan }
)
buf.PutStr(
bounds.x + 2, bounds.y + 3, "Enter pressed " + this.presses + " times", tui.StyleDefault
)
buf.PutStr(bounds.x + 2, bounds.Bottom() - 1, "q quits", tui.Style { dim = true })
endpubfuncHandleEvent(event: tui.Event): bool:
if event.IsKey(term.KeyEnter):
this.presses++
rettrueendretfalseendendfuncmain:
ifnot term.IsTerminal():
printerrln"run me in a terminal"ret1endmut screen := tui.NewTerminalScreen(Hello {})
screen.Start()
defer screen.Close()
screen.Present()
mut ev := tui.Event {}
until screen.NextEvent(ev):
consumed := screen.Dispatch(ev)
ifnot consumed and (ev.IsChar("q") or ev.IsCtrl("c")):
screen.Stop()
end
screen.Present()
endret0end
See a frame without a terminal
A screen made with NewScreen never touches the terminal. You can still send it events with dispatch (or post and next_event), draw with draw, and read every row back with buffer.row_text. That is how the examples on this page produce their output, and how you write tests for your own screens.
╭─ hello ────────────────────╮
│ Hello from tui! │
│ Enter pressed 0 times │
╰────────────────────────────╯
╭─ hello ────────────────────╮
│ Hello from tui! │
│ Enter pressed 2 times │
╰────────────────────────────╯
Lay out a screen
Hand widgets to a container and the container places them. A Column stacks its children; set_height with a LayoutSize chooses each share: Fixed cells, a Fill weight of what is left, or Pref for the widget's own preferred size. Make the container the root of the screen, and add each child to the screen too: the container decides where, the screen decides what is drawn and focused. On a resize the screen gives the root the new size and the layout runs again.
tui-guide-layout.salam
import tui
funcfixed(n: int): tui.LayoutSize:
ret tui.LayoutSize { kind = tui.SizeKind.Fixed, cells = n }
endfuncmain:
title := tui.NewText("Downloads") as dyn tui.Widget
rule := tui.NewSeparator() as dyn tui.Widget
mut bar := tui.NewProgress()
bar.SetProgress(40)
progress := bar as dyn tui.Widget
mut body := tui.NewText(
"salam-0.6.3.tar.gz is 40% done. The rest of this line wraps inside the column."
)
body.SetWrap(tui.WrapMode.Word)
text := body as dyn tui.Widget
mut col := tui.NewColumn()
col.SetPadding(tui.UniformInsets(1))
i := col.Add(title)
j := col.Add(rule)
k := col.Add(progress)
_ := col.Add(text)
col.SetHeight(i, fixed(1))
col.SetHeight(j, fixed(1))
col.SetHeight(k, fixed(1))
mut s := tui.NewScreen(col as dyn tui.Widget, 32, 8)
defer s.Close()
_ := s.Add(tui.RootId, title)
_ := s.Add(tui.RootId, rule)
_ := s.Add(tui.RootId, progress)
_ := s.Add(tui.RootId, text)
s.Draw()
repeat s.buffer.height in y:
println"|" + s.buffer.RowText(y) + "|"endend
Output
| |
| Downloads |
| ────────────────────────────── |
| ##########--------------- 40% |
| salam-0.6.3.tar.gz is 40% |
| done. The rest of this line |
| wraps inside the column. |
| |
A form: focus, typing and callbacks
Focusable widgets take turns receiving keys. The first focusable widget added gets the focus; with NewDefaultKeymap installed, Tab and the arrow keys move it. Values come back through callbacks: on_submit for an Input when Enter is pressed, on_toggle for a Checkbox, on_click for a Button. Callbacks are lambdas and cannot capture local variables, so keep the state they change in globals or in your own widget.
tui-guide-form.salam
import term
import tui
mut name := ""mut subscribed := falsemut saved := 0funcrect(x: int, y: int, w: int): tui.Rect:
ret tui.Rect {
x = x,
y = y,
width = w,
height = 1
}
endfunckey(seq: str): tui.Event:
ret tui.Event { kind = tui.KeyEvent, key = term.Decode(seq) }
endfunctyping(s &: tui.Screen, text: str):
repeat text.Len() in i:
_ := s.Dispatch(key(text.Substr(i, 1)))
endendfuncmain:
mut s := tui.NewScreen(tui.BaseWidget {}, 30, 4)
defer s.Close()
s.SetKeymap(tui.NewDefaultKeymap())
label := s.Add(tui.RootId, tui.NewText("Name:") as dyn tui.Widget)
s.Widget(label).SetBounds(rect(1, 0, 6))
mut entry := tui.NewInput()
entry.SetPlaceholder("your name")
entry.on_submit = (value: str):
name = value
rettrueend
field := s.Add(tui.RootId, entry as dyn tui.Widget)
s.Widget(field).SetBounds(rect(7, 0, 20))
mut box := tui.NewCheckbox("Send me news", false)
box.on_toggle = (enabled: bool): subscribed = enabled end
news := s.Add(tui.RootId, box as dyn tui.Widget)
s.Widget(news).SetBounds(rect(1, 1, 20))
mut button := tui.NewButton("Save")
button.on_click = (): saved++ end
save := s.Add(tui.RootId, button as dyn tui.Widget)
s.Widget(save).SetBounds(rect(1, 2, 10))
println"focused first:", s.FocusedId() == field
typing(s, "Sara")
_ := s.Dispatch(key("\r"))
_ := s.Dispatch(key("\t"))
_ := s.Dispatch(key(" "))
_ := s.Dispatch(key("\t"))
_ := s.Dispatch(key("\r"))
println"name:", name, "news:", subscribed, "saved:", saved
s.Draw()
repeat s.buffer.height in y:
println"|" + s.buffer.RowText(y) + "|"endend
Output
focused first: true
name: Sara news: true saved: 1
| Name: Sara |
| [x] Send me news |
| [ Save ] |
| |
Lists and tables
List shows one selectable item per row and moves with j and k (the arrow keys stay free for focus moves); Enter calls on_select. TableView is a scrolling table with a selected row; Up and Down move it and Enter calls activate with the data row. Columns take a LayoutSize width, an alignment and what to do with text that does not fit.
Always defer screen.close() on the line after start().
•
A child given to a container or a Panel must also be added to the screen, or it is placed but never drawn.
•
A dyn Widget cannot be turned back into its struct, so read values through callbacks or keep them in your own state.
•
Draw only inside render; change state in HandleEvent or in your loop, then the next present shows it. After changing state the widgets cannot see, set screen.dirty = true.
•
Glyphs fall back to ASCII on terminals without UTF-8; set SALAM_TUI_GLYPHS to ascii or unicode to choose. Colors follow NO_COLOR, COLORTERM and TERM.
•
On Windows resizes are noticed by polling the size about every 20 milliseconds instead of by a signal.
enumModalSize:
Percent(w: int, h: int)
Fixed(w: int, h: int)
end
How big the dialog is inside the Modal's bounds.
Name
Type
Description
Percent
(w: int, h: int)
A share of the bounds, in percent (0-100) on each axis. The product is floored, then clamped to at least 20 by 5 and at most the bounds. When the bounds are smaller than 20 by 5 the dialog is the bounds.
Fixed
(w: int, h: int)
Exactly w by h cells, clamped to the bounds and nothing more: no 20 by 5 floor applies to an explicit size.
An overlay dialog: a Single-line ring with a title, centred in the Modal's bounds over a DIM scrim. The child is inset one cell inside the ring. A hidden Modal paints nothing, takes no focus and hits nothing. Build it with NewModal. Its state is shared by every copy, so the methods below work before and after Screen.add.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
border_style
Style
The ring's colour. Only its foreground is used; attributes are ignored, as for Panel.
takes_focus
bool = true
When true the Modal is a focus stop while open. Its one focus stop keeps Tab inside its layer.
on_close
func()
Called after Esc closes the Modal. close does not call it.
state
Vector<_ModalState>
The shared state holder, one element. NewModal builds it; every copy shares it. Read and write the Modal through its methods.
The example for this item is shown with the ones above: tui-panels.salam
Shows the Modal. State only: it does not raise the Modal or move focus. The app does both with Screen.push_focus, then raise_subtree. Works on the local value or on the copy Screen.add stored.
The example for this item is shown with the ones above: tui-panels.salam
Hides the Modal. State only: it does not call on_close, unraise or restore focus. The app does those with unraise_subtree, then pop_focus. Works on the local value or on the copy Screen.add stored.
The example for this item is shown with the ones above: tui-panels.salam
Stores the Modal's rect in the shared state, then places the child in the dialog rect inset by one cell for the ring. Works before or after Screen.add.
The example for this item is shown with the ones above: tui-panels.salam
True only while open. A hidden Modal also hides its child from focus order, painting, and hit testing, because the screen checks every widget on the path to the root.
The example for this item is shown with the ones above: tui-panels.salam
Offers the event to the child first and returns true if it consumed it. Then Esc closes the Modal when closable, calls on_close and returns true. Then a mouse event inside the bounds but outside the dialog returns true, so it never reaches a widget below. Anything else returns false. A hidden Modal returns false for everything.
The example for this item is shown with the ones above: tui-panels.salam
Paints nothing while hidden. Otherwise dims every cell of bounds outside the dialog rect, then draws the ring around the dialog rect when it is at least 2 by 2. The child paints itself.
The example for this item is shown with the ones above: tui-panels.salam
The kind of border a container draws: none, or a one-cell ring drawn with light lines, double lines, or light lines and arc corners. A value only: drawing the ring (its code points, corners and titles) is CUR-220. It is a sibling of Style, never a field of it, so a border is a per-widget choice and is not inherited or merged.
Name
Type
Description
None
No border; the content area is the full area.
Single
A one-cell ring of light lines with square corners.
How a cell is drawn: a foreground and a background color and five attributes. Colors are Color, not Option<Color> (Default already means "no color chosen") and a false attribute is one that is off. Reverse is stored rather than composed at emission so StyleEq sees it and a reverse-only change reaches the buffer diff. The set stays closed at these seven: no strikethrough, blink or hidden.
Name
Type
Description
fg
Color
Glyph foreground; Color.Default leaves the terminal's own foreground.
bg
Color
Cell background; Color.Default leaves the terminal's own background.
bold
bool = false
Bold weight only; never brightens the foreground slot.
dim
bool = false
Reduced intensity.
italic
bool = false
Slanted glyphs.
underline
bool = false
A single underline.
reverse
bool = false
Swaps the foreground and background the terminal draws with.
The example for this item is shown with the ones above: tui-style.salam
A single-line text input: value, caret, optional placeholder, and styles for the value, the cursor cell, and the placeholder. It is focusable, so keyboard events reach it through the screen's focus dispatch. Set the value with the field or set_value, read it with value, and set the placeholder with the field or set_placeholder.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
placeholder
str = ""
Text shown (dim) while the value is empty. "" means no placeholder.
style
Style
The base style of the value and the blank background. StyleDefault draws with the terminal's defaults.
cursor_style
Style
The style merged over style for the cursor cell. Defaults to reverse video.
placeholder_style
Style
The style merged over style for the placeholder. Defaults to a bright-black foreground.
max_length
int = 0
Maximum value length in glyphs (codepoints), not display cells. 0 means unlimited. Typing at the limit is consumed and changes nothing; set_value truncates a longer value; deleting is always allowed.
filter
func(str): bool
Called with the whole candidate value after a proposed insertion (one typed glyph), once the max_length check has passed. Returning false rejects it: the key is consumed and nothing changes. Not called for Backspace, Delete or set_value. The default accepts everything.
masked
bool = false
When true every value glyph is painted as mask_glyph. Display only: value, caret and window are unchanged. The placeholder is never masked.
mask_glyph
str = "*"
The glyph painted for each value glyph while masked. Only its first codepoint is used; "" means "*". Under GlyphPolicy.ASCII a non-ASCII mask glyph paints as "*".
on_submit
func(str): bool
Called synchronously on Enter with the real value, never the mask. Returning true consumes the key; false lets it bubble to the parent. The default returns true. After it returns, the caret and window are clamped to the value, in case it changed the value.
Reacts to a key press. A printable character or space is inserted at the caret; Left, Right, Home and End move it (all consumed, even when it cannot move); backspace drops the codepoint before the caret and delete the one at it (nothing at the start or end); enter calls on_submit and returns its result. Other events and keys are not consumed, so they bubble on.
The example for this item is shown with the ones above: tui-controls.salam
Draws the value into bounds: the box is painted with style, the window of cells that holds the caret is written (the placeholder, dim, when the value is empty), and (while the buffer reports focus) one reverse-video cell marks the caret column. The window start is kept between frames and moves only when the caret leaves it. A degenerate box draws nothing and never panics.
The example for this item is shown with the ones above: tui-controls.salam
One terminal color, as the four kinds the wire format distinguishes. Equality is native: two Colors are equal when their kind and payload are equal, so different kinds are never equal.
Name
Type
Description
Default
The terminal's own default foreground or background (SGR 39 / 49), not an entry in any palette.
Ansi
(n: int)
A 16-color palette index, 0-15: 0-7 the normal colors, 8-15 their bright variants. No validation; the documented range is 0-15.
Indexed
(n: int)
A 256-color palette index, 0-255 (SGR 38;5;n / 48;5;n). An index in 0-15 stays Indexed on the wire, never rewritten to the ANSI form.
Rgb
(r: int, g: int, b: int)
A 24-bit truecolor triple, each channel 0-255 (SGR 38;2;r;g;b).
The example for this item is shown with the ones above: tui-style.salam
A one-row action button drawn as "[ label ]". Enter and Space call on_click while the button has the focus, and a left click inside its bounds calls on_click whether or not it has the focus. A disabled button draws dim, takes no focus, and ignores every event.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
label
str = ""
The text drawn between the brackets. Clipped to the width, never ellipsised.
style
Style
The base style of every cell in the button.
focus_style
Style
The style used instead of style while the button is focused and enabled. StyleDefault, the default, means bold on every cell.
disabled
bool = false
When true the button draws dim, does not take focus or hits, and ignores every event.
on_click
func()
Called when the button is activated. The default does nothing.
The example for this item is shown with the ones above: tui-controls.salam
Reacts to Enter or Space, and to a left press inside the bounds. A disabled button consumes nothing. Each activation calls on_click and returns true; every other event returns false.
The example for this item is shown with the ones above: tui-controls.salam
Draws the button into the first row of bounds: the row is filled with the effective style, "[" goes in the first column and "]" in the last (when the width allows), and the label is centred between them, clipped to fit. The effective style is style; dim and not bold when disabled; a focused, enabled button uses focus_style, or bold when focus_style is StyleDefault. A width of zero or less draws nothing.
The example for this item is shown with the ones above: tui-controls.salam
One column of a Table. width is read as a LayoutSize; min and max are read only when width is Pref. max = -1 means unbounded. When min and max conflict, min wins.
Name
Type
Description
width
LayoutSize
Fixed exact cells, Pref the content width, Fill a star share.
min
int = 0
Lower bound for a Pref column, in cells.
max
int = -1
Upper bound for a Pref column, in cells. -1 means unbounded.
align
Alignment
Default alignment of this column's cells and header.
overflow
CellOverflow
How text wider than the column is shown.
The example for this item is shown with the ones above: tui-table.salam
A non-focusable grid of single-line rows. Add columns and rows, then render it. When header is on, row 0 is the header: it is painted in header_style and each cell takes its column's alignment. rule draws a line of ─ under the header across the table's width. pad_x is the blank space on each side of a cell; a negative value counts as 0.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
columns
Vector<TableColumn>
The column definitions, left to right.
rows
Vector<Vector<str>>
The cell text by row, then column. Row 0 is the header when header is on.
header
bool = false
When true, row 0 is the header.
rule
bool = true
Draws a rule under the header. Only meaningful when header is on.
pad_x
int = 1
Blank cells on each side of every cell's text.
style
Style
Style of the data rows.
header_style
Style
Style of the header row. It replaces style there, rather than merging.
The example for this item is shown with the ones above: tui-table.salam
The table's natural size: the resolved widths with star columns at 0, clamped to max_width when it is positive. The height is the header, the rule and the data rows, so a table with no rows is 0 high. A table with no columns is 0 by 0.
The example for this item is shown with the ones above: tui-table.salam
A focusable, vertically scrollable Table. It embeds Table, so columns, rows, header, rule, styles and every setter are Table's. The header and rule stay pinned; the data rows scroll under them in a window that starts at offset. selected is the cursor row, an index into the data rows, or -1 when there are none. Place a TableView in a Fill slot: PreferredSize is Table's full height, so any other slot shows every row and never scrolls. Up, Down, PageUp, PageDown, Home and End move the cursor and are always consumed; Enter calls activate. When rows outnumber the window, the last column of cells holds a scrollbar.
Name
Type
Description
Table
Table
The embedded Table: columns, rows, header and styles, drawn by the view with scrolling and a selected row.
offset
int = 0
Index of the first visible data row.
selected
int = 0
The selected data row, or -1 when there are no data rows.
activate
func(int): bool
Called with the selected row when Enter is pressed on a non-empty table. Its result is the consumed flag: the default returns false, so Enter bubbles on.
The example for this item is shown with the ones above: tui-table.salam
Up and Down move the cursor by one row, PageUp and PageDown by the window height, Home and End to the first and last row. The window scrolls by the least amount that keeps the cursor visible, and a page key moves the window by a page. All six are consumed, even with no rows. Enter returns activate(selected), and is not consumed when there are no rows. Everything else returns false.
The example for this item is shown with the ones above: tui-table.salam
Draws the pinned header and rule, then data rows offset up to offset + window height, each painted only inside bounds. The selected row is reversed while the buffer is focused and bold while it is not; no row is marked when the selection lies outside the window. The scrollbar uses │ and █, or | and # under the ASCII glyph policy.
The example for this item is shown with the ones above: tui-table.salam
A single-child decorator that draws a border ring around its child. The child is positioned inside the ring: Panel insets it by BorderInset of border on each side and passes that rect to the child's SetBounds. A Panel with border None draws nothing and insets nothing, so it behaves like its child. Add the child with add; it must also be added to the Screen's tree to be painted, like any other child. Panel reports the child's natural size plus BorderInset of border on each side, so the ring it draws is part of that size. It is not focusable unless takes_focus is set.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
border
BorderStyle
The ring drawn around the child. None draws nothing and insets nothing.
border_style
Style
The frame's style. Only its foreground is used, for every ring cell and the title; attributes are ignored.
title
str = ""
Text on the top edge. Empty or whitespace-only means no title.
takes_focus
bool = false
When true the Panel is focusable: it takes focus and passes every event to its child. The child is not focusable and gets no focus of its own. False by default, so a Panel is never a focus stop.
focus_style
Style
The frame's style while the Panel has focus. StyleDefault, the default, means no focus style: the frame keeps border_style. Only the foreground is used, as for border_style.
slot
Vector<LayoutSlot>
The child, held as the one layout slot. Empty until add is called.
The example for this item is shown with the ones above: tui-panels.salam
The child's natural size plus BorderInset of border on each side. Each axis is measured at max_width minus that inset on both sides, floored at 1; a non-positive max_width is forwarded unchanged as unbounded. A child that cannot measure falls back to its PreferredSize. A negative component means no preference on that axis and stays -1. An empty Panel reports no preference.
The example for this item is shown with the ones above: tui-panels.salam
Paints the frame over the Panel's rect. While the Panel has focus and focus_style is set, the frame uses focus_style. The child paints itself: the Screen draws every widget in its tree.
The example for this item is shown with the ones above: tui-panels.salam
One input event. kind says which of the payload fields are meaningful.
Name
Type
Description
kind
int = 0
One of NoEvent, KeyEvent, MouseEvent, ResizeEvent, TickEvent.
key
term.Key
The key for KeyEvent; the raw sequence (in key.raw) for MouseEvent.
mouse
term.MouseEvent
The decoded report for MouseEvent.
width
int = 0
The new terminal width in columns, for ResizeEvent.
height
int = 0
The new terminal height in rows, for ResizeEvent.
bubbled
bool = false
True once the event has moved from the widget it started at to an ancestor. Containers such as Panel and Modal use it so they do not hand the same event to their child a second time.
A widget that draws a string: set once or updated later, aligned left, centre, or right, wrapped to its box (or clipped), in one style. Its preferred size comes from the content. Embed it or construct it with NewText.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
content
str = ""
The text to draw. An explicit "\n" starts a new line (see WrapText).
align
Alignment
Horizontal placement of each line. Defaults to Alignment.Left.
style
Style
How the content is drawn. The background fills the whole box; the foreground and attributes apply to the glyph cells only, interior spaces included, so an underline stays continuous. StyleDefault draws with the terminal's defaults. The buffer emits it at its tier.
wrap
WrapMode
How the content becomes lines at render time. Defaults to WrapMode.Word.
The example for this item is shown with the ones above: tui-text.salam
The size the content wants at max_width, as a rect at (0, 0): width is the longest wrapped line in cells, height the number of wrapped lines. max_width <= 0 means unbounded, so the explicit lines are measured.
The example for this item is shown with the ones above: tui-text.salam
Draws the content into bounds. The box is first filled with the pad style (the widget style's background only) so a background colour reads full-bleed while nothing else reaches the padding. Each line is then placed with the alignment offset and written as one run in the full style, interior spaces included, so an underline never breaks; at most bounds.height lines are drawn. A degenerate box draws nothing and never panics.
The example for this item is shown with the ones above: tui-text.salam
The stroke weight of a border run. Light is the zero value; Heavy and Double describe the other weights of the glyph table. A BorderGlyphs records the weight of its horizontal and vertical runs for Screen's post-paint junction pass.
The glyphs of one border ring: edges, corners, the four T junctions and the cross, plus the weight of the horizontal and vertical runs. Every glyph is one codepoint. DrawBorderGlyphs draws the edges and corners; Screen's post-paint pass selects junction glyphs from painted arms.
Name
Type
Description
h
str = ""
Horizontal run, drawn on the top and bottom edges.
v
str = ""
Vertical run, drawn on the left and right edges.
tl
str = ""
Top-left corner.
tr
str = ""
Top-right corner.
bl
str = ""
Bottom-left corner.
br
str = ""
Bottom-right corner.
t_down
str = ""
T junction with its stem pointing down.
t_up
str = ""
T junction with its stem pointing up.
t_right
str = ""
T junction with its stem pointing right.
t_left
str = ""
T junction with its stem pointing left.
cross
str = ""
Four-way junction.
hw
Weight
Weight of the horizontal run.
vw
Weight
Weight of the vertical run.
The example for this item is shown with the ones above: tui-buffer.salam
A one-row progress bar. It fills left to right from the value, which is a percentage of max (100 by default). Set the value with set_progress and the maximum with set_max. Style the filled cells, the empty cells and the percent tail separately with the fill_style, empty_style and text_style fields.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
fill_style
Style
Style of the filled cells. StyleDefault uses the terminal's defaults.
empty_style
Style
Style of the empty cells.
text_style
Style
Style of the five-cell percent tail.
The example for this item is shown with the ones above: tui-text.salam
Draws one row at bounds.y, from bounds.x across bounds.width cells. The bar takes the width less the tail, when the tail is shown. Nothing is drawn when the width is zero or less. Every cell is written through set, which clips to the buffer.
The example for this item is shown with the ones above: tui-text.salam
A table of key and key-sequence bindings. Build it with NewKeymap, NewDefaultKeymap or NewVimKeymap (or empty with Keymap {}), fill it with bind and its variants, feed events to handle, and release it with free. Never copy a Keymap value.
Name
Type
Description
pending_timeout_ms
int = 0
How long a pending key sequence may wait for its next key, in milliseconds. 0 (the default) never expires a prefix, which is the behavior without a timeout. The timeout is evaluated lazily, on the next KeyEvent only; non-key events never expire a prefix. Set it directly (keymap.pending_timeout_ms = 700); there is no constructor.
pending_since_ms
int = 0
The clock reading, in milliseconds, when the current pending sequence started waiting; it is refreshed on every prefix step and is 0 when nothing is pending. handle maintains it; an application sets pending_timeout_ms instead.
The example for this item is shown with the ones above: tui-events.salam
Handles one event against the bindings. Only KeyEvents reach the trie; every other kind returns false and leaves pending untouched. Returns true when an action ran. Reads resolve the key before any action is invoked; nothing touches the trie after an invocation.
The example for this item is shown with the ones above: tui-events.salam
Releases every node's children map and binding vector, then the node storage itself. The actions and their captured values are the caller's; only the trie is freed. Call once.
The example for this item is shown with the ones above: tui-events.salam
Default implementations of every Widget method. Embed it with pub use tui.BaseWidget and override what you need. On its own it is a widget that paints nothing, is unfocusable, reports itself visible and ignores every event, which also makes it a useful container or placeholder.
Name
Type
Description
rect
Rect
Storage for bounds() and SetBounds(). Embedding widgets can read it directly as this.rect.
The example for this item is shown with the ones above: tui-widget.salam
Cannot measure: returns the negative sentinel (width and height -1), which the layout engine maps to the available length. Override it to report a real size.
The example for this item is shown with the ones above: tui-widget.salam
A single-selection scrollable list of strings. It is focusable, so keyboard events reach it through the screen's focus dispatch: j moves the selection down and k up (clamped, no wrap), and enter calls on_select with the selected index. The selected row is drawn full width in the selection style, and the window scrolls by the minimum needed to keep it visible.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
style
Style
The style of every unselected row. StyleDefault draws with the terminal's defaults.
selected_style
Style
The style of the selected row while focused; it replaces style on that row. Defaults to reverse video.
selected_unfocused_style
Style
The style of the selected row while unfocused; it replaces style on that row. Defaults to a bright-black background.
on_select
func(int)
Called with the selected index when enter is pressed on a non-empty list. The default does nothing.
The example for this item is shown with the ones above: tui-controls.salam
Reacts to a key press. j moves the selection down and k up, each clamped to the ends (no wrap) and each always consumed even when the list is empty. Enter is consumed and, on a non-empty list, calls on_select with the selected index. Other events and keys are not consumed, so they bubble on.
The example for this item is shown with the ones above: tui-controls.salam
Draws the visible window into bounds: each row is filled full width with the base style and then the item that occupies it is written, clipped to the width, with the selected row in the selection style (reverse video focused, a bright-black background unfocused). A degenerate box draws nothing and never panics.
The example for this item is shown with the ones above: tui-controls.salam
A one-line rule that draws one rune repeated along the rect's first row (horizontal) or first column (vertical). Set the direction with set_orientation, the rune with set_ch and its style with set_style.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
orientation
Orientation
Which line is drawn. Horizontal by default.
ch
str = ""
The rune, one cell wide. Empty means the orientation's default rune.
style
Style
The rule's style. Its foreground colours the rune cells. A set background fills the whole rect before the rune is drawn.
The example for this item is shown with the ones above: tui-text.salam
Always measurable. The cross axis is one cell. The main axis takes max_width, the same fill the PreferredSize sentinel asks for. A separator never reports ok = false, so the layout never falls back to a stub.
The example for this item is shown with the ones above: tui-text.salam
Draws the rule inside bounds. Nothing is drawn when the rect has no width or no height. A set background fills the whole rect first. The rune then repeats along row 0 (horizontal) or column 0 (vertical) of the rect, full length. Every write goes through set, which clips to the buffer.
The example for this item is shown with the ones above: tui-text.salam
How a child is placed on the container's cross axis, the axis the container does not split. Stretch (the default) fills the whole axis; the others place a child of natural size inside the free space.
Name
Type
Description
Start
The child starts at the box's leading edge; free space follows it.
Center
The child is centred; when the free space is odd the extra cell goes right (Row) or bottom (Column).
End
The child ends at the box's trailing edge; free space precedes it.
Stretch
The child fills the whole axis (the default); any size is ignored.
The example for this item is shown with the ones above: tui-layout.salam
A weighted share of whatever is left after the Fixed children (R5). On a cross axis, Fill behaves like Pref and the weight is ignored (R8).
Fixed
Exactly cells long. A negative value clamps to 0.
Pref
The child's preferred size. On a main axis a measured Pref is reserved like Fixed; one that cannot measure is Fill weight 1. On a cross axis it is the measured natural size (R8).
The example for this item is shown with the ones above: tui-layout.salam
A child's requested size on one axis. cells is read only when kind is Fixed. weight is read only when a main-axis Fill or Pref joins the share.
Name
Type
Description
kind
SizeKind
How the size is resolved. Defaults to Fill.
cells
int = 0
The requested length, read only when kind is Fixed. Negative values clamp to 0 when used.
weight
int = 1
Share of the main-axis leftover for a Fill. Defaults to 1. A negative value clamps to 0 when used. Fixed ignores it, and so do Grid, Stack, and cross-axis alignment. SplitMain also reads it for a Pref that is still in the vector. Arrange resolves a measured Pref to Fixed first, and a Pref that cannot measure to Fill weight 1, so this value is not that slot's weight.
The example for this item is shown with the ones above: tui-layout.salam
Four side lengths in cells, written top, right, bottom, left. Used for both a container's padding and a child's margin. Negatives clamp to 0 at use (InsetRect); NewInsets and UniformInsets clamp on construction.
Name
Type
Description
top
int = 0
Cells added above the content (padding) or reserved above the child (margin).
right
int = 0
Cells added to the right of the content or reserved right of the child.
bottom
int = 0
Cells added below the content or reserved below the child.
left
int = 0
Cells added to the left of the content or reserved left of the child.
The example for this item is shown with the ones above: tui-layout.salam
One child's place in a container's ordered slot list. A slot is owned by the parent; a widget never sees it. margin insets the slot before the child is placed, width and height are the requested sizes on each axis, and align_x / align_y position a child that does not stretch. row, col, row_span and col_span are read by Grid only.
Name
Type
Description
child
dyn Widget
The child widget. It must be registered in the Screen's tree as well, or the Screen never paints it.
margin
Insets
Space reserved inside the slot, before alignment (R4). Zero by default.
width
LayoutSize
The requested size on the x axis. Fill by default.
height
LayoutSize
The requested size on the y axis. Fill by default.
align_x
CrossAlign
Cross-axis alignment on x. Stretch by default.
align_y
CrossAlign
Cross-axis alignment on y. Stretch by default.
row
int = 0
The Grid row this child occupies. 0 by default.
col
int = 0
The Grid column this child occupies. 0 by default.
row_span
int = 1
How many Grid rows this child covers from row. 1 by default. A non-positive value means 1, and Grid clamps it to the rows remaining.
col_span
int = 1
How many Grid columns this child covers from col. 1 by default. A non-positive value means 1, and Grid clamps it to the columns remaining.
The example for this item is shown with the ones above: tui-layout.salam
A container that lays its children left to right along the x axis. Slots are packed from the content start; set_gap inserts that many cells between them. A measured main-axis Pref is reserved like Fixed. Fill then shares the content width left after that reservation and the gap budget (R5). A child fills the content height unless its align_y places it otherwise. Set padding with set_padding; a child's margin, size and alignment with the slot methods. Children are positioned, not painted, so add them to the Screen's tree too.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
pad
Insets
The inset between the container's bounds and its content box (R3).
gap
int = 0
Cells between adjacent slots on the main axis (R5). Zero by default. A negative value clamps to 0.
items
Vector<LayoutSlot>
The children in placement order, one slot each.
The example for this item is shown with the ones above: tui-layout.salam
Natural extent on axis at max_width, without moving children. Main axis is padding, plus each Fixed size or measured Fill or Pref, plus the gap budget. Cross axis is padding plus the largest measured child. A child that cannot measure makes ok false.
The example for this item is shown with the ones above: tui-layout.salam
A container that lays its children top to bottom along the y axis. The mirror of Row: a measured main-axis Pref is reserved like Fixed, then Fill shares the content height left after that reservation and the gap budget (R5). A child fills the content width unless its align_x places it otherwise. See Row for the slot, padding and gap methods.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
pad
Insets
The inset between the container's bounds and its content box (R3).
gap
int = 0
Cells between adjacent slots on the main axis (R5). Zero by default. A negative value clamps to 0.
items
Vector<LayoutSlot>
The children in placement order, one slot each.
The example for this item is shown with the ones above: tui-layout.salam
A container that divides its content box into a fixed rows x cols grid (R9) and places each child by its explicit (row, col) (R10). Columns and rows share the space equally, the remainder to the earliest; an out-of-range or negative cell is a 0x0 slot at the content origin, and the child is still visited. set_span extends a cell by whole tracks (R15). Two children in one cell share it and overlap.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
pad
Insets
The inset between the container's bounds and its content box (R3).
items
Vector<LayoutSlot>
The children in placement order, one slot each.
rows
int = 0
The number of grid rows. Set by NewGrid.
cols
int = 0
The number of grid columns. Set by NewGrid.
The example for this item is shown with the ones above: tui-layout.salam
Stores the container's own rect (normalised), measures, then lays out and moves every child in slot order (R1). Overrides the BaseWidget default. Grid cannot measure; measure stays the BaseWidget default.
The example for this item is shown with the ones above: tui-layout.salam
A container that gives every child the content box minus its own margin (R11), so children overlap exactly. Size and alignment fields are ignored. The container does not paint or raise; Screen's paint order decides which child draws on top. A zero-margin child is exactly the content box.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
pad
Insets
The inset between the container's bounds and its content box (R3).
items
Vector<LayoutSlot>
The children in placement order, one slot each.
The example for this item is shown with the ones above: tui-layout.salam
Stores the container's own rect (normalised), measures, then lays out and moves every child in slot order (R1). Overrides the BaseWidget default. Stack cannot measure; measure stays the BaseWidget default.
The example for this item is shown with the ones above: tui-layout.salam
The terminal session: widget tree, back buffer, focus, and the event loop. Create it with NewScreen.
Name
Type
Description
events
chan.Chan<Event>
The channel the input thread sends events on and next_event reads.
root
dyn Widget
The root widget (ID 0). It always covers the whole screen.
focused
dyn Widget
The widget that currently receives events first.
buffer
Buffer
The back buffer widgets draw into.
glyphs
GlyphPolicy
The glyph policy seeded into every frame's buffer copy. Unicode by default; start() replaces it with DetectGlyphPolicy() unless the app called set_glyphs.
running
bool = false
True from start() (or the first run) until stop().
tree
Tree
The widget registry. Prefer add() and widget() to editing it.
tick_ms
int = 0
Interval of TickEvents in milliseconds; 0 (the default) sends none. Set it before start().
mouse
bool = false
When true, start() enables click reporting: presses and releases arrive as MouseEvents. Set it before start().
mouse_motion
bool = false
When true, start() enables all-motion reporting and every pointer movement, press, and release arrives as a MouseEvent. Includes clicks, so it does not need mouse, and reports are frequent. Set it before start().
keymap
Keymap
The opt-in key bindings, consulted as a dispatch fallback for KeyEvents no widget consumed. Empty by default, so an app that never touches it behaves exactly as before. Bind through this field to extend it in place, or install a whole map with set_keymap. Never assign a Keymap directly: it would leak the current map's buffers.
dirty
bool = true
True when the next present() must repaint the whole frame: a resize, a tick, an added widget, raise/unraise, a keymap-consumed key, or invalidate of an unknown widget. A precise change is a region.
focus_stack
Vector<int>
Widget IDs; the top (last) entry is the focused widget, and an empty stack means nothing is focused. Change it through focus, push_focus, pop_focus, and the navigation methods, which keep focused in sync and queue the old and new bounds.
tui-screen.salam
import term
import tui
funcat(x: int, y: int): tui.Rect:
ret tui.Rect {
x = x,
y = y,
width = 8,
height = 1
}
endfunckey(code: int): tui.Event:
ret tui.Event { kind = tui.KeyEvent, key = term.Key { code = code } }
endfuncmain:
mut s := tui.NewScreen(tui.BaseWidget {}, 20, 3)
defer s.Close()
a := s.Add(tui.RootId, tui.NewButton("A") as dyn tui.Widget)
b := s.Add(tui.RootId, tui.NewButton("B") as dyn tui.Widget)
c := s.Add(tui.RootId, tui.NewButton("C") as dyn tui.Widget)
s.Widget(a).SetBounds(at(0, 0))
s.Widget(b).SetBounds(at(10, 0))
s.Widget(c).SetBounds(at(0, 2))
println"nothing focused yet:", s.FocusedId() == tui.NoWidget
_ := s.Focus(a)
println"focused a:", s.FocusedId() == a, "can focus b:", s.CanFocus(b)
_ := s.FocusRight()
println"right:", s.FocusedId() == b
_ := s.FocusLeft()
_ := s.FocusDown()
println"down:", s.FocusedId() == c
_ := s.FocusUp()
_ := s.FocusNext()
_ := s.FocusPrev()
println"after next and prev:", s.FocusedId() == a
_ := s.PushFocus(c)
_ := s.PopFocus()
println"pop goes back:", s.FocusedId() == a, "stack:", s.focus_stack.Len()
println"hit at 11,0:",
s.HitTest(11, 0) == b,
"nothing at 19,2:",
s.HitTest(19, 2) == tui.RootId
mut layer := Vector {} asVector<int>
layer.Push(c)
s.Raise(layer)
println"raised takes focus:", s.FocusedId() == c
s.Unraise(layer)
s.RaiseSubtree(b)
s.UnraiseSubtree(b)
s.SetKeymap(tui.NewDefaultKeymap())
println"posted:", s.Post(key(term.KeyTab))
mut ev := tui.Event {}
if s.NextEvent(ev):
println"consumed:", s.Dispatch(ev)
end
s.Invalidate(a)
s.InvalidateSubtree(tui.RootId)
s.Resize(22, 3)
s.FitRoot()
s.Draw()
s.Present()
println"|" + s.buffer.RowText(0) + "|"println"|" + s.buffer.RowText(2) + "|"println"widgets:",
s.tree.Count(),
"dirty:",
s.dirty,
"focused bounds width:",
s.focused.Bounds().width
println"root covers",
s.root.Bounds().width,
"x",
s.root.Bounds().height,
"glyphs unicode:",
s.glyphs == tui.GlyphPolicy.Unicode
_ := s.events
_ := s.keymap
s.Stop()
end
Output
nothing focused yet: true
focused a: true can focus b: true
right: true
down: true
after next and prev: true
pop goes back: true stack: 1
hit at 11,0: true nothing at 19,2: true
raised takes focus: true
posted: true
consumed: true
|[ A ] [ B ] |
|[ C ] |
widgets: 4 dirty: false focused bounds width: 8
root covers 22 x 3 glyphs unicode: true
Stops the loop, restores the terminal exactly as start() found it, waits for the input and winch threads, and frees the screen's storage. Safe to call more than once; meant for defer.
The example for this item is shown with the ones above: tui-screen.salam
Which glyph repertoire structural glyphs (borders) may use. Unicode is the zero value and draws box-drawing glyphs; ASCII restricts them to codepoints up to 0x7F for terminals without box drawing.
Name
Type
Description
Unicode
Box-drawing glyphs.
ASCII
Plain ASCII glyphs only.
The example for this item is shown with the ones above: tui-buffer.salam
A one-cell-wide glyph, or "" for the continuation of the wide glyph in the cell to its left. A blank cell holds " ". put_str writes wide glyphs; set blanks any ch that is not one cell wide.
style
Style
The resolved style this cell is drawn with. StyleDefault asks for the terminal's default style. The buffer, not the widget, turns it into bytes.
The example for this item is shown with the ones above: tui-buffer.salam
A grid of cells that widgets draw into. Writes outside clip (or outside the grid) are silently ignored, so drawing is infallible.
Name
Type
Description
width
int = 0
Number of columns.
height
int = 0
Number of rows.
cells
Vector<Cell>
Row-major cell storage: the cell at (x, y) is cells[y * width + x]. Prefer get and set, which bounds-check and clip. Write through set / fill / put_str / clear. Direct writes to the backing vector are outside the contract and are not tracked.
front
Vector<Cell>
The front grid: what the terminal currently shows. Same length and layout as cells. Widgets never write it; only commit() advances it.
clip
Rect
Writes outside this rect are dropped. NewBuffer sets it to the whole grid; the screen narrows it to each widget's bounds while that widget renders.
focused
bool = false
Render context: true while the screen renders the focused widget, so the widget can draw a focus indicator. Always false outside a screen-driven render.
tier
ColorTier
Render context: the colour capability of the terminal this buffer is drawn for. The buffer lowers every cell's Style to this tier when it emits a frame; widgets and DrawBorder only store styles. Screen.start() sets it to DetectTier() once; a buffer built by hand keeps TrueColor, so headless renders stay true colour whatever the environment says. resize() preserves it.
glyphs
GlyphPolicy
Render context: the glyph policy structural glyphs follow. DrawBorder reads it. Screen seeds it on every frame copy; a buffer built by hand keeps Unicode. resize() preserves it.
force_full
bool = true
True when the next diff() must serialize the whole frame instead of only the changed cells. NewBuffer and resize set it; commit() clears it once the front grid has caught up with the back grid.
The example for this item is shown with the ones above: tui-buffer.salam
Writes one cell. Does nothing when (x, y) is outside the grid or outside clip. A non-empty ch that is not one cell wide becomes blank; "" is accepted only after a wide glyph.
The example for this item is shown with the ones above: tui-buffer.salam
Copies every cell when force_full is set or clear() touched the whole grid, and only marked cells otherwise, then clears the marks and force_full, so a later diff() reports only subsequent changes.
The example for this item is shown with the ones above: tui-buffer.salam
A one-row boolean toggle drawn as "[x] label" when checked and "[ ] label" when not. It is focusable, so keyboard events reach it through the screen's focus dispatch: Space toggles it and is consumed, and every other key bubbles on. A left press inside its bounds toggles it whether or not it has focus. Read the state with checked, and change it with set_checked or by the user. Set disabled to stop it from taking input.
Name
Type
Description
BaseWidget
BaseWidget
The embedded BaseWidget: bounds and the default answers for every Widget method this type does not override.
label
str = ""
Text drawn after the mark. "" draws the mark alone.
box_style
Style
Style of the three mark cells, the "[", the state glyph and the "]".
label_style
Style
Style of the spacer, the label, and the trailing fill of the row.
disabled
bool = false
When true the checkbox is not focusable, ignores every event and does not take hits, and draws its row dim.
on_toggle
func(bool)
Called with the new checked value after every toggle. The default does nothing.
The example for this item is shown with the ones above: tui-controls.salam
Reacts to Space and to a left press inside bounds. Either one flips the checked state, calls on_toggle with the new value, and returns true. Every other event returns false, and a disabled checkbox returns false for all of them.
The example for this item is shown with the ones above: tui-controls.salam
Draws one row at bounds.y: the spacer and label cells and the trailing fill in label_style, then the three mark cells in box_style. Focus (while enabled) overlays bold and disabled overlays dim and drops bold onto both styles. Each cell is clipped to the width, so a narrow row drops the label first and then the mark cells from the right. A degenerate box draws nothing.
The example for this item is shown with the ones above: tui-controls.salam
The style of a cell that asks for nothing: both colors the terminal's default and all five attributes off. It is the zero value of Style and the identity of StyleMerge.
The example for this item is shown with the ones above: tui-style.salam
How often, at most, the input thread wakes when no key arrives, in milliseconds. Bounds the latency of stop() and, on Windows, of resize detection (on POSIX a resize arrives as SIGWINCH instead).
The cells a border of this kind uses on each side: 0 for None, 1 for every other kind. A container shrinks its content area by this to get the area its children draw into.
The example for this item is shown with the ones above: tui-style.salam
The style a child ends up with under a parent, by sentinel patch: a child's color is used unless it is Color.Default (then the parent's color is inherited), and each attribute is the OR of the two. So StyleMerge(StyleDefault, s) and StyleMerge(s, StyleDefault) both equal s, and the result of merging into StyleDefault is a fully resolved style. Pure: it returns a new value and never mutates its inputs. a child can add an attribute or override a color but cannot remove an inherited attribute (child false is indistinguishable from unset) or force the terminal-default color under a colored parent (child Default means inherit). Ceiling: no subtraction. Upgrade path if removal is ever needed: a separate StylePatch of Option fields that resolves into a Style, leaving Style, cells and equality unchanged.
The example for this item is shown with the ones above: tui-style.salam
True when two styles are equal field by field, over the seven stored fields: colors by kind and payload, attributes directly. It needs no tier. The contract with emission: equal styles emit identical bytes for every tier (sound), but unequal styles can emit the same bytes at tier Off, where every color is dropped (not complete). It therefore errs toward "different", so a cell is never wrongly skipped; a tier change invalidates every cell, since equality ignores the tier.
The example for this item is shown with the ones above: tui-style.salam
The SGR sequence that takes a terminal from its default state to style at tier: attributes first in the fixed order bold, dim, italic, underline, reverse, then the foreground, then the background. Attributes ignore the tier (NO_COLOR asks for no color, not for no bold); each color is lowered to the tier first, and one that is Default after lowering is skipped. Returns "" when nothing is set, and never emits a reset: every sequence is built from term's builders and color.salam's encoders, none is written by hand.
The example for this item is shown with the ones above: tui-style.salam
The mirror of StyleSgr: the SGR sequence that takes a terminal from style back to its default state at tier, in the fixed order a single 22 if bold or dim is set (22 clears both together), then 23 if italic, then 24 if underline, then 27 if reverse, then 39 if the foreground is non-default after lowering, then 49 if the background is. Returns "" when nothing is set and never emits a reset; the codes are built with term.Sgr.
The example for this item is shown with the ones above: tui-style.salam
Diagnostics: how many non-empty SGR sequences StyleSgr and StyleSgrOff have emitted this process. Nothing caches them: the buffer appends one per style change it writes, so a frame adds one per on or off sequence emitted. Read-only; not configuration.
The example for this item is shown with the ones above: tui-style.salam
The foreground SGR sequence for a color, at full fidelity: the exact escape the color's kind encodes to, with no tier downgrade. Default is SGR 39; Ansi 0-7 is 30+n and Ansi 8-15 is 90+(n-8); Indexed is 38;5;n; Rgb is 38;2;r;g;b. Built from term's sequence builders: no escape is written by hand.
The example for this item is shown with the ones above: tui-style.salam
The background SGR sequence for a color, at full fidelity: the exact escape the color's kind encodes to, with no tier downgrade. Default is SGR 49; Ansi 0-7 is 40+n and Ansi 8-15 is 100+(n-8); Indexed is 48;5;n; Rgb is 48;2;r;g;b. Built from term's sequence builders: no escape is written by hand.
The example for this item is shown with the ones above: tui-style.salam
The color tier the environment advertises, from NO_COLOR, TERM, COLORTERM and CLICOLOR_FORCE only: no tty probe and no caching, so it is pure and headless-testable. First match wins: NO_COLOR set and non-empty -> Off; TERM == "dumb" unless CLICOLOR_FORCE is set to a non-empty value other than "0" -> Off; COLORTERM == "truecolor" or "24bit" -> TrueColor; TERM containing "256color" or any other non-empty COLORTERM -> Indexed256; otherwise Ansi16. NO_COLOR beats CLICOLOR_FORCE.
The example for this item is shown with the ones above: tui-style.salam
The same color at a lower tier: the emission-time downgrade. Off makes every color Default; TrueColor is unchanged; Indexed256 lowers only Rgb to the nearest 256 index; Ansi16 lowers Rgb and Indexed 16-255 to the nearest of the 16 ANSI colors (Rgb directly, never through Indexed) and leaves Default and Ansi alone. Pure: it returns a new value and never mutates its input.
The example for this item is shown with the ones above: tui-style.salam
The foreground SGR sequence for a color after lowering it to tier: FgSeq of Lower(c, tier), so the emitted escape matches the tier and no sequence is written by hand.
The example for this item is shown with the ones above: tui-style.salam
The background SGR sequence for a color after lowering it to tier: BgSeq of Lower(c, tier), so the emitted escape matches the tier and no sequence is written by hand.
The example for this item is shown with the ones above: tui-style.salam
Splits text into display lines of at most width cells, top to bottom. An explicit "\n" starts a new paragraph, each wrapped on its own; the space at a break is consumed. A word longer than width is cut on the character grid. A two-cell glyph can exceed a width of one. width <= 0 means unbounded, so each paragraph is returned unwrapped.
The example for this item is shown with the ones above: tui-text.salam
The preferred size of text wrapped at max_width, as a rect at (0, 0): width is the longest wrapped line in cells, height the number of wrapped lines. max_width <= 0 means unbounded, so width is the longest explicit line and height is the explicit line count. Widths count display cells.
The example for this item is shown with the ones above: tui-text.salam
The glyph set for border under policy. BorderStyle.None gives the zero value (no glyphs). Under GlyphPolicy.ASCII every other style gives GlyphsASCII; otherwise Single, Double and Rounded give GlyphsSingle, GlyphsDouble and GlyphsRounded.
The example for this item is shown with the ones above: tui-buffer.salam
Paints a one-cell ring of border around rect into buf, every cell in one foreground color taken from style.fg. Rules: - BorderStyle.None, or a rect with no area, writes nothing. - A one-row rect is a horizontal rule and a one-column rect is a vertical rule; neither has corners or a title. - Otherwise the four corners are drawn, then the horizontal edges, then the vertical edges. Edges run strictly between the corners. - title sits on the top edge starting at rect.x + 2, with one space before and after it. It is trimmed; an empty title draws nothing; it is cut to rect.width - 5 display cells on the right and needs a width of at least 6. - Only foreground color is used. Attributes in style are ignored, and a Color.Default fg writes an empty style (the terminal default). Writes go through Buffer.set, which clips to the grid and the clip region, so a rect partly outside the buffer paints only its inside part.
The example for this item is shown with the ones above: tui-buffer.salam
Paints a one-cell ring of glyphs around rect into buf, with every rule of DrawBorder (degenerate rects, title, one foreground color). Use it for a custom or non-default glyph set. When buf.glyphs is GlyphPolicy.ASCII the set is replaced by GlyphsASCII, so a custom set never emits a non-ASCII glyph under that policy.
The example for this item is shown with the ones above: tui-buffer.salam
Creates an opt-in keymap with the library's default focus bindings: exactly five rows: Tab moves the focus to the next widget, and Up, Down, Left and Right move it in those directions. Nothing installs this map on its own; pass it to set_keymap (or bind through a screen's keymap field) to use it. Shift+Tab is deliberately not bound: Salam decodes the backtab sequence to KeyUnknown.
The example for this item is shown with the ones above: tui-events.salam
Creates an opt-in vim-style preset. It is a superset of NewDefaultKeymap, so Tab and the four arrows keep working, and it adds h, j, k and l for the same four directions; "gg" and "G" move to the top and the bottom of the focused widget's column, by repeated directional moves, so the column is kept; Esc pops the focus stack, but only while a pushed focus remains, and is reported unconsumed at the root so the application still sees it; and "/" runs on_search, the application's own action, whose boolean is the dispatch result. Enter and Space are deliberately not bound: dispatch offers every key to the focused widget first, where Button, Checkbox, List and Modal already act on them, and Widget has no generic activation to bind. A focused Input consumes "/" before the keymap sees it. Install the map with set_keymap, which takes ownership: never copy or free it afterward.
The example for this item is shown with the ones above: tui-events.salam
funcNearest(from: Rect, candidates: Vector<Rect>, dir: int): int
Finds the candidate nearest to from in direction dir (DirUp, DirDown, DirLeft, DirRight) and returns its index in candidates, or -1 when no candidate qualifies. The rules are spelled out in the comments of the function body. O(n): every candidate is looked at once.
The example for this item is shown with the ones above: tui-geometry.salam
Creates a List over items with the selection on the first item (or on nothing when items is empty) and the window at the top, using default styles and a no-op on_select.
The example for this item is shown with the ones above: tui-controls.salam
The cells shared by r and box (R2). When they do not intersect, a 0x0 rect at the nearest point of box to r: the result is never empty in the negative sense, so a rect that leaves this function is either non-empty or exactly 0x0.
The example for this item is shown with the ones above: tui-layout.salam
Insets r by i, then clips the result back inside r (R3, R4). Each side is first clamped to 0, so a negative padding or margin adds nothing. Padding larger than r gives an empty content box anchored inside r; the returned rect is never negative.
The example for this item is shown with the ones above: tui-layout.salam
Splits a main-axis length of length cells between sizes, in order (R5). Fixed takes max(0, cells) and ignores weight. gap is the cells between adjacent slots. A negative gap clamps to 0. The budget is gap * max(0, k - 1), where k is the slot count, including zero-size slots; k <= 1 charges nothing. Fill and Pref share the leftover R = max(0, length - sum of those Fixed sizes - budget). Arrange resolves a measured Pref to Fixed before this call, and a Pref that cannot measure to Fill weight 1. This function does not measure; a Pref still in the vector stays in the weight pool. Each pool entry's weight is max(0, weight). The share is floor(R * weight / sum of weights), then one extra cell goes to each remaining cell, given to the pool entries with the largest (R * weight) mod sum of weights. Ties go to the earliest pool slot. A weight sum of 0 gives every pool entry 0 and leaves R unused, with no division. Fixed overflow, or a budget that uses up the length, makes R 0, so every pool entry is 0 and Fixed is not shrunk. The gap is not part of the returned sizes and is not refunded. The vector has one entry per input. Weight 1 on every pool entry is an equal split, remainder to the earliest entries.
The example for this item is shown with the ones above: tui-layout.salam
Divides a total length into n grid tracks (R9). Assumes total >= 0 (content lengths are never negative; on a negative total the division truncates toward zero and the exact-sum claim below does not hold). Track k is floor(total/n) plus one for each of the earliest total mod n tracks, so the tracks sum to total exactly. A non-positive n gives an empty vector.
The example for this item is shown with the ones above: tui-layout.salam
funcPlaceAxisOffset(avail: int, align: CrossAlign, natural: int): int
The offset of a child from the box start on one axis (R7). Stretch, or a non-positive avail, gives 0; otherwise the natural size is clamped into [0, avail] and the free space is split per align: Start 0, Center floor(free/2) with the odd cell trailing, End free.
The example for this item is shown with the ones above: tui-layout.salam
Creates a screen of width x height cells with root as its root widget (ID 0, sized to the whole screen). Nothing touches the terminal until start(), which resizes the screen to the real terminal.
The example for this item is shown with the ones above: tui-screen.salam
The glyph policy the environment advertises. Pure and uncached; the only environment reader for glyphs, called once by Screen.start. First match wins: SALAM_TUI_GLYPHS "ascii" -> ASCII, "unicode" -> Unicode; TERM == "dumb" -> ASCII; the first non-empty of LC_ALL, LC_CTYPE, LANG decides: not UTF-8 -> ASCII, UTF-8 -> Unicode; otherwise Unicode.
The example for this item is shown with the ones above: tui-buffer.salam