Getting started: Trame in a new project
From an empty folder to a window, then the choices a project makes (render backend, text backend, accessibility), the tests, the versions, where state lives, and the pitfalls met so far.
1. Prerequisites
| What | Version | Needed for |
|---|---|---|
| Windows 10 or 11 x64, or Linux x64 | Windows: Win32, Direct3D 12 by default (shader model 6.9: a current driver). Linux: X11 or Wayland, Vulkan 1.3 (a GPU's driver, or Mesa's lavapipe without one), Rust for the text library (the native text backend, FONT_BACKEND's default off Windows). No macOS renderer. | |
| Formula | pinned in flake.nix | everything. Linux uses nix develop; Windows CI uses .github/actions/setup-formula |
MSVC + lld-link (Windows), or cc / clang (Linux) | linking object files produced by formula build --emit-obj; on Windows, rc.exe for an exe icon | |
| Rust, the stable toolchain of rustup | stable | only when building the optional native libraries locally (section 4: native text, accessibility) |
Nothing else: the default Windows build (Direct3D 12, DirectWrite, no accessibility) uses only Formula's std: library, the vendored bindings, and
the system. The fonts it falls back to (Roboto, Paper Mono, the icon font) are compiled into the executable; Paper Mono is also the monospace face of a program that gives none.
2. A new project with Trame as a submodule
mkdir myapp && cd myapp
git init
git submodule add https://github.com/sachahjkl/gui_toolkit ext/gui_toolkit
git -C ext/gui_toolkit tag -l # the published versions
git -C ext/gui_toolkit checkout vX.Y.Z # the latest
mkdir -p app build # the compiler does not create the output folderThe smallest application is examples/hello (a label, a text field, a button that counts its clicks). Copy ext/gui_toolkit/examples/hello/main.fm into app/main.fm, change #module hello to #module myapp, and build with the trame and vendor collections:
formula build --emit-obj --collection trame=ext/gui_toolkit/src --collection vendor=ext/gui_toolkit/vendor app -o build/myapp.o
cc -no-pie build/myapp.o -lm -ldl -lpthread -o build/myapp
./build/myapp # the window
./build/myapp --frames=3 # three frames of the hidden window, prints "hello: 3 frames, 11 boxes", exits 0#import "trame:ui", "trame:draw", "trame:render", "trame:font", "trame:platform", "trame:flate", and "trame:base" are the
packages in Trame's src folder; every module's #module name matches its directory leaf name, and they import each other by relative paths. Pass --release for an optimized build; omit it while iterating.
On Windows, link with lld-link and pass /SUBSYSTEM:WINDOWS for no console window (omit /SUBSYSTEM:WINDOWS while developing to see standard output).
examples/hello/main.fm uses a window as an object, host.Host (#import "trame:host", above ui and render):
App :: struct { shared: host.Shared, main: host.Host } // what the windows share; one window
if !host.host_open(&app.main, &app.shared, {title = "My app", size = {640, 400}}, build, app) {
os.exit(1) // it has said why: host.open_error(&app.main)
}
platform.show_window(app.main.win)
for !platform.is_closed(app.main.win) {
host.hosts_wait({&app.main}) // 0 % CPU at rest
host.host_frame(&app.main)
}
host.host_close(&app.main)When the window cannot open. host_open returns false and says why once, where a person looks: in the program's log
(std:log, the logger the program set), on standard error as <program>: <why>, and, for the first window of a Windows
program that has no console (-subsystem:windows), in a message box. On a machine with no graphics driver that is:
myapp: no graphics device this program can draw with (Vulkan): vulkan drivers/libraries could not be loaded. Install your system's Vulkan driver (the package mesa-vulkan-drivers on Debian and Ubuntu).The program then ends with its exit code. With crash reports on, it calls crash.end_session first (a defer does not
run under os.exit: return from the procedure that deferred it), and the next start finds no crash (crash.md). host.open_error(&app.main, allocator) gives the same sentence ("" once it opened) to a
program that shows it its own way; Host.failure says which step failed (Open_Failure: No_Window, No_Renderer,
No_Font, Refused for another window). rendering.md, "When init fails".
Each host keeps the times of its last pictures (Host.frames, host.FRAME_RING of them, in every build: a few stores a
frame, no allocation): the interface's builds and the draw up to the present, and with partial redraw on the pixels drawn.
host.frame_stats(&h.frames) gives their median and 95th percentile and the share of pixels drawn; it sorts at most
FRAME_RING numbers, so call it when they are shown (the settings' Diagnostics page does, once a second). A program
with a loop of its own keeps a host.Frame_Ring per window and calls host.frame_add(&ring, sample) at each picture.
build :: proc(h: ^host.Host, size: host.Vec2) holds the widgets (h.user is the app given to host_open). What it does
for you, in order:
host_open:render.preload_device(the device and its first pipelines on a thread, unless the program asked for it already),font.init,platform.open_window(..., transparent = true), the UI font,render.init_window(&r, win, win.size, transparent = true),render.set_fixed_surface(&r, platform.monitor_size(win))(below: a resize never stretches a frame); the UI font isfont.load_system_or_embedded(..., platform.system_font_path("segoeui.ttf"), font.FALLBACK_UI_DATA);draw.init,ui.apply_palette+ui.init, andwin.on_frame: a frame withinner = true, called from inside the system's loops (live resize, menus) byWM_PAINT;host_frame:render.pace_frame->platform.poll_events->render.resize->ui.begin_build-> your widgets ->ui.end_build->draw.begin_frame->render.frame_begin->ui.draw_tree->draw.end_frame->render.frame_end(&r, !at_once)->render.paced_present->free_all(context.temp_allocator)(docs/pacing.md);hosts_wait:platform.wait_event(win, ui.wake_in_ms(&s))unlessui.needs_frame(&s)(an animation): 0 % CPU at rest, woken by input or by the interface's own timers (caret blink, tooltip).
What a frame of yours does besides is a hook of the Host (src/host/host.fm): params (the style, the animations of each
build), input (events the interface does not see), builds (several builds in a frame: host.host_build again),
hold (no picture this frame), after_build, before_input, dragging, rest_frame, close_asked (the title bar's
close or the compositor's: the window stays, the program hides it or asks first; a window that has it gets its frame even
when the close was read in another window's frame, as on Wayland). A window hidden with
host.host_hide gets no host_frame until host.host_show (the program waits on it with platform.wait_event and
reads it with poll_events); the first frame after the show makes the renderer's surface again. When no window of the
Shared has shown for Shared.rest_after (0: 30 s; negative: never), the renderer lets its graphics device go, whatever
window the program waits on; host_show makes it again on a thread, and the window's first frame takes it
(rendering.md, "The device at rest"). host.rest(&shared) rests at once. Another window is another
host_open with the same Shared: a surface on the same renderer, built in turn, hosts_wait({&a, &b}) for both
(hosts_frame makes a frame of each). The steps above are all public: a program may make its frames by hand, as
examples/fidget does, or mix both. The windows of views (a view detached into a window of its own, docs/views.md) are
hosts too: ui.views_set_windows(&app.views, host.view_windows(&app.shared)) once for all the program's windows (each
view's window is made after the frames of the window that owns the view), and host_frame of a window makes their
frames after its own; hosts_wait counts them. Call ui.views_destroy before the last host_close.
Frames after a change. A window draws Host.after_input frames after each event (host_open and host_adopt set
host.AFTER_INPUT, 3, when the program has not set another count): what the event set off settles in them. A change that
comes with no event (a task's answer, a file read, an update's news) owes the same frames: host.host_settle(&app.main).
The start of a program. Its log (log.md) and its crash reports (crash.md) in one call, in main before any thread and any window (it reads the report folder there):
p := host.program_start({name = APP_NAME, folder = APP_FOLDER, version = APP_VERSION})
context.logger = p.logger
defer host.program_end(&p) // the clean end: the next start says no crash
crash_bar.init(&app.crash_bar, p.last_crash) // the last session's report, "" when it ended cleanlyProgram_Start_Options | |
|---|---|
name | the technical name: <name>.log and the reports' program line |
folder | the program's folder in its vendor's: the log goes to tlog.default_dir(folder), the reports to crash.default_report_dir(folder) |
version | the program's version, in each report |
dir | "": as above; else <dir>/logs and <dir>/crashes (a test's or a portable profile's folder) |
quiet | the log's lines are not echoed on standard error |
settings | a crash.Source: the settings that differ from their default |
no_session | a process that is not the program's session (a torn-off window's): no session mark, no last report |
launch | what starts the program again at program_end (nil: setup.launch); a test's records it |
program_start installs the log, then the crash handler with the log's tail, begins the session, then reads the last
report: begin_session is what turns a session that ended with no report (a kill) into the report last_report gives.
It logs a warning with the report's path. Program_Start.last_crash is owned; program_end frees it, ends the session and
closes the log; the caller's context.logger must not log after it.
A restart after the end. "Restart now" after an update: host.restart_after_exit(&p, args) (args: nil, or
{"--hidden"}), then the program quits as on any quit. program_end ends the session, then starts the executable that
program_start read (Program_Start.executable: after an update the running file can be <exe>.old), then closes
the log. program_end runs last, after the single instance is released and after prefs_page.install_launch: a copy
started earlier would hand itself over to this one. Asked again, the last args win.
Open_Options.headless opens a window of no system, drawn into an image (a test, a picture, a film of the interface).
Its first window draws on the software renderer: the same pixels on every machine. With headless_gpu it draws on the
graphics card when there is one, else on the software one: a long run of pictures goes as fast as the card (a 1080p film
of the showcase took 2.6 minutes on the card, more than 15 on the processor).
A window ready ahead. A window that must show at once when it is asked for (a screenshot tool's editor at its
shortcut) is opened hidden before: each turn while one is wanted, if host.ahead_due(&app.ahead, &app.shared, wake, app)
opens it. With no window yet, the graphics driver is made on a thread first (render.preload_device), whose end calls
wake(app); then it is due, once.
Text on a worker thread. A font.State is one thread's: a worker that draws text (a watermark on a picture) keeps a
host.Worker_Fonts and calls host.worker_fonts(&f) on its thread each time it needs them (made at the first call: the
interface's face, the system's else the toolkit's own, the rule of host.load_ui_font), then host.worker_fonts_destroy
when it ends.
Redraw only what changed. Set h.partial_redraw = true (any time; it is read at every frame): each frame then compares
what every box draws with the last frame and redraws only where something changed (a hover, a caret, an animation, a toast).
An idle frame redraws nothing; the window shows the same pixels as with whole frames. A program that makes its frames by hand
calls ui.set_partial_redraw(&state, true) before ui.draw_tree; ui.damage_stats(&state) says what the last frame
redrew. How it works and what makes a frame whole: docs/draw.md "Automatic damage". A program with the standard settings
needs nothing: rendering.partial_redraw is on by default, and prefs_page.standard_watch sets the flag it is given.
A window that resizes without stretching. An ordinary swap chain (open_window and init_window with their defaults)
is scaled to the window by the system: while the window is resized, the last frame is shown stretched until one of the new
size arrives. Three lines give a composition swap chain whose buffers keep the size of the screen, so that a frame of the old
size is clipped by the window instead (examples/hello has them; a window grown past the screen is shown scaled once, the
buffers then follow):
win := platform.open_window("My app", {640, 400}, transparent = true) // when the window is made: too late afterwards
render.init_window(&r, win, win.size, transparent = true)
render.set_fixed_surface(&r, platform.monitor_size(win))It stays opaque as long as the frame is (render.frame_begin with an alpha of 1): such a frame is presented with its
alpha ignored, so the desktop never shows through it. A clear of alpha < 1 (a translucent theme's background) makes the
window translucent again, at that frame; the renderer remakes its swap chain by itself. Colours in the linear blend space are
then held in 16-bit floats, twice the memory of the ordinary swap chain, for buffers of the screen's size. Vulkan has no fixed
surface (set_fixed_surface returns false): its swap chain is made again at each size.
tools/resize_probe checks a program from outside: it resizes the window and reads where a column of fixed width ends.
The widgets are calls in build (ui.label, ui.button(...).clicked, ui.line_edit, if ui.row() { ... }):
README.md ("What it looks like", "Features") and examples/fidget (the gallery of every widget) show the rest.
examples/showcase shows what a program gets from the toolkit, one scene each: the intents and the hues, the numbers
and ranges, the command palette, a menu that searches, the dialogs, the settings page, a node graph and its inspector,
the toasts, every theme and finish. Its data is fixed, so each scene is the same picture at each run.
./build/trame build showcase, then build/showcase --scene=graph --theme=Nord --light opens a scene in a theme;
the head of examples/showcase/main.fm lists its flags. Its code is the place to copy a scene from.

A password is ui.line_edit(id, &field, {kind = .Secret}): bullets in place of its characters, and it is neither copied nor cut.
Once it is used, ui.line_edit_wipe(&field) leaves nothing of it in memory (widgets.md, "A secret's memory").
Give it {kind = .Secret, reveal = &shown} (a bool the program keeps) and an eye at its end shows the text and hides it again; shown, it is
text like any other. The field keeps the keyboard when the eye is clicked.
A field with things beside it in one surface (a search icon, the field, a count) is an if ui.input_frame(id) { ... }.
The frame draws an input's background, border and corners (its radius from next), and one focus ring around all of
it while a box inside has the keyboard focus (the box flag .Focus_Within). Build the field inside under the tag
"bare" (if ui.tags("bare") { ui.line_edit(...) }): the default theme makes a bare field's background, border and
focus ring clear, so it does not draw a second box inside the frame.
A box's square_corners (ui.Corners: .Top_Left, .Bottom_Left, .Top_Right, .Bottom_Right) stay square whatever its
radius: its background, border, shadow, hover and focus ring follow (ui.box_radii, ui.radii_grown; ui.paint_rect_corners
is paint_rect with a radius per corner).
A box that declares its sides (.Draw_Side_Top, .Draw_Side_Bottom, .Draw_Side_Left, .Draw_Side_Right) has those
lines alone: no finish draws its rim (the lit line round a raised face) on it. Nor on a box flush with an edge of the
window, a bar. Nor on a box inside a face that draws (a background, a border, a custom draw: a frame, a card, a well)
when it meets that face's inner top edge or runs across its whole inner width: a header, a row, a stripe. The rim is for
a face that stands on its own: a button, a card, a chip, a dialog. ui.box_rimmed(s, b) says whether a box gets the rim;
ui.paint_rect_corners(..., rim = false) paints a face without it; sunk = 1 paints it pressed in (a gradient turned
over: docs/themes.md, "States in each finish"), as ui.lit_face(..., sunk) does.
ui.next({width = ui.fill(), height = ui.px(em * 2), radius = em * 0.45})
if ui.input_frame("###search") {
glyph(ICO_SEARCH)
ui.next({width = ui.fill(), height = ui.pct(1)})
if ui.tags("bare") { ui.line_edit("###field", &field, {placeholder = "Search"}) }
}3. What trame build does
./build/trame build <example> [-debug] (in the toolkit's folder; build.bat and ./build.sh are its shortcuts) compiles
examples/<example> with formula build --emit-obj --collection trame=src --collection vendor=vendor (with --release unless -debug or -fast) and links build/<example>. On Windows it links with /SUBSYSTEM:WINDOWS and examples/<example>/<example>.res when the example has an icon; on Linux it builds the native
text backend first (the default backend there). It builds the examples only; your project calls formula build (or its own toolbox tool) as above.
4. Choices made when compiling (--define)
| Define | Values | What it needs |
|---|---|---|
TOOLKIT_RENDER | auto (Windows' default: Direct3D 12 with runtime Vulkan fallback; the compressed Agility SDK runtime fetched by trame fetch_d3d12 is built in), d3d12 (Windows Direct3D 12 only), vulkan (every other system's only backend; Windows Vulkan-only override: rendering.md) | a Vulkan 1.3 driver on Linux or Windows fallback |
FONT_BACKEND | dwrite (the default, Windows only), native (required on Linux: without it no text is shaped) | native: ./build/trame build_native -features:text (cargo, about 45 s the first time) -> ext/gui_toolkit/build/native/trame_native.lib (or libtrame_native.a) |
A11Y_ACCESSKIT | false (default), true | ./build/trame build_native -features:a11y (cargo, about 20 s) -> ext/gui_toolkit/build/native/trame_native.lib |
FONT_TEXT_RENDERER | atlas (default on Windows), slug (default elsewhere, the only one there) | nothing (Slug: glyphs drawn from their outlines on the GPU; also per font.State at run time) |
TRAME_DEVTOOLS | true in a -debug build and a test, else false | true: the CDP endpoint of devtools.start_from_env in a release build (devtools.md) |
LUCIDE_SUBSET | "" (default: the whole Lucide font), an absolute path | the program's icons only, made by toolbox.lucide_subset (lucide.md) |
FONT_EMBED_FALLBACK | true (default), false | false: no Roboto or Paper Mono compiled in; only for a program that loads its fonts itself |
What each costs in the executable: builds.md. A program's tool declares them once in toolbox.Project.features.
The commands of tools/trame are independent (any order; each does nothing when its output is current: a STAMP file next to it).
They write into the toolkit's own build\ folder, where its packages link them from (foreign import
"../build/native/trame_native.lib"). fetch_emoji (the color emoji font of tests/colr) and fetch_shokado (the shader compiler, for whoever edits
the shaders) are for the toolkit's own work, not for an application.
- Render backend. On Windows, Direct3D 12 is the default and the complete one. Vulkan, Linux's only one, has the same interface and passes the same pixel tests, but no GPU canvas engine and no fixed surface: rendering.md.
- Text backend. DirectWrite is the default on Windows: system fonts, shaping, fallback.
native(Fontations, HarfRust, ICU4X in Rust) needs no DirectWrite: it is the backend on Linux, and an option on Windows: font-backend.md, text.md. - Accessibility. On Windows, without
A11Y_ACCESSKIT=truescreen readers see an empty window (on Linux a small AT-SPI bridge is always there). With it, every widget is read through UI Automation, and the tree costs nothing until a reader asks: accessibility.md. A program with a Rust library of its own buildsnative/a11y(andnative/text) into it instead and adds-define:A11Y_NATIVE_LINK=false(FONT_NATIVE_LINK=false): one Rust standard library per program.
5. Tests
In the toolkit's folder (the CI runs the same: .github/workflows/ci.yml):
./build/run_tests flate # one package
./build/run_tests keyboard # packages that build interfaces
./build/run_tests # every package (needs the native library on Linux)Pixel tests draw on an offscreen renderer on a software device (render.init_offscreen(&r, size, software = true): WARP on
Windows, lavapipe on Linux under Vulkan's validation layer; the same pixels on every machine, no window). Timing assertions only run with GUI_PERF=1 and never in CI (base.perf_skip).
A test of your own interface uses src/testkit/session (testing.md): an application with no window, input through the
event path, real pixels, barriers on a state, and a clock of its own, so that the caret blink, double clicks and delays do not depend on how
fast the machine runs.
6. Versions and changes
Semantic versioning, ui.VERSION, git tags vX.Y.Z with a GitHub release each; while 0.x a minor version may change
the API (CHANGELOG.md says how). Pin the submodule to a tag and read the CHANGELOG's section before moving it. A change to
the toolkit itself follows CONTRIBUTING.md: a fragment in changelog.d/, never an edit of
CHANGELOG.md or src/ui/version.fm.
7. Where state lives
What is one window's or one app's lives in the struct that owns it, so that several apps run in one process, each on a thread of
its own: the window's in platform.Window, the device's in render.Renderer, the interface's in ui.State (the names of the
caption buttons too: ui.set_window_button_names(s, ...) translates a State's). A package-level variable is one of four
classes, and only these:
| Class | What | Example |
|---|---|---|
const | a table, written by the compiler, or once (at start-up, a sync.Once) before anything reads it; then only read, by any thread | ui.THEMES, the Wayland protocol tables, the sRGB tables |
process | a resource of the process, one whatever the number of apps: locked, atomic, or bound to a thread its note names | the clipboard store, the device made early (render.preload_device), the window class, a library of the system |
thread | @(thread_local): each thread its own | the State a thread builds, the frame gate, OLE on Windows, the display connection and session bus on Linux |
test | a test's own |
On Linux each thread that opens windows has its own connection to the display server (its events, its seat's focus) and its own session bus: a window's procedures are called on the thread that opened it, as on Windows, whose messages are the thread's.
tools/globals_allowed.txt lists every global of the packages with its class and why; tests/globals (in ./build/run_tests)
fails on a global that is not listed, on one listed that is gone, and on a class the code contradicts (@(thread_local) is
thread, and only it). Build tests/globals with --test --define GLOBALS_WRITE=true to rewrite the list from the code, keeping the classes
known; a new one gets ? until it is classified, or moved into its struct.
8. Pitfalls
- The output folder must exist:
formula build --emit-obj ... -o build/x.ofails whenbuild/is missing. - Repeated test runs: build a test binary with
formula build --emit-obj --test --collection trame=src --collection vendor=vendor tests/<name> -o build/<name>_test.o, link it, and run it repeatedly to chase an unstable test. - A
render.Surface(second window) in a local variable: it is several kilobytes; copying it on the stack bloats optimized codegen. Make it where it lives:render.surface_init(&r, &app.surface, hwnd, size), nots, ok := render.surface_create(...). - One interface build at a time per thread:
ui.begin_buildinside another build (a frame made fromWM_PAINTwhile a menu's loop runs inside your build) asserts; checkui.building()at the top of the frame procedure (hello does). Theuipackage keeps the State being built per thread (@(thread_local)): each thread builds its own interface, and a publicuiproc called on a thread where noinit,useorbegin_buildselected a State stops at once withui.NO_STATE_MESSAGE("ui: no begin_build on this thread") instead of crashing further on. - Several windows: give each window a
ui.Stateof its own and passBuild_Params.inactive = truewhen building a window that is not the one the user is in: its focused text fields keep their focus but show no caret and ask for no wake to blink it (ui.inactive()tells a widget of your own), as every desktop does. - A scope under a negation: a procedure with a deferred end (
ui.row,ui.parent,ui.menu,debug.section:@(deferred_out),deferred_none) ends where the scope of its call ends.if !ui.parent(page) { return }ends the parent at the end of theif: what follows is built outside it. Build insideif ui.parent(page) { ... }, or call it as a statement:inside := ui.parent(page), thenif !inside { return }.toolbox.check_scopesfinds the wrong form (a step ofprogram_check, toolbox.md). - Keys: widgets are found again from frame to frame by their id.
"Label"alone uses the text as the id: two buttons labelled "OK" collide and a label whose text changes loses its state. Use"Text###stable_id"(the part after###is the key) for anything whose text changes, as hello does for the counter. - A press on a box that is not a button (a right click that opens a menu on a message, a card): check it with
ui.pointer_on(box), not with its rect alone. It says whether the pointer is on the box with nothing drawn over it there, as the last build laid it out: a box that a later sibling covers (a message the conversation scrolls under its composer, a panel under a floating one) is not under the pointer, the box in front is. A.Clickablebox's ownright_clickedalready goes to what is in front. - At an event's own position (each event of a batch, not the pointer's last place):
ui.pointer_on_at(box, p)ispointer_onatp, andui.hit_box_at(p)is the box a press atpacts on (the topmost enabled clickable box there; nil: none), both by the last layout. A terminal's grid decides per event which ones are its own. - Free the frame's temporaries:
free_all(context.temp_allocator)at the end of each frame (thefmt.tprintfstrings of labels live there).ui.line_edit_destroytheLine_Edits you made. expect_assertin tests: on Windows the test runner's handling of an assertion races the system's end of the process; a test program can end without a word. Catch an expected assertion on a thread of your own (tests/ui_robust/nested_build_test.fm).- Rust libraries out of date: after updating the submodule, run
./build/trame build_nativeagain (they rebuild only when the sources changed); an oldtrame_native.lib/libtrame_native.awith new Formula code fails at link or at run time. - Console output of a
/SUBSYSTEM:WINDOWSexe is lost: redirect it, or link without the flag while developing.