toolbox: what the tools of a project share
toolbox :: #import "<toolkit>/src/toolbox" (or #import "trame:toolbox" with the collection). It is for the tools that build, check and publish a project (tools/trame here, ocntools in opencode native,
Wren's tooling), not for the programs they make. Pure Formula with std:os, Windows and Linux.
ok := toolbox.run({"cargo", "build", "--release"}, {dir = "native"}) // its output on this process's
ok = toolbox.run({"./build/run_tests", "fsx"}, {log = "build/fsx.log", limit = 10 * time.Minute, echo = true})
out, code := toolbox.capture({"git", "rev-parse", "HEAD"}) // standard output and exit code
env := toolbox.env_with({"XDG_CONFIG_HOME"}, "XDG_CONFIG_HOME=/tmp/c") // this process's, changed
sum := toolbox.sha256_hex(data) // 64 lower-case hex digits
sum, ok = toolbox.sha256_file("build/x.zip")
why := toolbox.download_pinned(URL, "build/x.zip", X_SHA256) // "" when the file is there and as pinnedRun
run(command, o: Run_Options) starts the command and waits for it. It returns true when the command started and exited
with 0. The fields of Run_Options, all optional:
dir: the working directory ("": this process's).env: the whole environment of the command (nil: this process's).env_withmakes one.log: a file. The standard output and error of the command are appended to it, and so are the lines thatrunsays. "": the command writes to this process's output, and reads this process's input.limit: a time limit (0: none). After it, the process is killed andrunreturns false. Only the process is killed, not the processes that it started.echo:runwrites> commandfirst.
capture(command, o) returns the standard output of the command and its exit code. The code is -1 when the command did not
start. When the command fails, its standard error is written to this process's. o.dir and o.env apply.
exit_code(state) is the exit code of a finished process (-1 when it did not exit). Windows gives the code as an unsigned
number: exit_code reads it back as a 32-bit signed integer, so exit(-1) gives -1 and a crash gives a negative NTSTATUS.
succeeded(state) is true when the process exited with 0. Do not use Process_State.success: on Windows it is always true.
env_with(without, ..extra) is this process's environment without the variables named in without and without the
variables that extra sets, followed by extra ("NAME=value"). Names compare by ASCII case on Windows and exactly on other
systems. The per-drive entries of Windows (=C:=C:\work) stay.
Process groups (Linux)
start_group(command, env, out) starts a command in a process group of its own (setsid). env is its whole environment
(nil: this process's); out receives its standard output and error (nil: none). stop_group(p, wait) sends SIGTERM to
the whole group, waits for the leader at most wait (default GROUP_STOP_WAIT, 3 s), then sends SIGKILL to what is left.
group_ended(p): the leader was waited for and ended; what it left in its group is killed, and the group is no longer
stopped. Use them for a program that runs beside a tool, such as a compositor for tests: a wrapper (NixOS's sway is
dbus-run-session) starts the real program as its child, and a signal to the wrapper alone leaves that child running.
guard_groups() installs a handler of SIGTERM, SIGINT and SIGHUP (timeout's signal, Ctrl+C, a closed terminal): it kills
every group that start_group started and stop_group did not stop, then ends the tool. Call it once, before the first
group.
A desktop nobody sees: the sway session (Linux)
sway_start(&s, dir, o) starts sway with no screen (headless) in dir, made anew, and waits until it answers
(swaymsg -t get_outputs), at most o.wait (SWAY_WAIT, 8 s). It returns "" when sway runs, else why not.
Nothing of the person's desktop is reached:
- its own runtime directory,
<dir>/run(mode 700): its own Wayland socket and IPC socket; - no
DISPLAY, no session bus (DBUS_SESSION_BUS_ADDRESS), noXDG_CURRENT_DESKTOP; - one headless output at
o.output(SWAY_OUTPUT_DEFAULT, 1600x1000), no XWayland, no input devices; - with
o.homes, the programs'HOMEis<dir>, andXDG_CONFIG_HOME,XDG_DATA_HOMEandXDG_STATE_HOMEare<dir>/config,dataandstate: an install in~/.local/optstays in the session's folder, and a path a program shows reads~/config/..., with no path of the machine in a picture; witho.cache,XDG_CACHE_HOMEis<dir>/cache.
o.config adds lines to sway's config (for_window [app_id="x"] floating enable); o.renderer is pixman
(the CPU, default) or vulkan. sway_config(o) is that config. The session's fields: dir, runtime, display
(WAYLAND_DISPLAY), ipc (SWAYSOCK) and env, what a program in the session gets.
sway_program(&s, command, env, log) starts a program in the session, in a group of its own, with s.env and env
("NAME=value", over it). Its output goes to log ("": <dir>/<program>.log). sway_wait(&s, p, limit) waits at most
limit for it to end (a quit asked): ended and its state, what it left in its group killed. sway_stop(&s) stops the session's programs, then sway, each with all it started, and frees the
session. On another system, sway_start returns why it does not run.
s: toolbox.Sway
defer toolbox.sway_stop(&s)
toolbox.guard_groups()
if why := toolbox.sway_start(&s, "build/live", {config = `for_window [app_id="papier"] floating enable`, homes = true}); why != "" { return fail(why) }
p, why := toolbox.sway_program(&s, {"build/papier", "--hidden"}, {"TRAME_DEVTOOLS=9300"})trame desktop_tests wayland runs the toolkit's desktop tests in this session.
A program driven by its tool: the program session
A tool's live, shots or bench starts its program on the desktop above, drives its window over the DevTools
protocol (cdp.md), then ends it. Program_Session does the whole of it
(src/md/infrastructure/program-session.md says why each part is so).
program_session_start(&s, dir, o)starts the desktop indir(made anew,o.desktop:Sway_Options), writeso.files(Program_File{path, text},pathunder the session's folder, its folders made), then startso.commandwithTRAME_DEVTOOLSon a free port ando.envover the desktop's environment. Its output goes too.log("":<dir>/<program>.log). It returns "" when the program runs, else why not. It does not connect: a program may show its window later.- The program draws with Vulkan on the CPU (Mesa's lavapipe), never the machine's GPU:
VK_DRIVER_FILESnames lavapipe's manifest alone and the implicit layers are off (VK_LOADER_LAYERS_DISABLE=~implicit~). AVK_DRIVER_FILESthat already names lavapipe is kept (the CI's); else it is looked for in Vulkan'sicd.dfolders (XDG_DATA_DIRS,/run/opengl-driver/share,/etc,/usr/share):software_vulkan_driver()gives its path, for a tool that starts a program without the session. A machine without it does not start the program.o.gpu = truekeeps the environment's driver: a demo a person watches. program_session_connect(&s)connects to the window, tried until it answers, at mosto.wait(PROGRAM_START_WAIT, 60 s). It fails at once when the program ended, and when the program's log says that its DevTools server could not listen (another program took the port first). It returns the client, or why not. Connect as many times as needed (a window hidden and shown again).program_session_restart(&s)asks the program to quit and starts it again in the same desktop and folders. It returns the first run's exit code and why the new run did not start.program_session_stop(&s)asks the program to quit, waits at mostPROGRAM_END_WAIT(8 s), then stops the desktop and frees the session. It returns the program's exit code (-1: it was stopped, or it did not run). It is safe after a start that failed.- The quit is
o.quit, a command run in the session ({"build/papier", "quit"}); none closes the window over the protocol (Browser.close). - The session's fields:
dir,port,env(the program's whole environment: run a command of the session withcapture(command, {env = s.env})),program,log,started. free_port()gives a port of 127.0.0.1 that no program listens on now. Use it for any program a tool starts withTRAME_DEVTOOLS, with or without the desktop. Never a fixed port: a second run cannot listen on it, and its tool then drives the first run's window as its own.
s: toolbox.Program_Session
defer toolbox.program_session_stop(&s)
if why := toolbox.program_session_start(&s, "build/shots", {
command = {"build/papier", "--hidden"},
desktop = {config = `for_window [app_id="papier"] floating enable`, homes = true},
files = {{"config/FromentSoftware/Papier/prefs", "wbprefs 1\nappearance.mode\tdark\n"}},
quit = {"build/papier", "quit"},
}); why != "" { return fail(why) }
_, _ = toolbox.capture({"build/papier", "show"}, {env = s.env})
c, why := toolbox.program_session_connect(&s)
if why != "" { return fail(why) }
defer cdp.close(&c)Hashes
sha256_hex(data) and sha256_file(path) give the SHA-256 as 64 lower-case hex digits. sha256_file returns ok = false
when it cannot read the file. Both use the frame's allocator unless an allocator is given.
Pinned downloads
download_pinned(url, path, sha256, log, quiet) makes sure that path holds the file whose SHA-256 is sha256:
- If the file at
pathhas that SHA-256, it is kept and nothing is downloaded. - Else curl downloads
urlintopath(the folder is made first). Curl tries again 5 times, 10 s apart, on any error. - If curl fails and
urlis the file of a GitHub release (https://github.com/<owner>/<repo>/releases/download/<tag>/<name>),download_through_apiasks GitHub's API for the asset and downloads it.GH_TOKENorGITHUB_TOKENis sent when set. - The SHA-256 of what came is checked. If it is not the pinned one, the file is removed.
It returns "" when the file is there and as pinned, else why not. log receives curl's output and the lines said ("": this
process's output). quiet keeps the lines "downloading ..." from being said.
On Windows, curl and tar are the system's own (system_program("curl"): C:\Windows\System32\curl.exe), never another
program of that name earlier on the PATH. On other systems, system_program returns the name: the PATH finds it.
release_asset_id(release_json, name) reads the id of an asset from the answer of GitHub's API for a release ("": none).
test262
test262_fetch(dir, log) puts in dir what a run of the ECMAScript test suite reads, and returns "" or why not:
dir/test262: tc39/test262 at the commit QuickJS-ng 0.17.0 runs (TEST262_COMMIT), from a GitHub archive pinned by SHA-256. ItsCOMMITfile says which commit is unpacked. If it is another, the suite is unpacked again.dir/test262.conf,test262-fast.confandtest262_errors.txt: QuickJS-ng's runner configuration (TEST262_QJS_VERSION), unchanged, from its release source. A file is written only when it differs, so two runs can sharedir.
The archives and QuickJS-ng's source stay in dir. Wren's runner of its
Wasm image calls it to judge against the pinned suite and reference.
The tests (./build/run_tests toolbox) run without a network: the hashes, env_with, a run with a log and a time limit, a
capture in another folder and environment, a pinned file kept, a file: URL downloaded, and a wrong SHA-256 refused.
WebP
webp_encoder(dir) -> (encoder, why) is cwebp, libwebp's encoder: the system's elsewhere (nix libwebp, Debian webp), and on
Windows libwebp's own build, fetched into dir once and pinned by its SHA-256. webp_encode(encoder, src, dst, width = 0,
quality = WEBP_QUALITY) writes src (PNG, JPEG, TIFF or WebP) as a WebP, width pixels wide (0: its own), with -preset text:
a screenshot's small text stays as sharp as in its PNG, the file some twenty times smaller. image_width(data) reads a PNG's or
a WebP's width from its header (pure).
A program's logo
Each program draws its own logo; write_logo(logo) writes what every program makes of it. The program gives
draw(pixels, size, user), which draws the logo pixels wide as it must read once shrunk to size (a small size drops
its details; a canvas the toolbox frees). The toolbox draws each size at draw_size or more (0: master; with neither,
at its size), by multiples of LOGO_SHRINK_STEP (4), then shrinks it by 4 at most at each step, so its edges stay clean
at 16 px (logo-files.md). The program says which files it wants:
dirandmaster:<dir>/logo.pngatmasterpixels (0: none).sizes:<dir>/logo_<size>.pngeach (the desktop entry, the site, the program's window).ico: the.icoof the Windows executable, with the sizesico_sizes(nil:ICO_SIZES, 16 to 256 px). Each size is drawn for itself. The sizes fromico_png_fromare PNG entries, the ones below are classic DIBs (0: all PNG).project_image:PROJECT_IMAGE(.project/image.png, 512 px), the picture of the repository and of opencode's sessions of it.files: more PNG files, each aLogo_File(a path and a size): the site's logo.
It says each file it writes and returns "" when all are written, else the file that is not. Folders are made.
detail_for :: proc(size: int) -> int { return size <= 24 ? 0 : size <= 48 ? 1 : 2 }
logo_draw :: proc(pixels, size: int, _: rawptr) -> paint.Canvas { /* draws at pixels, with detail_for(size) */ }
why := toolbox.write_logo({draw = logo_draw, dir = "assets", master = 1024, sizes = {16, 32, 64, 128, 256},
ico = "assets/papier.ico", project_image = true})logo_picture(logo, size) -> paint.Canvas is one size as write_logo makes it (a sheet of the sizes, a test).
logo_shrink(big, size) -> paint.Canvas is the shrink alone: big destroyed, the picture size square. A logo made
of layers shrinks each layer with it before it draws the next one over it.
logo_command(logo) -> Command is the logo command of a project's tool: write_logo of logo (copied; its slices
must live as long as the tool).
A Windows executable's resource
Every program gets the same Windows resource from its Project, with no .rc file and no manifest of its own.
build_windows(p) (which build_native runs first) writes them in WINDOWS_RESOURCE_DIR (build/windows), each file
only when it changes, and odin_command passes the script to the linker (-resource:):
| Resource | From | What shows it |
|---|---|---|
id 1, ICON | Project.icon ("": assets/<name>.ico) | Explorer, the shortcuts, Settings > Apps, the taskbar, every window (the window class loads id 1, big and small) |
id 1, VERSIONINFO | the version (version_file), title ("": name), description, publisher, copyright | Properties > Details; Task Manager names the process by the file's description |
id 1, RT_MANIFEST | the version, project_aumid(p) (the assembly's name; else name) | runs as the user who starts it; Windows 10 and 11; per-monitor DPI aware (v2); UTF-8 as the code page of the A functions and the C runtime; paths longer than MAX_PATH; the common controls of version 6 |
write_windows_resource(p, dir = WINDOWS_RESOURCE_DIR)writes<dir>/<name>.rcand<dir>/<name>.manifest.whysays what is wrong: the version is not three numbers of 16 bits, or the icon is not there (the tool'slogocommand writes it).windows_resource_script(p, version, icon, manifest)andwindows_manifest(p, version)are their texts.version_numbers(version)reads "x.y.z".windows_resource_path(p)is the script,project_icon(p)the icon,project_title(p)the title.exe_has_icon(path)(Windows) is true when the executable carries an icon group 1.check_launcherchecks it.
A program's update files
update_command(product, args) is the update command of a project's tool, for its product (docs/update.md):
update keygen <file>: a new key pair. The private key goes in<file>(refused inside a git work tree, or over a file that exists); the public key is printed, for the product'spublic_key.update pubkey: the public key of$UPDATE_SIGNING_KEY(UPDATE_KEY_ENV).update manifest <program> <version> <channel> <out.json>: the manifest of the program (namedexpected_file_name(product, version, platform);-for no channel) and its.sig, signed by$UPDATE_SIGNING_KEY.update verify <manifest.json> <channel>: the manifest and its.sig, checked with the product's key.
update_manifest(product, program, version, channel, out) is the manifest step alone, for a tool's release step.
update_earlier(product, earlier, program, version, last_earlier, channel, out_dir) is the release step of a product that
changed its name: the program (named as a release of product) copied into out_dir under the earlier product's file
name, with the earlier product's manifest of it and its .sig. An install of the earlier name updates from that folder
(update.md). version must be above last_earlier, the last version
released under the earlier name: an earlier updater takes only a newer one.
A program's licences
licence_commands(tool) gives the licence and paddle commands of a project's tool, for its Licence_Tool (its
licence.Product, the folder of its private key, its development pair, the hint of its files, its Paddle catalogue):
licence keygen,licence pubkey,licence issue,licence verify: the signing key pair (outside any git work tree, inlicence_key_dir(tool)), a licence signed by hand, a check;licence secrets <secrets.yaml> <out.env>: the Worker's secrets decrypted by sops (sops_dotenv), to a file git ignores;paddle [-apply]: the product and its prices in Paddle's catalogue, overtrame:http.
licence.md says the whole flow and each command.
Crash reports
A program's crash reports (crash.md) give each frame as a module and an offset. These name the offsets of the program's own module offline, with what its build left:
CRASH_LINKER_FLAGS: what the program's-extra-linker-flags:must hold. Windows:/MAP(the linker's map of every function). Linux:-Wl,--build-id(the build id the report names).crash_publish_symbols(exe, allocator) -> (named, why): after each link. Windows:<dir>/<stem>.mapbecomes<dir>/<stem>-<build>.map, and the older maps of that stem go; keep it with the release. Linux: checks that the executable has a build id;namedis the executable.whysays what is wrong ("": done).crash_build_id(path, allocator) -> (id, ok): the build a file is, as a report names it: a PE file's link time stamp and image size (%08X%X), an ELF file's GNU build id. Any system reads either.crash_symbolize(report_path, symbols, allocator) -> (text, why): the report with the program's frames named.symbolsis a map, a folder that holds<stem>-<build>.map, or (a Linux report) the executable that crashed, read throughaddr2line. The map is read in pure Formula: a Windows report is named on any system. An executable of another build is refused; a map of another link gives asymbols-warningline. The text is a report again, with asymbolsline that says from what.
trame crash_symbolize <report> <symbols> prints it.
// a program's build tool, after its link
append(&flags, fmt.tprintf("-extra-linker-flags:%s", toolbox.CRASH_LINKER_FLAGS))
...
if named, why := toolbox.crash_publish_symbols(exe); why != "" { return why }A project's tool
A project's tool is one program with a command each: tools/trame here, and every program's (classeurtool, papiertool...).
It is a list of Commands given to tool_main:
main :: proc() {
p := project()
r := release.commands({project = p, dist = "build/dist", files = FILES[:], check = proc() -> cli.Exit { return run_check(nil) }})
toolbox.tool_main("classeurtool", {
{name = "build", usage = "[release]: the program", run = run_build},
{name = "check", usage = ": the checks of the CI", run = run_check},
changelog.command(p), site.command({meta = site_meta()}), toolbox.logo_command(LOGO), r[0], r[1], r[2],
}, toolbox.ROOT_MARK_DEFAULT)
}A Command has a name, a usage (its arguments and what it does, one line) and run(args) -> cli.Exit, the arguments
after its name. A command made for a project (changelog.command, site.command, release.commands, logo_command,
notices_command) has run_with(args, user) and its user instead. With checked, the line is checked first: a flag is
-name (a switch) or -name:value, and must be one of flags ("name", "name:"); positionals is the number of
plain arguments (-1: none or one). A command not checked reads its own arguments (--port 9222, --dry-run).
tool_main(program, commands, root_mark = ""):
- reads the line, each
-name:and its value joined again (args_joined: PowerShell 7 splits-name:valuetyped after--into two arguments); - with a
root_mark(ROOT_MARK_DEFAULT:odin.version), finds the project's root, the first folder from the working directory up that holds it (project_root(start, mark)), and works there; none:.Usage; - runs the command (
dispatch(program, commands, args) -> cli.Exit) and ends with it (cli.exit).
A command ends with a cli.Exit (the same as a program's line, cli.check): .Done when the work is done, .Failed when it failed (it said why), .Usage for a line
it does not take. Only tool_main turns it into the process's exit code: 0, 1 and 2.
| Line | Exit |
|---|---|
no command, help, -h, --help | .Done: the commands and their usages (tool_usage); help <command>: that one |
| a command it does not know | .Usage, the commands said |
| a checked command's line that is not one it takes | .Usage, its usage said |
| a command | its own |
done(why) -> Exit is how a work that says why it failed ends ("": .Done, else .Failed), the failure said as
<tool> <command>: why. ended(ok) -> Exit is .Done or .Failed for a step that said why itself.
command_find(commands, name) and args_check(command, args) are the dispatcher's steps.
generated_files(root, files, check, command = "") -> string writes each [path from root, text] of a tool's generated
files, only those that changed; with check it writes nothing and says which differ, command named as the way to make
them again.
{name = "gen_docs", usage = "[-check]: generated files from declarations", run = proc(args: []string) -> cli.Exit {
files := [][2]string{{"generated/api.md", build_markdown()}}
return toolbox.done(toolbox.generated_files(".", files, toolbox.has_flag(args, "check"), "mytool gen_docs"))
}},The flags of a line: has_flag(args, name), flag_value(args, name, default) (the last one given wins),
int_flag(args, name, default) and f64_flag(args, name, default) (why: not a number), plain_args(args) (the arguments
that are not flags; a lone - is plain).
A project
Project is what a program's project is to its tool, and to the standard commands:
| Field | What it is |
|---|---|
name | the program (classeur): its archive's, its commit's, the launcher's answer |
repository | https://github.com/<owner>/<repo> |
changelog | CHANGELOG.md ("": that), its fragments in changelog.d/ beside it |
version_file, version_line | the source of the version (the program's main file) and its line's start (APP_VERSION ::) |
program | the release build (build/classeur) |
src | the program's package ("": src) |
toolkit | the toolkit's checkout ("": $TRAME, else TRAME_DEFAULT, ext/gui_toolkit) |
collections | more collections than trame: a name and its folder |
defines | what every build, test and check command of the program gets, on every system |
linux_defines | what every build, test and check command of the program gets on Linux |
link | what the linker gets beyond the toolkit's own, a Link: static_vcruntime (Windows: the C runtime linked in, no vcruntime140.dll to ship), strip (Linux: a release build has no symbol table), force_multiple (Windows: /FORCE:MULTIPLE, a symbol two static libraries define taken once; not for Vt's builtins, see vt_dedup), rust_libs (Windows, with native_carried and Vt: the program's own Rust static libraries, from its root, "build/native/tower_native.lib", of which vt_dedup links a stripped copy; the foreign import reads <STEM>_LIB) |
launcher | Windows: the rules of its console launcher, a Launcher (below) |
thumbnailer | its thumbnail provider's package, a folder of the program's tree ("": none): Windows builds it as a DLL the program embeds (below) |
licence | its licence, for its notices ("": MIT) |
features | what it takes of the toolkit beyond the core, a Features (below) |
crates | its own Rust libraries, for its notices: their Cargo.toml, relative to its root (rust/core/Cargo.toml) |
native_carried | one of its own Rust libraries carries the toolkit's native crates: build_native builds none of the toolkit's (native_parts), and the notices read only the program's crates; its defines say which it carries (FONT_NATIVE_LINK=false, MERMAID_NATIVE_LINK=false...) |
systems | the systems it is built for, a Systems (bit_set of runtime.Odin_OS_Type; {}: SYSTEMS_DEFAULT, Windows, Linux and macOS): its check checks each other one |
works | what else it links or embeds, for its notices: Project_Works (Third-party notices, below) |
title, description, publisher, copyright, icon | what Windows shows of it: its resource (above) |
A program's tool keeps its Project in a package variable (PROJECT := toolbox.Project{...}), not a constant
(PROJECT :: toolbox.Project{...}): a constant composite is made anew at each use, its lists (crates, works,
defines) on the stack of the procedure that uses it, and they dangle once that procedure returns (build_options
returned, then check read freed lists and crashed).
project_systems(p)issystems, elseSYSTEMS_DEFAULT.version_of(source, line)is the version in quotes afterline("": no such line);version_set(source, line, version)is the source with it replaced (ok = false: no such line).project_version(p)reads it fromversion_file.toolkit_dir(p)is the toolkit's checkout.project_aumid(p)is the AppUserModelID of the program's windows, never written:publisherandtitle("":name) in PascalCase of ASCII letters and digits, joined by a dot (platform.app_user_model_id:Froment Softwareandopencode nativegiveFromentSoftware.OpencodeNative).desktop.Identityderives the same from itsvendorand itsname, so the windows group with the shortcuts in the taskbar. Nopublisher:"", no id (the taskbar groups by the executable).odin_command(p, verb, pkg = "", extra = nil, release = false)builds the project's command line with collections, feature defines,defines, on Windowswindows_flags, on Linuxlinux_defines, the linker flag (linker_flag), thenextra.pkg"": the program's.release: the command of a release build.linker_flag(p, target, verb, release)is the one-extra-linker-flagsof a command fortarget("": none). Only one such flag is kept, so every source goes in this one: on LinuxLINUX_LINK(--allow-multiple-definitionfor duplicate Rust standard library symbols and--gc-sectionsso unused crates in prebuiltlibtrame_native.aare stripped;LINUX_LINK_FLAGis its flag alone) and, in a release withlink.strip,-s; on WindowsWINDOWS_LOAD_SYSTEM32(/DEPENDENTLOADFLAG:0x800, resolving static imports from System32 only) forbuild(nottest, so tests beside WARP'sd3d10warp.dllstill load it),WINDOWS_STATIC_VCRUNTIMEwithlink.static_vcruntime, andWINDOWS_FORCE_MULTIPLEwithlink.force_multiple.checkgets none.vt_dedup(p): on Windows, for a program withVt, writes a copy of each of its Rust static libraries without thecompiler_builtins-*members that define a builtin libghostty-vt'scompiler_rtdefines too. LLVM writes these builtins as weak externals in COFF, which radlink (Error 024) and link.exe (LNK1227) refuse twice,/FORCE:MULTIPLEor not. The libraries (vt_dedup_libs(p, target)): the program'slink.rust_libswithnative_carried, else the toolkit'sbuild/native/trame_native.libwhen it links a Rust part. The original is never written. The copy is the program'sbuild/vt_dedup/<name>.lib(vt_dedup_copy(lib)), beside<name>.stamp: the SHA-256 ofVT_DEDUP_VERSION, the Rust library and libghostty-vt. With the same stamp nothing is written; else the copy is written to a sibling temp file and renamed.program_prepareruns it after the program'sprepare(which builds a carried library); a tool with its own build command calls it after building its Rust library, and addswindows_flags.The link names the copy:
windows_flagsaddsvt_dedup_flags(p, target),-collection:trame_vt_dedup=<absolute build/vt_dedup>and, for each copy made,-define:<STEM>_LIB=trame_vt_dedup:<name>.lib(vt_dedup_define(lib):TRAME_NATIVE_LIB,TOWER_NATIVE_LIB). The toolkit's foreign imports oftrame_native.libreadTRAME_NATIVE_LIB. A program's own library inlink.rust_libsmust read its define the same way, with the original's relative path as its default:FormulaTOWER_NATIVE_LIB :: #config(TOWER_NATIVE_LIB, "../build/native/tower_native.lib") foreign import tower_native { TOWER_NATIVE_LIB, "system:ntdll.lib" }An executable that links a copy links
trame:vttoo: the builtins are only there. The thumbnail provider gets nowindows_flagsand links the original. Its parts, for a tool of its own:coff_dedup_file(rust_lib, vt_lib, copy) -> (removed, written, why),coff_overlapping_builtins(rust, vt)(the rule),coff_archive_without(data, members)(the archive written again, both linker members, withoutlib.exe, on any system),coff_archive_symbols(data).windows_flags(p, linked)is whatbuild_windowsmade, for a Windows build command: the console launcher (-define:GT_CONSOLE_LAUNCHER=<file>andGT_CONSOLE_LAUNCHER_MARK: trame:desktop embeds it and writes it with the PATH entry), the thumbnail provider withthumbnailer(-define:GT_THUMBNAIL_DLL=<file>: trame:desktop embeds it and writes it with the Thumbnails part),-define:GT_AUMID=<project_aumid(p)>(trame:platform declares it before the first window) and, whenlinked, the resource. A file not made yet is left out: a check from Linux builds without them. A tool that builds the program with its own build command (opencode native's) runsbuild_windowsand appends these.build_native(p)builds what the program needs before compiling: on Windowsbuild_windows(p)(the resource and the console launcher), then the toolkit's native library withnative_parts(p, target.OS)(trame build_native -features:...), by the toolkit's own tool in the project's checkout of it (nothing when the library is up to date or there is no part), the Lucide subset withLucide_Subset(lucide_subset, lucide.md), and last, on Windows, the thumbnail provider (build_thumbnailer(p, release)).build_native(p, release = true): what it builds is optimised too (program_buildpasses it for a release). To avoid rebuilding Rust in downstream CI and dev builds,trame build_nativeresolves the library in order: (1)TRAME_NATIVE_PREBUILT(a Nix store path such asgui_toolkit.packages.x86_64-linux.native) when itsSTAMPmatchesnative/, (2) existingbuild/native/when itsSTAMPmatches, (3) the prebuilt GitHub Release archivetrame-native-<os>-x64.<ext>for the checkout'sui.VERSIONafter verifying.sha256and the extractedSTAMP(skipped whenTRAME_NATIVE_BUILD_LOCAL=1is set), and (4) localcargo build(-profile:ciwithout fat LTO whenrelease = false, full release fat LTO whenrelease = true; see src/md/infrastructure/native-library.md).native_parts(p, target)is the parts of the toolkit's native library a program built fortargetlinks:textoff Windows, or withNative_Text;a11yon Windows withAccessibility;mermaidwithMermaid;webpwithWebp;pdfwithPdf;vtwithVt. None of the Rust ones withnative_carried: the program's own Rust library carries them, andbuild_nativemakes only the resource, the launcher, the Lucide subset andvt.thumbnailer_path(p)is the provider,<name>_thumbnails.dllbesideprogram(the name trame:desktop gives it beside the installed executable).thumbnailer_command(p, release)builds<thumbnailer>as a DLL with the collections and the features' defines, optimized for a release, else unoptimized with debug info; notwindows_flags: the DLL embeds nothing.build_thumbnailerruns it each time (it imports the program's renderer and the toolkit: a stamp of its own sources would miss a change). Elsewhere it does nothing: Linux's file managers run the program itself.check_windows(p)also checks the provider's package for Windows (-no-entry-point).
Features
A program declares once what it takes of the toolkit beyond its core: Project.features, a Features
(bit_set[Feature]). The defines (feature_defines(features, target, lucide)), the native builds (build_native) and
the crates of the notices (native_crates(features)) follow from it. What each one gives (sizes: builds.md):
Feature | Define | Native build | Crates of the notices |
|---|---|---|---|
Native_Text | Windows: FONT_BACKEND=native (the default elsewhere) | trame build_native, part text (Linux: always) | native/text (always) |
Accessibility | Windows: A11Y_ACCESSKIT=true | Windows: trame build_native, part a11y | native/a11y |
Mermaid | trame build_native, part mermaid | native/mermaid | |
Devtools | TRAME_DEVTOOLS=true: the CDP endpoint in a release build (devtools.md) | ||
Lucide_Subset | LUCIDE_SUBSET=<path>, once the file is made, but for check | lucide_subset(p) | |
No_Fallback_Fonts | FONT_EMBED_FALLBACK=false | ||
Webp | IMAGE_WEBP=true | trame build_native, part webp: libwebp inside the program, every system | native/webp (libwebp, BSD) |
Vt | GT_VT=true | trame build_native, part vt: libghostty-vt, a Zig library of its own beside trame_native (vt.md); Windows: vt_dedup strips the Rust library's builtins that libghostty-vt defines | none: libghostty-vt (MIT) as a work |
p := toolbox.Project{name = "classeur", src = "src", program = "build/classeur", features = {.Mermaid, .Lucide_Subset},
title = "Classeur", description = "A fast file manager.", publisher = "Froment Software"}
if !toolbox.build_native(p) { return "the native parts failed" }
if !toolbox.run(toolbox.odin_command(p, "build", extra = {"-o:speed", "-out:build/classeur"})) { return "the build failed" }A program's build, test and check
build_commands(o: Build_Options) -> [3]Command are a program's build [release|debug], test [names] and check, the same
steps in every program (the intent). Build_Options is the Project
(using project) and what the program adds:
| Field | What it is |
|---|---|
changelog_command | the project's changelog.command(project): check runs its check (the fragments and the roadmap) |
tests | the Test_Packages (path, one_thread: its tests one after the other, each said as it starts); nil: the program's package |
tool | the tool's package ("": tools/<name>tool): checked with -vet; in tests, tested with no native library |
catalogues | an I18n_Catalogues (folder "": none): every <folder>/<language>.txt checked against the code |
notices | THIRD-PARTY-NOTICES checked up to date |
prepare | proc(p: Project) -> bool, after build_native, before a build or test: what the program builds itself |
checks | []Build_Check (proc(p: Project) -> bool): the program's own checks, each says why it fails |
iterate | the Build_Mode of build with no word: Debug (the default) or Dev |
fresh | built into <dir>/<name>-new, then swapped in: a running program's file is never written (Windows refuses it) |
pinned_odin | compiler version pin file (ODIN_PIN_FILE); GT_ANY_ODIN=1 builds anyway |
Its slices must outlive the tool's commands: package arrays (@(rodata) TESTS := [?]toolbox.Test_Package{...}), not a
literal in the procedure that makes the options.
A Build_Mode is how the program is compiled:
Build_Mode | Flags | What for |
|---|---|---|
Debug | unoptimized with debug info, a console on Windows | the fastest build, its debug information |
Dev | minimal optimization, /SUBSYSTEM:WINDOWS | fast incremental iteration |
Release | --release, /SUBSYSTEM:WINDOWS, link.strip | what ships, what alone is measured for speed |
program_build(o, release = false, debug = false) -> bool: checks the compiler pin whenpinned_odinis set, thenbuild_native,prepare, then the program atProject.programin its mode (Release,Debug, elseiterate). Withfresh, the build goes to<dir>/<name>-new; the program moves to<name>-old(Windows lets a running executable be renamed, not written), the fresh file takes its place, and<name>-oldis removed when nothing runs it. Every build writes its mode beside the program,<program>.mode(MODE_SUFFIX).build_mode_of(program) -> (mode, known): the mode the program was built in, from its mode file (known = false: built otherwise). A tool's package command refuses what is not aRelease; a measure of speed reads only one.odin_pin_says(pinned, found) -> string:""whenfound(the compiler's printed version) holdspinned, else why.program_test(o, names = "") -> bool: each test package tobuild/test_<path>;names(pkg.test_a,pkg.test_b): those tests of the program's package alone, in that order, on one thread.program_check(o) -> bool: the steps ofcheck_steps(o, target.OS)in the order ofCheck_Step:Changelog,Scopes,Checks,Catalogues,Notices,Flake_Toolkit(below),Odin_Check,Check_WindowsandCheck_Darwin(from another system, whenproject_systemsholds it),Tool,Tests,Release_Build,Launcher(Windows). The first that fails ends it.
The flake's toolkit
nix run github:owner/program fetches the program as a tarball: a tarball holds no submodule, whatever
inputs.self.submodules says, and ext/gui_toolkit is empty. The package of a program's flake therefore takes the
toolkit from an input, pinned to the submodule's commit:
inputs.gui_toolkit = {
url = "github:sachahjkl/gui_toolkit/<the submodule's commit>";
flake = false;
};
# in the package: the program's tree without ext/gui_toolkit, the input copied there
postUnpack = ''
cp -r ${gui_toolkit} $sourceRoot/ext/gui_toolkit
chmod -R u+w $sourceRoot/ext/gui_toolkit
'';
cargoDeps = pkgs.rustPlatform.importCargoLock {lockFile = "${gui_toolkit}/native/trame/Cargo.lock";};The commit is then said twice. Flake_Toolkit holds them equal: flake.lock's nodes.gui_toolkit.locked.rev must be
the commit checked out in the toolkit's folder (toolkit_dir), else the check says which url to set. A bump of the
submodule sets the input's url too, then nix flake lock. A program whose flake.lock has no gui_toolkit node, or a
tool pointed at another checkout ($TRAME), passes.
flake_toolkit_pin(lock_text) -> (rev, ok): the commitflake.lockpins the toolkit to.checkout_head(dir) -> (rev, ok): the commit checked out in a git checkout, a submodule's included (its.gitfile, its HEAD, a branch in its refs orpacked-refs). Files only: no git process.flake_toolkit_says(pin, head) -> string:""when they agree, else why and what to do.flake_toolkit_check(p, root = ".") -> bool: the step.
A tool's other commands call them (live builds with program_build(build_options())), and release.commands takes
the check: check = proc() -> cli.Exit { return toolbox.ended(toolbox.program_check(build_options())) }.
@(rodata) TESTS := [?]toolbox.Test_Package{{path = "src", one_thread = true}} // (and a package of its own: {path = "src/<name>"})
@(rodata) CHECKS := [?]toolbox.Build_Check{check_systems}
build_options :: proc() -> toolbox.Build_Options {
p := project()
return {project = p, changelog_command = changelog.command(p), tests = TESTS[:], catalogues = I18N, checks = CHECKS[:]}
}
b := toolbox.build_commands(build_options()) // b[0], b[1], b[2]: build, test, checkFont subsets
font_subset(data, codes, allocator) is a TrueType font (glyf outlines) with only the glyphs of the characters codes
(those the font has), .notdef, and the glyphs a kept composite glyph is made of. The outlines and advances are the
original's; the glyphs are numbered anew in their old order, the character map holds only codes (format 4, or 12 past
the BMP), post has no glyph names, and only OS/2, cmap, glyf, head, hhea, hmtx, loca, maxp, name and
post are kept (no ligatures, kerning or hinting). why: the font cannot be read (CFF outlines, a collection).
sfnt_tables(data), sfnt_table(tables, tag), sfnt_cmap(cmap) and sfnt_glyph(glyf, loca, long, gid) read a font's
tables, its character map and a glyph's bytes.
lucide_subset(p) writes the program's icons of the Lucide font at LUCIDE_SUBSET_FILE (build/lucide_subset.ttf, in
the working directory) and returns its absolute path; lucide_names_used(dirs) and lucide_codes(source, names) are its
steps (lucide.md).
- Every program with a window has a console launcher on Windows:
launcher_path(p),<name>.combesideprogram.build_launcher(p)(inbuild_windows) builds it from the toolkit'stools/console_launcher, with the marklauncher_mark(p)((<name> console launcher): installed launchers carry it) and theLauncher's rules:default_rule(waitordetach;"":detach) andothers("":LAUNCHER_OTHERS_DEFAULT, the help and the version). The program embeds it with no code of its own (windows_flags), and the release's archive has it beside the program (trame:release).check_launcher(p)checks a release build: it carries its icon,<launcher> versionsays<name> <version>, and withrefuses_exit, an unknown command ends with that code. check_windows(p)andcheck_darwin(p)run cross-target checks of the program for Windows (windows_amd64) and macOS (darwin_arm64), from any system (odin_check).
Builds made once
A build that is slow makes its output once: a stamp beside it holds the hash of what it is made from.
stamp_holds(output, stamp, expected) is true when the output is there and the stamp says expected (its line end aside).
write_stamp(path, text) writes one, with this system's line end (STAMP_NEWLINE).
write_if_changed(path, text) -> bool is the one writer of a generated file (a stamp too): it makes the file's folder and
writes nothing when the file holds the text already, so what is built from it keeps its time.
build_c_lib(name, sources, out, cflags) builds <out>/lib<name>.a from sources: each .c file compiled by cc with
cflags, then ar; another file (a header) is hashed only. It does nothing when <out>/STAMP says these sources and flags
(c_lib_stamp(sources, cflags): the SHA-256 of each source and of the flags). For a C library a program builds itself
(papier's SQLite), on Linux and macOS.
A check of the scopes
A scope is a procedure with a deferred end (@(deferred_out = section_end), deferred_none, deferred_in...):
ui.row, ui.parent, ui.menu, debug.section, a program's own. It ends with the statement that opens it:
if !debug.section("x") { continue } closes the section at the end of the if, and the values after it are outside
it. if ui.menu("m") == false { return } is the same trap. The compiler accepts both. The right forms:
if debug.section("Transform") { ... } // the scope's content in the block
open := ui.menu("m") // or the call as a statement: the scope ends with the block that holds it
if !open { return }check_scopes(src_dir, toolkit_dir = TOOLKIT_SRC_DEFAULT) says each misuse in the .fm files under src_dir, with its
file, its line and the right form, and is true when there is none. It is the Scopes step of program_check. The
scopes are read from the sources of the toolkit's packages and of the program (scope_names(sources)), so a new
scope is checked at once. A call pkg.name(...) is checked against every scope's name; a call name(...) only
against its own package's. scope_misuses(text, local, qualified) is the check of one file's text. The toolkit runs
it on its own sources in the toolbox's tests.
Third-party notices
third_party_notices(p, out, check_only = false) writes the licences of what the project's executable holds besides its
own code at out (NOTICES_FILE, THIRD-PARTY-NOTICES), or with check_only says whether out is up to date. It returns
"" when all is well, else why not:
- Trame (MIT) and its attributions (
NOTICE.md), Roboto, Paper Mono and Lucide's icons, from the toolkit's checkout; - Formula's standard library licence;
- the toolkit's works of the project's features that are not crates (
FEATURE_NOTICES): libghostty-vt (MIT) withVt; - the program's works (
p.works), in their order; - the Rust crates of the project's features (
native_crates(p.features)) and of its own libraries (p.crates):cargo metadataof each (--locked, forNOTICES_TARGETS: Linux and Windows together), the crates the library links (notices_crates(metadata, given): the normal dependencies from its package, crate after crate; never a build script's, a test's or a procedural macro; a path crate is walked but not listed), each with its licence files (LICENSE*,LICENCE*,COPYING*,NOTICE*, and its manifest'slicense-file). A crate two libraries link is listed once. A crate with no licence file is an error.
A program states what the toolkit does not know: its own Rust libraries in crates, the rest in works. A
Project_Work has name, licence (an SPDX id) and one of file (the licence's file, relative to the project's root)
and text. A work with neither or both is an error. A work with crate (a crate's name) is that crate's licence when
its package ships no licence file (webview2-com's repository has one, its package none): it is listed with the crates,
not as a work. The error for crates with no licence names them all at once.
p := toolbox.Project{name = "sample", features = {.Mermaid, .Webp},
crates = {"rust/core/Cargo.toml"},
works = {{name = "libghostty-vt", licence = "MIT", file = "vendor/ghostty/LICENSE"}}}One file covers Linux and Windows: it goes beside each build, and its check says the same on each system. A Linux
archive lists a Windows-only crate too. cargo metadata is not offline: a build fetches only its own target's crates,
and the check fetches the other target's once. Why: src/md/features/third-party-notices.md.
notices_text(p, works, crates, libraries) is the file: the list, then each work's texts, then each crate's text once with
the crates that ship it (libraries: the native libraries as the list names them, Trame's native/text). notices_command(p) is the notices [--check] command of a project's tool.