API & Architecture - ttgui
Developer documentation for the framework in ttgui.hpp. User documentation (build, run, keys) is in README.md; test documentation is in tests/README.md; the original specification is prompt.md.
Build (repo root Makefile): make (demo+tests), make check, make asan, make selftest, make clean.
1. Overview and design rules
ttgui recreates the Transport Tycoon Deluxe / OpenTTD window-and-widget
GUI in a text terminal. Design rules, enforced throughout:
- Zero dependencies. C++20 standard library + POSIX only (
termios,ioctl,poll,pty). No ncurses, no third-party headers anywhere - including the JSON parser and the test framework. - One source of truth. A single
Configobject holds every colour, glyph, size, timing, effect, bell, and keybinding value. Widgets read it through aconst Config* cfgmember; nothing hard-codes style. - OOP + RAII. Widgets own children with
std::unique_ptr; the terminal restores itself via RAII even on signals/exceptions; child processes are owned by theTerminalWidgetthat spawned them. - One event loop.
Application::run()is a singlepoll()loop owning stdin, all PTY masters, timers, and resize. Nothing blocks it - animations are timer steps, never sleeps. - Header-only.
#include "ttgui.hpp"is the whole framework. This trades compile time for zero build system; see §11 for the cost.
2. Architecture
demo.cpp ──registers──▶ AppRegistry ──creates──▶ IApp implementations
│ createWindow()
Config ──▶ Theme ──▶ every Widget (cfg pointer) ▼
WindowManager ◀── Window (caption/boxes)
Terminal (RAII, raw mode) ──▶ InputParser ──▶ Event ──▶ Application
▲ │ dispatch
│ ANSI diff output ▼
Canvas (double buffer) ◀── drawTree ── Widget tree (Desktop, Panels,
Windows, leaf widgets)
TerminalWidget ──▶ VtParser (grid) DragManager, BellService
| Class | Role |
|---|---|
Config |
All style/behaviour values; JSON load/save; search order (§6). |
Theme |
Read-only convenience view over Config (window colours, glyphs, ascii mode). |
Point/Size/Rect/Insets |
Cell-unit geometry. Rect provides intersect, unionRect, clampInside, inset. |
Color/CellStyle/Cell |
Colour (named, 256-index, or RGB), cell attributes, one terminal cell. |
Canvas (alias ScreenBuffer) |
Double-buffered cell grid; clipping stack; drawText/drawBox/drawBevel/drawInset; text()/findText() for tests. Free function diffRender(cur, prev) emits only changed cells as ANSI. |
Terminal |
RAII terminal: raw mode, alternate screen (1049), mouse (1002/1003/1006), focus (1004), bracketed paste (2004); restores on destruction. |
InputParser |
Byte stream → ParsedEvent (keys, SGR mouse, paste, focus, resize). Also directly unit-testable. |
Event |
type + KeyEventData/MouseEventData/paste/resize/tick/custom payloads, handled flag for bubble short-circuit. |
Signal<Args...> |
Lightweight slot list (connect, emit) used by every widget instead of raw callbacks. |
Widget |
Abstract base: bounds, parent, visible/enabled/focusable/focused/hovered, tooltip, minSize/prefSize/maxSize/flex, virtual draw(Canvas&), onEvent/onKey/onMouse, layout(), hitTest(), drawTree(). |
WindowManager |
Z-order, focus, drag/resize sessions, snapping, cascade, workspaces, closeAll() (honours sticky), maximize/shade/minimize, serialization. |
Desktop |
Root widget: wallpaper pattern, icon grid, icon activation signal. |
Window |
A Widget root with caption, close/shade/sticky/resize boxes, windowClass (semantic colour), modal/sticky/shaded/minimized/maximized, serialize/deserialize. |
Application |
Owns Config, Terminal, WindowManager, AppRegistry, panels, desktop, notifications; run(), quit(reason), notify(title, body), bell(), setFocused(w). |
IApp / AppRegistry |
Embeddable programs: name(), glyph(), createWindow(WindowManager&, Application&). Registering an app never touches framework code. |
VtParser |
VT100/xterm subset → cell grid (SGR, CUP, ED/EL, insert/delete, scroll regions, alternate screen with cursor save/restore, deferred wrap, UTF-8 split across feeds, BEL callback). |
TerminalWidget |
A widget hosting a real shell on a PTY; resize propagates via TIOCSWINSZ; exited child shows [process exited - press R to restart]. |
DragManager |
Drag sessions: DragPayload{type, text, row, colour, filePath}, ghost, valid-target highlighting, Esc cancel. |
BellService |
Audible (\a), visual flash, urgent flag, rate limiting, per-source suppression. |
3. Widget catalogue
All widgets: construct, set cfg, set bounds, add to a parent with
addChild(std::make_unique<T>(...)) (or raw new adopted by the demo's
manual panel assembly), wire Signals, done. Every widget supports
enabled/disabled (disabled ignores input, draws greyed), visibility,
tooltip, and focus policy (Widget::setFocusPolicy).
| Family | Classes |
|---|---|
| Containers | HBox, VBox, Grid, Spacer, Layered, ScrollView, SplitPane, TabView |
| Structure | Panel, InsetPanel, Frame, Empty, StatusBar, Badge, Toolbar, MenuBar |
| Buttons | PushButton (momentary/latched via latch), IconButton, ArrowButton, ToggleButton |
| Choice | CheckBox, RadioButton, RadioGroup, ComboBox, Menu |
| Text | Label, TextWidget, EditBox, TextEditor (alias TextView), NumericStepper, Slider, ProgressBar |
| Lists/data | ListBox, Matrix, Table (sortable headers), TreeView, IconGrid, Graph, FileList |
| Scrolling | ScrollBar (vertical/horizontal via bounds), contained in ScrollView/ListBox |
| Special | ViewportWidget, MiniMapWidget, TerminalWidget, OnScreenKeyboard, DatePicker, ColourPicker (alias ColorPicker), Tooltip, Notification (alias Toast), Dialog, MessageBox (info/errorBox/question factories) |
| Windows | Window, plus caption boxes drawn/hit-tested by Window itself (close at far left, shade/sticky at right, resize box bottom-right) |
Semantic window colours (Window::windowClass / Panel::windowClass):
brown setup/neutral, purple settings, grey company/save-load,
green construction/toolbars, lightblue network, lightred
authorities, blue messages, red errors, white newspaper. Values:
§6 / Config::defaults().
4. Events and focus
- Delivery:
Application::dispatch()→ global handler → capture phase (Widget::onCapture, root→target, mouse) → focused window → focused widget bubble, withEvent::handledstopping propagation.Window::onCloseRequestmay veto a close (return false); setforceCloseto proceed. - Mouse kinds:
Move, Down, Up, Click, DoubleClick, Wheel, DragStart, Drag, DragEnd, Enter, Leave. Double-click timing and tooltip delay come fromConfig(doubleClickMs,tooltipDelayMs) and are driven by the fake-clock seam in tests. - Keyboard:
KeyEventData{code, text, ctrl, alt, shift, ch}. One edit widget may hold global focus (OpenTTD rule): it receives all keys, including hotkeys, until Esc or click-away.Tab/Shift+Tabtraverse focusable, visible, enabled widgets. - Reserved global chords (configurable in
Config::keybindings):Deleteclose-all non-sticky (scoped, viakeybindings),Alt+Tabwindow switcher,F12/~console toggle,Ctrl+Qquit. Terminal widgets forward everything else to their PTY. - Timers:
Applicationtick events drive caret blink, news ticker, clock, notifications, and effect steps. No threads.
5. Windows
WindowManager::createWindow(title, windowClass, rect) returns a
Window* owned by the manager. Drag by caption (snap distance from
Config::snapDistance), resize by resize box/borders (min size
clamped), double-click caption or the maximize path to maximize into
the work area (screen minus panels). Shade = wheel on caption or shade
box; sticky windows survive close-all; minimized windows live in the
tasklist; switchWorkspace(i) filters visibility and tasklist/pager
contents consistently. Window state round-trips through
Window::serialize()/deserialize() (JSON values).
Closing a window is deferred. WindowManager::closeWindow(w) only
marks the window closing: it is hidden everywhere at once, manager and
Application references into it (focus, hover, capture, drag source,
registered terminals) are purged via onWindowClosed while it is still
alive, and the object is destroyed by processPendingCloses(), which
Application calls at the top of render() and once per loop iteration.
That makes closing safe from anywhere - the close box, Delete
close-all, or a button inside the window closing its own window (Logout
Cancel) - and stale
Window*held by app code (menu/console toggles) become harmless no-ops on a second close. Regression coverage:tests/test_focus.cpp("closing a window never leaves dangling refs") andtests/test_window_manager.cpp(screenshot content-offset case).
6. Configuration reference
Format: JSON (with // and /* */ comments tolerated by the built-in
parser) in *.env.json. Search order: --config <path> →
$RGUI_CONFIG → ./rgui.env.json → ./.env.json →
$XDG_CONFIG_HOME/rgui/rgui.env.json (or ~/.config/...) → built-in
defaults. Unknown keys warn and are ignored; wrong types warn and fall
back per key; malformed JSON reports line:col and defaults are used.
./demo --dump-config prints the effective config; feeding it back via
--config reproduces it exactly (tested). Settings in the demo edits
the same Config and can save it back (Config::saveToFile).
| Key(s) | Type | Meaning |
|---|---|---|
windowColors |
{name:{fg,bg}} |
Semantic window colours (§3). Colour values: "#rrggbb", 256-index number, or named. |
ttColors / colors |
{name:colour} |
The 16 Transport Tycoon colours (+Black). |
uiColors |
{role:colour} |
Widget base colours: paper, paperText, selection, selectionText, disabledText, menuPaper, iconGridBg, badgeBg, badgeUrgent, urgent, progressTrack, progressFill, tooltipBg, panelGrey. Read via Config::uiColor(role, fallback); every paper/selection-style widget honours it (see review.md M6). |
glyphs |
{name:string} |
close, shade, sticky, resize, up/down/left/right, check, radio, shadow, block, shadeLight/Med, shadeDark, halfTop, halfBot. |
bevelStyle, asciiMode |
string/bool | unicode (default) or ascii fallback for dumb terminals. |
panelHeight, panelPosition, bottomPanel, bottomPanelHeight |
int/string/bool | Panel geometry. |
padding, spacing |
int | Layout defaults. |
snapDistance |
int (0-10) | Window snapping threshold in cells. |
doubleClickMs, tooltipDelayMs, caretBlinkMs |
int | Input/animation timings. |
effectsEnabled, reducedMotion |
bool | Master effect switch; reduced motion forces effects off. |
dropShadow, popEffect, shadeSlide, menuReveal, smoothScroll |
bool | Individual effects (§8); final state is identical with them off. |
bellAudible, bellVisual, bellOnError, bellSuppressFocused |
bool | Bell routing (§8). |
bellVisualMs |
int | Visual-bell flash/urgency duration. |
keybindings |
{action:string} |
closeAll, switchWindow, console, quit. |
shell |
string | Shell for new terminals (/bin/sh default; the demo also respects $SHELL at the app layer where noted). |
workspaceCount |
int (1-8) | Pager/workspace count. |
clockFormat |
string | strftime format for the panel clock. |
wallpaperPattern, wallpaperColor, wallpaperFg |
string/colour/int | Desktop wallpaper. |
focusFollowsMouse |
bool | When true, hovering a window focuses it (Settings → Panel). |
mouseForwarding |
bool | Forward mouse to PTY children that request it. |
7. Writing an app and a widget
App (no framework changes needed). One rule first: the framework
does not retain your IApp instance - it is typically destroyed as
soon as createWindow() returns, while your windows live on. Widget
callbacks must capture the widgets they use (owned by the window),
never this. A [this] capture in a widget lambda is a
use-after-free segfault (this exact bug once crashed the demo console
on its first command; see the comment in ConsoleApp).
struct MyApp : IApp {
std::string name() const override { return "My App"; }
std::string glyph() const override { return "M"; }
void createWindow(WindowManager& wm, Application& a) override {
auto* win = wm.createWindow("My App", "grey", {10, 4, 50, 14});
win->appName = name();
auto* btn = new PushButton("Ring");
btn->cfg = &a.cfg; // style comes from Config
btn->onPressed.connect([&a]{ a.bellRing(); });
win->setContent(std::unique_ptr<Widget>(btn));
}
};
// in main(): app.registry.add("My App", "M", []{ return std::make_unique<MyApp>(); });
Widget: subclass Widget, set focusable/focusPolicy if it takes
keys, override draw(Canvas&) (draw inside absoluteBounds(), respect
enabled and hasStyleOverride), onKey/onMouse returning true when
handled, and measure()/layout() if it sizes children. Emit state
changes through a public Signal<...>. Then add its Gallery entry and
its test (the Gallery-coverage test in tests/test_xfce_demo.cpp fails
for a widget/app with no case - by design).
8. Effects and bell
Effects are steps in the timer queue, each gated by its Config flag;
with all effects off every operation is instant and lands in the same
final state (asserted in tests/test_effects.cpp). Bell: a PTY child's
BEL byte, Application::bell(), or an error dialog (if bellOnError)
routes through BellService - audible writes exactly one \a (never
for the focused terminal when bellSuppressFocused), visual marks the
window urgent in the tasklist until focused, bursts are rate-limited.
9. Terminal widget notes
TerminalWidget::start(shell) forks /bin/sh -c <shell> (or the given
command) on a PTY sized to the widget. VtParser is deliberately a
subset: it handles what shells and vim/less/htop-class programs
need (see its test fixtures), but it is not a full xterm - truecolor
SGR is stored per cell, wide characters are best-effort width-1, and
exotic modes (e.g. SGR mouse reporting to the child beyond the
forwarding flag) are approximations. The cursor is always inside the
grid (deferred-wrap flag, never cx == cols).
10. The demo, section by section
demo.cpp registers Terminal, File Manager, Editor, Settings, Widget
Gallery, SmallMap Toy, About, Calculator, Task Manager, Console.
Boot state: top green panel (Whisker-style searchable menu, launchers,
tasklist, 4-workspace pager, tray, clock + Calendar button, Log Out
dialog with Lock/Cancel), bottom grey status bar (user@host, memory,
CPU, scrolling ticker), wallpaper desktop with icons, and pre-opened
Terminal/File Manager/Settings/SmallMap windows. File-manager mutations
are confined to a sandbox directory; Task Manager reads /proc.
Console commands: help, open <app>, bell, effects on|off,
config, quit.
11. Known limitations (honest list)
- Compile time: one huge header × many test translation units is slow
at
-O2and can OOM under high parallelism on small machines; build test objects at-O0/-P2for iteration (commands in tests/README.md). - The ASan demo PTY run once exited 1 with no sanitizer report; the ASan unit subset is clean, the non-ASan PTY smoke is clean. Tracked, not hidden.
- Some XFCE goodies exist as panel indicators/compositions (tray, CPU graph, clock/calendar) rather than standalone apps.
VtParseris a subset (§9); the wallpaper is a shade-glyph pattern, not an image. These are terminal constraints, stated rather than silently approximated.
12. Documentation standard
Every public class, struct, enum, free function, and method in
ttgui.hpp and tttest.hpp carries a Doxygen
comment (/** @brief ... @details ... */, or /// @brief for one-line
helpers) naming its fields, parameters, return value, signals, and side
effects or invariants where they exist. Compact one-line widgets document
each public member inside their class block. Demo programs in
demo.cpp carry a one-paragraph @brief each, and main(),
runSelfTest(), and printHelp() are documented. When you add a public
API, document it in the same change - an undocumented public definition
is a review failure, on par with an untested widget (§13.6). User docs
live in README.md, test docs in tests/README.md; keep all
three in sync when behaviour changes.