Widgets¶
A widget is a function of ui and whatever it needs to display, returning a View. There is no object to instantiate or keep.
from turbodesk.widgets import button, listbox, table, textbox
view = button(ui, "Save", on_press=save, focus="save-button")
Every widget has an optional focus key. With one it joins the focus ring and only responds when it holds the keyboard; without one it is decoration you can still click.
All arguments after the required ones are keyword-only, so call sites read for themselves and parameter order is not part of the API.
The catalogue¶
Text and input¶
textbox(ui, *, focus, style, cursor_style, initial, width) |
single-line input; returns Textbox(view, value, set) |
editor(ui, *, keymap, style, width, max_height, initial, single_line, caret, highlights, selection_style, group_undo, indent, gutter, marks, history, focus) → .find, .replace_all, .select, .undo |
multi-line editor, with standard, vim or emacs keymaps |
spinner(ui, *, kind, style, interval) |
an animated dot or line spinner |
Controls¶
button(ui, label, on_press, *, focus, style, accent) |
Enter or Space when focused; also clickable |
checkbox(ui, label, checked, on_toggle, *, focus, switch) |
a checkbox, or a toggle with switch=True |
radio_set(ui, options, selected, on_select, *, focus) |
one choice from several; up/down move, rows are clickable |
progress_bar(ui, fraction, *, width, label, style) |
determinate bar |
tabs(ui, items, selected, on_select, *, width, focus) |
a row of tabs; left/right move |
rule(width, *, style, label) |
a horizontal line, with an optional label sitting in it |
Lists and tables¶
listbox(ui, rows, selected, size, on_move, *, on_select, on_delete, on_toggle, focus, empty) |
single-column list of Row(label, style, value); arrows and j/k, fixed height, scrolls itself. on_toggle binds Space |
selection_list(ui, rows, selected, size, on_move, *, checked, on_toggle, focus, empty) |
the same with a check box on every row; checked holds the ticked indices |
table(ui, columns, rows, selected, *, size, on_move, on_select, on_delete, on_sort, focus, empty, show_header) |
the same with Columns; rows are strings or Cell(text, style); on_sort gets a column index when its heading is clicked |
tree.render(node, style) |
Leaf / Branch / Split with box-drawing connectors |
directory_tree(ui, entries, selected, size, on_move, *, on_open, on_toggle, focus, dir_style, empty) |
a browsable directory; entries comes from directory.rows(root, expanded) |
ncdu.browser(ui, root, title, *, separator, on_leaf_select, focus) |
a weighted-tree browser |
directory_tree splits into a pure part and a drawn one. directory.rows(root, expanded, *, show_hidden=False) turns a root and the set of open directories into the lines that should be on screen; the widget draws them through listbox, so selection and scrolling come free. A directory is read only when it is expanded, so the cost follows what is on screen. An unreadable directory closes that branch and leaves the view alone.
from turbodesk.widgets import directory, directory_tree
entries = directory.rows(root, expanded)
view = directory_tree(ui, entries, selected, size, set_selected,
on_open=lambda entry: load(entry.path),
on_toggle=lambda entry: set_expanded(
directory.toggled(expanded, entry.path)))
Enter opens a file and toggles a directory, Space toggles either. The caller owns root and expanded, so both can be saved between runs.
table's columns share the row out by weight, so you say which column deserves the space, whatever the terminal's width:
COLUMNS = [
Column("name", weight=3),
Column("state", width=9), # fixed
Column("size", align="right"),
]
Desktops and menus¶
windows |
overlapping windows as pure geometry: opened, closed, raised, cycled, moved, placed, sized, cornered, zoomed, tiled, cascaded, refitted, at, find |
menu.bar(menus, open_index, width, style, on_open, *, indent) |
a menu bar, every title clickable |
menu.pulldown(items, selected, style, enabled, on_pick, *, on_hint) |
the open menu with its shadow; enabled decides what greys, on_hint reports the row under the pointer |
menu.move / first_item / by_letter / menu_for |
the arithmetic for walking one from the keyboard |
frame(body, *, style, title, active, number, zoomed, footer, grip, on_close, on_zoom, on_scroll, vertical, horizontal) |
window chrome: border, title, close and zoom boxes, a footer, a resize grip, and a scroll bar that replaces the edge when there is more to see |
frame.shadowed(view, dim) |
a shadow that darkens what is under it |
frame.desktop(size, style) |
the hatched backdrop windows sit on |
statusline(items, width, *, style, hint) |
the foot of the screen: Entry(key, label, action) pairs, each clickable, with a right-aligned hint |
shell(*, desktop, menus, opened, set_opened, picked, set_picked, greyed, on_pick, body, status, menu_style, status_style, on_hint, hint) |
the three bands together: menu bar, desktop, status line |
commands.dispatch(table, name, *, close) |
run the command name, if the table has one; True when it did |
turbodesk.windows is not a widget: nothing in it draws. A window is a numbered rectangle with a title. A stack goes in and a new stack comes out, front to back, which is the order zcat wants:
stack = windows.opened(stack, "editor", "hello.py", bounds)
stack = windows.raised(stack, key)
zcat([*(draw(w) for w in stack), backdrop])
Menus are data. An item whose command is missing from the application's table draws grey:
MENUS = (Menu("~F~ile", (Item("~O~pen", "file.open", "F3"), Item("E~x~it", "file.exit"))),)
menu.pulldown(MENUS[0].items, picked, MenuStyle.of(ui.theme), commands.__contains__, run)
examples/windows.py is both of them together, with ui.on_drag for the mouse.
One table with three readers¶
commands.dispatch keeps a menu consistent with what the keys do. The application holds one mapping from command id to function: an id that is absent draws grey, one that is present runs. The menu, the keyboard and the status line all read the same mapping, so a shortcut can never do something its menu item says is unavailable:
table = {"file.open": open_file} # `file.exit` is missing, so it greys
if not commands.dispatch(table, name, close=lambda: set_opened(None)):
... # nothing ran; the key is still up for grabs
close runs first, because picking a command always dismisses the thing it was picked from. The bool it returns is for a key handler that has to say whether it consumed the event; a click has nowhere to report it and ignores it.
The whole screen¶
shell() composes the three bands a Turbo Vision–style application is made of, and owns no state: which menu is open and which row is highlighted live in your hooks and are passed in.
return shell(
desktop=bounds,
menus=MENUS,
opened=opened, set_opened=set_opened,
picked=picked, set_picked=set_picked,
greyed=table.__contains__, # asked about every command id
on_pick=run,
body=lambda: desktop_view,
status=[Entry("F10", "Menu", open_menu)],
menu_style=MenuStyle.of(ui.theme),
status_style=StatusStyle.of(ui.theme),
)
It hangs the open pull-down under its title, clamped so it cannot run off the right edge, and puts a transparent sheet over the desktop beneath it so a click anywhere else closes the menu. That sheet is also what stops a press reaching a draggable region underneath.
Framing and scrolling¶
border(view, *, title, subtitle, line, style, title_style, subtitle_style, padding, hide) |
four line styles; hide="tr" leaves sides open |
scroller(ui, view, size, *, crop_width, focus, stick_to_bottom) |
a window with less-style keys; follows the bottom for logs |
scrollbar(position, height, *, track_style, thumb_style) |
the bar on its own |
vim_status(position, style) |
Top / 50% / Bot, as vim shows it |
scroller and scrollbar take a ScrollPosition(offset, max_offset); border's line is one of LINE_TYPES.
The widgets that return more than a View hand back a small NamedTuple whose first field is view: Textbox(view, value, set), Scroller(view, position, inject, scroll_to, stuck_to_bottom), Pane(view, send, ...) and Editor, which holds enough for an application to build an Edit menu out of:
view, text, cursor, mode, cursor_tag |
what it drew, what it holds, where the caret is, plus the tag ui.set_cursor wants |
set_text, set_caret |
replace the text; jump to an offset (a compiler error, a search hit) |
selection, select(start, end), replace_selection(text) |
Cut, Copy, Paste and Clear are these plus a string you keep |
find(needle, *, backwards, ignore_case, whole_words, regex), replace_all(needle, fresh, *, ignore_case, whole_words, regex) |
see Finding and replacing |
undo, redo, can_undo, can_redo |
the last two are for greying the menu items |
Finding and replacing¶
box.find("needle") # selects the hit; False if there is none
box.find("needle", backwards=True, ignore_case=True)
count = box.replace_all("old", "new")
find selects the match, so the hit is visible on the line. It searches on from the caret and wraps, so calling it again walks the file. The caret leads in the direction of travel: a backwards search that landed the caret at the match end would find the same match for ever.
replace_all returns how many it changed and records one undo step; a search with no match leaves the text and the undo history alone.
Both go through re with the needle escaped, so a needle full of metacharacters is literal and a replacement containing \1 is two characters. That is also why case-insensitive search is exact: lower-casing both sides would return offsets pointing at the wrong characters for any letter whose lower case is a different length.
box.find("count", whole_words=True) # not "account", not "counter"
box.find(r"def \w+\(", regex=True) # re.error if it will not compile
whole_words needs a word boundary at both ends. regex reads the needle as a pattern, and only the needle: the replacement stays literal either way. A pattern that does not compile raises re.error, which lets a Find dialog tell a bad pattern from a missing match.
For search without a widget, search(text, needle, start, *, backwards, wrap, ignore_case, whole_words, regex) and replaced(text, needle, fresh, *, ignore_case, whole_words, regex) are the pure functions underneath, and pattern_for(needle, ...) is what both compile.
Syntax colouring¶
from turbodesk.syntax import SyntaxStyle, highlighter
editor(ui, highlights=highlighter("python", SyntaxStyle.of(ui.theme)), ...)
highlights= is any function from the text to a list of Highlight(start, end, style) in character offsets: matching brackets, search hits, a diff. highlighter returns exactly that function, for a language. language is a Pygments lexer name such as python, rust or sql. An unknown name raises at the first call, where drawing everything plain would hide the typo.
There are four kinds, because that is what a terminal palette tells apart at a glance: comments, literals, keywords, and the names a language defines for you.
Two properties make a per-frame hook affordable, which is why this lives in the library. The lex result is cached on the text as token kinds, so scrolling is free and changing theme repaints without lexing again. Above MAX_HIGHLIGHT characters the colouring switches off, because 20 ms a keystroke is a sticky keyboard and plain text is not. Pass limit= to move that line.
Pygments is not a turbodesk dependency: pip install turbodesk[syntax] adds it. The module says so if it is missing.
The editor's gutter¶
gutter=True numbers the lines. marks puts one character beside a line, keyed by document line from 0:
Both come out of width, so the widget stays the size you asked for and the text wraps a few columns sooner. Passing marks at all reserves the mark column, empty or not. A column that appeared with the first breakpoint would reflow the file under the person setting it, so marks={} is a meaningful argument.
A wrapped line is numbered once, on the row it starts. A press in the gutter puts the caret at the start of that line.
The editor's indentation¶
indent is one level, as a string, so indent="\t" is a file indented with tabs and code downstream need not know which it is:
- Enter copies the current line's leading whitespace onto the new line. It takes only the whitespace before the caret, since what follows moves down anyway.
- Tab inserts a level at the caret; Shift-Tab takes one off the front of the line.
- With a selection, both shift every line the selection touches and leave the block selected, so the key works pressed twice. Blank lines are left alone. A selection ending on a line break stops at the line before: dragging down three lines lands the caret at the start of the fourth, which the user did not mean to shift.
A tab character counts as one level however wide indent is, so outdenting a tab-indented file removes one tab.
Tab only reaches the editor when it is alone in a focus group: the runtime moves focus with it first. That suits an input field on a form. A file being typed into needs Tab, so put a window's editor in a group by itself.
The editor's mouse¶
Pressing puts the caret where you pressed; dragging selects what you cross. Past the end of a short line is that line's end. A drag that wanders off the widget goes on selecting to the nearest end. editor() registers a ui.on_drag target itself, so there is no wiring to do.
That target covers the whole widget, so the registration-order warning applies. An editor nested inside something else draggable loses the mouse to whichever target was registered first. An untagged overlay drawn over the editor does not stop a press from reaching it.
The editor's keymaps¶
standard uses what the operating system already trained everyone on: arrows and Home/End, plus a modifier with an arrow to move by word. Option is that modifier on macOS, Control almost everywhere else, and the editor accepts either. Control-Home and Control-End reach the ends of the document, and the same modifier with Backspace or Delete removes a word.
emacs adds Control-A, E, F, B, N, P, D and K, plus Meta-f, Meta-b and Meta-d. Those letters are absent from standard. A letter under Control is among the most contested keys in a terminal; an editor holding focus would silently eat its host's bindings: Control-B costs examples/frogmouth its bookmarks pane. Modifier-plus-arrow collides with no binding, which is why standard can have it.
Fuzzy matching¶
turbodesk.fuzzy is the matcher behind dialog.pick. It also works without the picker:
fuzzy.match("fb", "src/foo/bar.py") # -> Match(text, score, positions) | None
fuzzy.ranked("fb", names, limit=200) # -> best first
The query's characters have to appear in order; where they appear decides the score. A character starting a word is worth most, a run of adjacent characters next, and depth in a path costs a little. Matching is leftmost-greedy. Scoring the best alignment would take a dynamic program, which nothing has needed yet.
History lists¶
An input can remember what has been typed into it before:
↑ walks back through the list, ↓ walks forward, and ↓ past the newest gives back whatever was being typed before the walk started. Typing over a recalled line ends the walk: an entry you have edited is a new line. The list is oldest first, the way you accumulate one by appending, and you own it. Appending on submit is the application's business, the same as the text. dialog.prompt(history=) and dialog.Field(history=) pass it through.
It is read only with single_line, where those keys are otherwise unbound. In a multi-line editor they move the caret and go on doing so.
caret is where the cursor starts. The default is the end of initial, which is right for an input field the user is about to add to and wrong for a file: Turbo Python passes caret=0, because Turbo Pascal opens a file at 1:1. After that the caret belongs to whoever is typing, with one exception: Editor.set_caret moves it from outside, for going to a line number, jumping to a compiler error, or landing on a search hit.
Pasting. A bracketed paste arrives as one Paste event and the widget puts its text in at the caret, replacing any selection. It is text whatever mode the editor is in: in vim mode the characters would otherwise be commands.
Selections and undo. Shift with any movement key extends a selection, moving without it drops one, and typing over one replaces it. Editor.selection is the selected text and replace_selection swaps it, which covers Cut, Copy, Paste and Clear once the caller keeps a string: the widget has no idea what a clipboard is. select(start, end) puts a selection on a search hit from outside.
Editor.undo and redo walk a stack of whole-text snapshots, with can_undo and can_redo for greying a menu. Pressing Alt-Backspace undoes from inside the widget; Borland used that key and terminals reliably deliver it. group_undo=True, the default, collapses a run of edits of the same kind into one step, so undoing a typed word takes it back whole.
The setters belong to the frame that produced them. Calling select and then replace_selection in the same frame makes the second one act on the buffer as it was before the first, because that is the buffer it closed over. In an app the two arrive on separate events and it never comes up.
vim opens in normal mode with hjkl, i, a, o, dd, x and the rest of the small vocabulary in widgets/editor.py. Editor.mode reports which mode it is in, so the app can ask for a block cursor:
A tag alone does nothing. Until the app hands it to ui.set_cursor, the text is editable and the terminal shows no cursor at all.
Charts¶
bar_chart(bars, ...), line_chart(lines, ...) and scatter_chart(points, ...), taking Bar(label, value, color), Line(points, label, color) and Point(x, y, color, marker). All three are built on the braille Canvas, which addresses four times the resolution of one cell.
Other¶
dialog (modals), tmux.pane (embed another TUI), less_keys (the navigation key table on its own).
Writing your own¶
There is no base class. A widget is a function that returns a View:
from turbodesk.runtime import focus_tag
def field(ui: UI, label: str, value: str, on_change, *, focus=None) -> View:
active = focus is None or ui.focus(focus)
def keys(event: Event) -> bool:
if active and isinstance(event, KeyPress) and isinstance(event.key, str):
on_change(value + event.key)
return True
return False
if active:
ui.on_event(keys, focused=True)
view = hcat([
View.text(f"{label}: ", Style(fg=ui.theme.subtext0)),
View.text(value, Style(underline=active)),
])
return view.tagged(focus_tag(focus)) if focus else view
Follow the two conventions the built-in widgets do:
The caller owns the state. field above takes value and on_change. The app usually already has that value and wants to save it; a widget that hides it makes that impossible.
Return a View, unless the caller needs more than pixels. textbox, scroller, editor and tmux.pane return a small NamedTuple whose first field is view, because callers need the value, the scroll position or the cursor tag as well.
Writing a component is the long version: a radio set built from scratch with tests, the patterns for popups and cursors, and the mistakes that cost an hour.