Direct to write, retained to run
Direct to write, retained to run
I’ve been building a text editor called Scratchpad. File tree, tabs, search, a couple of panes. Pretty neat, nothing you haven’t heard before. I will say however, to make all of it work together a Goliath undertaking that I underestimated. Keep a search result visible after the document changes, preserve focus when tabs move, handle text input, and avoid rebuilding the editor because someone hovered over a toolbar.
The reason why i started Scratchpad is to actually test my more interesting project: Alicorn is the experimental GUI runtime I’ve been developing alongside it. You describe an interface in ordinary Odin code, and Alicorn keeps the information needed to operate it between descriptions. The application keeps its own data. The runtime keeps identity, interaction state, layout, text, and rendering products.
The idea is simple enough to write in one line: direct to write, retained to run. Explaining exactly what survives, who owns it, and when it becomes invalid takes a little longer.
In v0.2.0, Alicorn adds alicorn:ui as a simpler front door for ordinary application code. The point is to make a small native app easier to write without hiding the retained runtime or moving application state into a framework-owned store.
Start with a button
Say we’re making a counter. Our application owns one integer:
App :: struct {
count: int,
}
We want a label showing the count and a button that increments it. In a conventional retained GUI, we’d create persistent controls, attach a handler, and update the label when the value changes. The framework keeps those controls around.
An immediate-mode API lets us express the interaction directly. In Dear ImGui, that looks like this:
ImGui::Text("Count: %d", count);
if (ImGui::Button("Increment")) {
count++;
}
I like this shape. The click and its consequence are next to each other. Conditional UI is an if statement. A list is a loop. I can read what the application does without following a handler into another object.
There’s a distinction here that’s easy to lose. Immediate mode describes the interface between the application and the library. It doesn’t forbid internal state, caching, or sleeping when idle. Dear ImGui keeps internal state, and its own explanation of the paradigm explicitly rejects the idea that IMGUI requires continuous refresh or all-or-nothing updates.
So retaining things isn’t an invention Alicorn adds to immediate mode. I’m choosing a particular set of things to retain, with an explicit update contract, for native desktop tools.
Alicorn’s beginner path has the same shape, in Odin:
import "core:fmt"
import ui "alicorn:ui"
App :: struct { count: int }
render :: proc(app: ^App, ctx: ^ui.UI) {
if ui.column(ctx, padding=24, gap=12) {
ui.text(ctx, fmt.tprintf("Count: %d", app.count))
if ui.button(ctx, "Increment") {
app.count += 1
}
}
}
main :: proc() {
app := App{}
ui.run(&app, render, title="Counter", width=720, height=480)
}
ui.run supplies the routine single-window host and frame lifecycle. The
render procedure receives typed, application-owned state and the same UI
description context used by the lower-level runtime. The helpers emit ordinary
retained nodes; they don’t add a second widget tree or a state store. v0.2.0
also adds controlled text fields, checkboxes, sliders, icon controls, virtual
lists, typed worker lifecycle hooks, and semantic defaults for informational
text to this package.
For example, ordinary form values stay in the app while the helpers handle their UI interaction:
import ui "alicorn:ui"
App :: struct {
name: ui.Text_Buffer,
show_grid: bool,
gain: f32,
}
render :: proc(app: ^App, ctx: ^ui.UI) {
if ui.column(ctx, padding=24, gap=12) {
ui.text_field(ctx, "Name", &app.name)
ui.checkbox(ctx, "Show grid", &app.show_grid)
ui.slider_f32(ctx, "Gain", &app.gain, 0, 1, step=0.05)
}
}
main :: proc() {
name, ok := ui.text_buffer("Alicorn")
if !ok { return }
app := App{name=name, show_grid=true, gain=0.65}
defer ui.text_buffer_destroy(&app.name)
ui.run(&app, render, title="Form", width=560, height=460)
}
The buffer owns editable text for the app’s lifetime, so it has an explicit
creation and destruction step. The checkbox and slider take pointers to
application-owned values and adopt user changes there. That’s less plumbing
for a normal form; it isn’t a hidden reactive store. ui.text_field also
provides its visible label as the field’s semantic name. Informational
ui.text is semantic by default; decorative=true opts visual-only text out.
host.Run remains available when an app needs more direct native callbacks,
runtime initialization, or services. Both paths can mix convenience helpers
and lower-level calls through the same context. The
native starter
is the canonical minimal example.
The convenience layer is progressive, not an all-or-nothing wrapper. ui.row,
ui.column, ui.panel, and ui.layout cover common and exact layout scopes;
ui.text and ui.button forward typed runtime styling options, and a button
can specify a semantic variant or direct dimensions. A scoped call such as
if ui.column(ctx) { ... } uses ordinary Odin control flow; the scope closes
when the block exits, including an early return, break, or continue.
Runtime controls that don’t have a convenience wrapper can still use ctx in
the same description.
The calls submit descriptions. Behind ui.run, Alicorn reconciles them with
the interface it already has: matching existing elements, updating changed
properties, creating new elements, and retiring elements that disappeared.
Reconciliation is just that comparison and update step.
A button can keep its identity and focus through another description. An unchanged string can keep its shaped text. We execute ordinary procedures without asking the application to maintain a second permanent hierarchy of widget objects.
Follow one click all the way through
The label appears before the button. On the pass that consumes a click, it
initially describes the old count before count += 1 happens. ui.run selects
Alicorn’s bounded .Correct_After_Interaction policy, so the host describes
the updated state before presenting the frame. The activation is consumed only
once; a correction doesn’t increment the counter again.
This is a convenience of ui.run, not a claim that the runtime watches
application memory. The Application passed to host.Run defaults to
.Explicit: the application invalidates after changes it owns. It can instead
select the same corrective policy for consumed widget activations and
controlled-value changes. Neither route discovers arbitrary writes or fixes a
region revision the application forgot to advance. The corrective loop is
bounded, so rendering descriptions should stay free of unrelated side effects.
That sequence matters because a UI description can run more than once before presentation, or skip running altogether. Work placed unconditionally in the render/build procedure follows that schedule too. I wouldn’t put a database write or an expensive directory scan there and assume it runs once per click. The guarded button action consumes an event; the surrounding code describes the current state.
Moving the pointer over the button is a smaller change. Alicorn already has its bounds and can determine which retained control is under the pointer. Updating hover paint doesn’t inherently need the application to describe the counter again.
With no input, pending work, or scheduled deadline, the host can wait for an event. It doesn’t need to keep calling the description at display refresh rate. Animations, caret blinking, and live graphs still need updates when they’re active; their deadlines are reasons to wake.
This gives us three separate schedules: when application code describes the
UI, when retained results need recomputing, and when the host presents an
image. The lower-level API still calls its description entry point
begin_frame, but a description and a displayed frame aren’t interchangeable.
The update contract
Suppose a file finishes loading on a worker. The worker produces an owned result and wakes the host. On the UI thread, the application accepts that result, updates its data, and requests the UI work it needs. Since v0.2.0, this ordinary lifecycle can stay on the ui.run path:
ui.run(&app, render, title="Search",
on_start=start_worker,
on_wake=adopt_worker_result,
on_stop=stop_worker,
)
The application still decides whether the result is relevant. If an old search finishes after a newer one, delivering it safely doesn’t make it the right answer to display. Request generations and stale-result rejection belong with the application that knows which search is current. ui.wake only asks the host to deliver an event; it neither publishes nor synchronizes the result. The worker and application still need a mutex, channel, or other synchronization for the data itself.
on_wake runs on the application thread. It reads the synchronized result, decides whether to adopt it, and calls ui.invalidate(ctx, reason) if the description needs to change. on_stop must stop and join producers before returning, because the waker is borrowed host state and expires after shutdown. See the async-list example for the complete ownership path.
On the lower-level .Explicit path, that last step is explicit. Inside the
host.Run build callback, rt is the runtime pointer:
import alicorn "alicorn:runtime"
app.count += 1
alicorn.invalidate_root(rt, "counter changed")
count += 1 is an ordinary write to an Odin struct. Alicorn doesn’t watch the address, intercept assignments, or discover dependencies by inspecting application memory. The invalidation says that the retained description may now be out of date.
ui.run handles both parts without observing arbitrary app memory: it
corrects descriptions after consumed widget actions, and its worker hooks let
the app adopt asynchronous results and explicitly invalidate. Use host.Run
when the application needs lower-level native services or callbacks. Neither
path discovers an unrelated write just because it can see a pointer to the
application struct.
That keeps the data model under the application’s control. It also means forgetting the invalidation can leave stale UI. I don’t get to call that a performance optimization when it’s actually a bug.
There are two different jobs hidden in the word “update.” One is finding out what the application now wants to display. The other is making the existing description work under changed conditions. A window resize can require new layout without changing which controls exist. A hover can require new paint without changing layout. A changed label may affect both text measurement and its parent’s geometry.
Alicorn tracks description, reconciliation, layout, paint, and presentation work separately. It can retain the valid parts and run the stages affected by a change. That doesn’t promise a repaint of only one tiny screen rectangle: avoiding description or text shaping and avoiding a GPU submission are different savings.
For a more expensive subtree, the application can supply a region with its own revision: a version number it advances when that region’s output changes. Imagine a sidebar beside an editor. Selecting a sidebar row changes the application, but the editor’s logical content may be unchanged. During the next root description, Alicorn can reuse that region’s retained subtree if its revision still matches. The app skips emitting its descendants again.
The application has to include every relevant input in that decision. If the editor’s output depends on document contents, selection, and display options, changing any of those may require advancing its revision. Updating the document revision while forgetting an app-owned option is enough to produce a stale region.
The runtime can reject revisions that go backwards and invalidations for unknown region keys. It cannot prove that every unchanged revision tells the truth. Optional mutation diagnostics help check changes the application explicitly reports; they don’t make arbitrary memory observable.
Region reuse also doesn’t freeze geometry. If its parent assigns a different width, retained children may still need layout and text reflow. Skipping the application’s description answers one question. Reusing an old measurement under new constraints answers another, and sometimes the answer is no.
Layout changes can also spread beyond the element that started them. A label that grows taller can enlarge a container and move its siblings. Alicorn’s layout boundaries let an application contain that work along dimensions whose outer size is stable. A fixed-size panel can relayout its contents locally; a content-sized panel can’t promise that its height is unaffected. A region revision and a layout boundary make different promises, so neither substitutes for the other.
Identity comes before reuse
Alicorn needs to know which previous element a new description refers to. Otherwise it has no reliable place to attach focus, scrolling, or cached work.
Consider three document tabs:
README.md
notes.txt
ideas.md
Move notes.txt to the front. The item at index zero changed, but the document didn’t. A tab’s current position is a bad identity if we expect its state to follow it through a reorder. Its visible filename is also insufficient if two documents can have the same name.
Alicorn combines the structural call site with scoped identity and application-supplied keys. Odin’s #caller_location gives a procedure access to where it was called. That identifies a declaration in the code. Repeated items at that declaration need a logical key:
for item in app.items {
if ui.button(ctx, item.name, key=ui.key_u64(item.id)) {
app.selected_id = item.id
}
}
For a single control, the convenience helper accepts the item’s stable key directly. The button call can be the same line of code for every row because the logical key supplies the identity that the shared call site lacks. Reordering the collection preserves that association. For a multi-node item, an explicit component scope can give the whole subtree one keyed identity. Duplicate keys are reported instead of guessed around.
Reusable procedures need to respect this too. Wrapping a widget doesn’t automatically make every invocation a distinct logical instance; the wrapper needs appropriate scoping or call-site forwarding. The source location helps locate a declaration, while the key distinguishes the data represented there.
Once an element is omitted from a fresh description, its retained lifetime can end. A reused region is different: it explicitly preserves an existing subtree without describing every child again. Skipping arbitrary widget calls and declaring a subtree reusable aren’t equivalent operations.
Runtime node IDs are also a poor persistence format. They’re useful while that runtime exists, but application session files should store document IDs, workspace-relative paths, and other identities the app understands. A source edit or another process launch shouldn’t redefine which document the user meant.
Scratchpad made this fairly concrete. Restoring tree focus and scroll once per frontend runtime was insufficient because a user can switch workspaces without restarting it. Two workspaces can contain the same relative paths. The application has to decide which workspace those paths belong to and when restoration applies; Alicorn can supply retained-state queries and restoration hooks, but it can’t infer that policy from a node ID.
What the runtime keeps
Alicorn has a retained tree. Avoiding an application-owned widget tree doesn’t make the runtime’s tree disappear.
The application owns documents, files, sampled process data, filters, and commands. The runtime owns the UI machinery derived from those things: the focused control, a scroll offset, resolved bounds, shaped text, paint products, and resource metadata. The native host owns windows, platform events, GPU submission, and the resources tied to that native device.
Some data necessarily crosses those boundaries. A label’s bytes have to survive long enough to be rendered, for example. The useful ownership claim is that Alicorn doesn’t become the authority for the document just because it retains text describing part of it.
Text makes the cost of this distinction obvious. Shaping turns characters into positioned glyphs, the shapes a font uses to draw the text, accounting for the font and the script being displayed. Measuring wrapped text also depends on available width. A string can be byte-for-byte unchanged and still need different line breaks after a pane narrows.
Runa provides Alicorn’s text shaping and rasterization. Alicorn retains the resulting products and invalidates them when their relevant inputs change. Moving over the toolbar doesn’t by itself change the editor’s text or font, so repeating that work would need another reason.
Retained memory has a price, though. Nodes, cached text, lookup tables, and resources all occupy space, and their lifetimes need cleanup. Virtualization is how a large collection avoids making that price proportional to every logical item. A list can describe a visible range and a small surrounding buffer while leaving the million underlying records in application storage.
That bounds the UI’s realized working set. It doesn’t make an application’s sorting, filtering, or data loading constant-time. Monitor exposed this distinction: recomputing a filtered, insertion-sorted process list on each root build became expensive when the Mac supplied many more processes. Retaining the row UI couldn’t repair unnecessary work in the application’s projection.
Why Odin fits this
I want an Odin GUI library whose application code feels like Odin. A reusable component is a procedure; data can stay in normal structs, slices, and maps. The language’s allocators and scoped context make temporary and persistent storage explicit, and native interoperability keeps the host boundary accessible.
Those properties suit this particular runtime. They don’t choose the caching policy, enforce the revision contract, or make a bad layout algorithm fast.
The counter’s fmt.tprintf is a useful example. It formats text into temporary storage. A runtime that kept that pointer indefinitely would eventually read invalid or overwritten bytes. Alicorn’s reconciliation copies text that needs to survive into runtime-owned storage. Short-lived description work uses scratch storage; retained data uses storage with a longer lifetime. Retirement and destruction have to release the corresponding owned data.
A slice is also a view into memory, not a lifetime guarantee. Passing one to a procedure doesn’t necessarily allocate, but retaining it still requires an ownership decision. The same question applies to geometry, image descriptors, and worker results.
This is the part of manual memory management I care about here: I can ask which allocator paid for a result, how long it must live, and whether a repeated update allocated anything. The mistakes are still mine to make. Odin gives me ways to inspect them.
From descriptions to pixels
The ordinary path looks like this:
Application data
|
| explicit invalidation
v
Odin UI description
|
v
Identity matching and reconciliation
|
v
Layout and text measurement
|
v
Paint products and composition
|
v
Native host / SDL_GPU
|
v
Presented image
The runtime matches identities before deciding which products remain usable. Layout resolves bounds under the current constraints. Paint resolves the visual representation, and composition puts the resulting primitives in order. The SDL_GPU host handles native submission; the application’s widget code doesn’t receive a GPU command buffer.
On Windows that host uses Direct3D 12, and on macOS it uses Metal. “Native” here includes the window and platform integration; the ordinary controls are drawn by Alicorn. It doesn’t mean every button is an AppKit or Win32 widget.
Some updates enter further down this path. A graph can replace the payload of an already-retained GPU surface without describing the surrounding panels again. Hover can update retained presentation. Changed pane bounds can trigger retained layout. The runtime needs those paths to agree about identity and lifetime even when the full description path doesn’t run.
One early surface bug came from giving two different changes the same revision. The description revision and the graph’s live payload revision both advanced together. Reconciliation treated the changed description as a reason to replace the surface, clearing the payload. Clicking could make the graph blink.
The correction separated those responsibilities. Declaring the surface establishes it; updating its geometry replaces an owned payload with its own internal versioning. An unrelated description shouldn’t erase the last valid graph. Surfaces are also noninteractive unless the app opts in, so displaying a graph doesn’t quietly make it behave like a button.
The procedural API is the small visible part. Most of the runtime work is making these lifetimes and partial-update paths agree.
What real applications broke
The apps have been more useful than a widget gallery for finding the places where the model was incomplete.
Monitor’s process list once had an unreachable bottom. The app estimated its viewport with arithmetic like logical_height - 340. That estimate didn’t match the space actually left by the graph, filter, controls, and table header. The scrollbar and virtualization calculations could agree perfectly and still use the wrong height.
The fix was to make the resolved layout rectangle authoritative for the viewport. Row realization, scroll clamping, clipping, and scrollbar geometry need to use the same bounds. Asking every application to maintain a second approximation of layout is a fairly silly way to keep the framework “explicit.”
Scope found another case. A workspace scrollbar painted over the command palette even though input correctly treated the palette as being on top. Scrollbars were being appended in a final global pass, so their visual order no longer matched the retained hierarchy.
Painting each scroll region’s scrollbar after its own content, before later overlays, restored the intended order. The tree already contained enough information. The compositor had thrown it away.
History exercises asynchronous Git work and scrolling diffs. Monitor exercises live samples, virtual rows, and a graph. Scope has a Go backend using Caliber, a separate experimental C application binary interface that lets the languages communicate. Scratchpad brings editing, IME text composition (such as entering Japanese characters), file operations, menus, persistence, fonts, and multiple windows. Different consumers make different assumptions fail.
On macOS, a graph whose label read about 17% could still draw near the top of the plot because line vertices missed the Retina scale conversion already applied to background quads. The data wasn’t the problem. A Windows run near 1× scale hadn’t exposed the mismatch.
These failures have more to do with ownership and geometry than with whether the API looks immediate or retained. They also keep the project honest: a green headless test can’t establish how a physical trackpad gesture, native dialog, or IME behaves.
Where the React comparison helps
If you come from React, describing an interface repeatedly while preserving its identity should be familiar. React associates component state with position, type, and keys. Its render and commit phases also separate calling components from changing the DOM. Calling a component again doesn’t imply replacing its DOM nodes.
That comparison is useful up to a point. React DOM commits into a browser, which handles layout, text, and drawing. Alicorn has to provide those native UI stages itself. In React, state setters and external-store subscriptions schedule work; in Alicorn, application writes need the explicit update contract described above.
Both can reuse work. React has memoization and React Compiler can automate some of that reuse; neither its model nor an immediate-mode API inherently requires wasteful continuous rendering. Alicorn’s particular choice is procedural Odin authoring, application-owned state, and retained execution with visible invalidation.
There is a reconciliation tree here, but no DOM underneath it. That gives an experienced web developer a useful point of reference without pretending the implementation problems are the same.
What the measurements actually say
I care about which work ran as much as how long it took. If a benchmark is supposed to reuse text but reshapes it every time, a tolerable frame time doesn’t establish that the reuse mechanism works.
The v0.2.0 final Windows performance report is more useful than a broad speed claim. It used three fresh processes on Windows 10 with a Ryzen 5 7600X and -o:speed for the matched retained-work comparison:
| Workload | Observed work |
|---|---|
| 10,000 idle frames after building a 10,001-node tree | Zero allocations, reconciliation, layout, paint/composition visits, or GPU submissions |
| 1,000,000-item virtual list over 100 frames | 8.325 ms median; 23 retained visual nodes |
| 1,200 custom-surface updates | Zero ordinary UI-stage work and zero allocations in the measured path |
| Reuse a retained 10,000-node subtree | 2.427 ms median |
Those are headless runtime workloads. The graph test still changes a surface payload; excluding ordinary retained stages doesn’t mean a native renderer could display those updates for free. The report also measures a 10,000-node root invalidation with one changed value at a 15.499 ms median. Its October 27 comparison run used the same runtime source, so lower October 28 medians describe run-to-run variation, not a new optimization. The report does not measure native startup, interactive frame latency, process memory, GPU residency, or macOS performance.
It still shows why “retained” needs an explanation. Invalidating the entire root and repeating its description can do substantial work. A region that avoids descending into an unchanged subtree is a different optimization, and the counters need to distinguish them. The separate native host report covers CPU and submission samples; none of these figures is a battery-life claim.
Where it stands
Alicorn is experimental and its API is still unstable. The widget set is still small. v0.2.0 includes an experimental AccessKit bridge, with maintainer-confirmed physical checks using Narrator/NVDA on Windows and VoiceOver on macOS. Those checks covered editable controls, modal boundaries, and bounded traversal within a virtualized million-row collection.
That is useful evidence, not comprehensive accessibility conformance. Exact reader versions and detailed action traces were not recorded, and Linux has no screen-reader adapter. The release also records physical input, IME, mixed-DPI, appearance, and window-lifecycle checks on Windows and macOS; those results apply to the tested environments, not every platform or device.
The design also draws on work I didn’t invent. Dear ImGui and egui inform the application-facing API; Shirei is a practical reference for direct GUI authoring; GPUI, Fenestra, Xilem, and Masonry have informed how I think about native runtimes and incremental work. Runa supplies the text system and grew out of work in Skald. Those are distinct influences and foundations, with different architectures of their own.
What I want now is for the next app to need less private glue. If Monitor and History both reconstruct the same scrolling rules, there’s probably a missing library facility. If only Scratchpad needs a document-specific policy, that can stay in Scratchpad. Making every snippet shorter isn’t enough reason to add another concept.