docs/design.md
sigil-ui design
sigil-ui is a retained-mode UI library for Sigil. A program describes what the screen should show as plain data; sigil-ui keeps the last description, works out what changed, and repaints only that. It renders in software onto a pixel canvas, which it shows through an offscreen buffer, a Linux fbdev framebuffer, a DRM dumb buffer or a Wayland surface.
This document covers the model, the choices behind it, and the measurement that decided how much of a view runs again on each change.
The pieces
| module | what it is |
|---|---|
(sigil ui color) | colors as 24-bit integers, rgb and hex |
(sigil ui raster) | the canvas: XRGB8888 pixels, clipped fills, blends, masks, bitmaps and copies in C |
(sigil ui font) | bitmap fonts and font sets (one font per integer scale, same logical advance) |
(sigil ui mask) | 8-bit alpha masks, 4-bit run-length decoding, mask sets per scale |
(sigil ui display) | the display list: fill, blend, text and mask items, rendering and clipped repaint |
(sigil ui theme) | names for colors, fonts and images |
(sigil ui tree) | elements, the retained tree, reconciliation, and the ui object |
(sigil ui surface) | offscreen, fbdev and DRM surfaces |
(sigil ui wayland) | a Wayland window or fullscreen surface, with keyboard and pointer input |
(sigil ui png) | PNG output for test renders |
The flow on every change:
state --view--> element tree --reconcile--> retained tree + damage
|
display list ------+--> repaint damage --> canvas --> surfaceUnits and scale
Everything above the canvas is in logical pixels. A ui has one integer scale s; a logical pixel is an s x s block of device pixels. Fonts and masks come in sets with one entry per scale, and a font set refuses fonts whose advance is not the same number of logical pixels at every scale, so layout never depends on the scale. There is no fractional scaling and no antialiasing beyond what a mask carries.
Elements
A view is an ordinary function from state to an element tree. Elements are lists, compared with equal?:
(rect x y w h color)
(blend-rect x y w h color alpha)
(label x y string color [font])
(runs x y ((string . color) ...) [font])
(image x y name color)
(group x y children)
(keyed key element)
(component fn arg)Colors are theme tokens ('fg1) or integers. Fonts and images are theme names. An element never holds an asset, so the same view renders under any theme that defines the names it uses, and comparing two elements is cheap.
Layout is explicit: a view computes positions itself. text-advance gives a string's logical width in a theme font, which is what centering and right-alignment need. A layout engine (rows, columns, constraints) can be built as functions that produce elements; it is not part of this version.
The retained tree and reconciliation
ui-update! takes the next element tree, reconciles it with the retained one and repaints the damage. The rules:
- Identity. A child is matched with an old sibling by its key if it has one (
keyed), otherwise by its position among its siblings. Kinds must match too: a group never turns into a leaf in place. Duplicate keys among siblings are an error. - Leaves. A leaf whose element and origin are unchanged keeps its display items and costs no repaint. If only its origin changed (a parent group moved), its items are moved, not rebuilt. Otherwise its items are built again, and both its old and new bounds are damaged.
- Components.
(component fn arg)runs(fn arg)to get its element. It is not run again whilefnis the same procedure (eq?) andargisequal?to the last one; its subtree is kept, or moved if its origin changed. - Removal and order. A removed child damages its old bounds. A keyed child that now comes before a sibling it used to follow damages its bounds, because paint order changed.
- Repaint. Damaged rectangles are merged where they touch, clipped to the screen, cleared to the ui's background and repainted from the whole display list, clipped to each rectangle.
The invariant is that after any update the canvas equals a fresh render of the latest tree. test/test-tree.sgl checks it after 40 random updates at scale 1 and 2, and it fails when either damage rule above is removed.
Keyed identity
Keys matter when children are inserted, removed or reordered. Matched by position, inserting one row at the top of a list makes every row differ from the row that used to be at its position, so everything is rebuilt. Matched by key, only the new row is built (the tests check both cases). Use a key that names the thing the row shows: a generation number, a service name, a log line's sequence number. Keys only need to be unique among siblings.
Re-run granularity: whole view, with components
The choice was between re-running the whole view on every change and reconciling, as above, or tracking dependencies with signals so that a change updates only the leaves that read it.
Decision: whole re-run with reconciliation, with components to skip subtrees whose input did not change. Signals are not part of sigil-ui.
The measurement, bench/ (run it with sigil build --config release and then build/release/bin/sigil-ui-bench). It builds natively at optimize 2, the way a shipping program is built, and runs on an AMD Ryzen 7 7840U at 1920x1080, scale 1, with a synthetic 8x16 font. Times are per update, the median of three runs:
| scenario | nodes | view | reconcile | signals, lower bound | repaint |
|---|---|---|---|---|---|
| loading screen, 31 progress events | 9 | 0.006 ms | 0.19 ms | 0.03 ms | 0.10 ms |
| boot log, 200 lines, following the newest | ~50 | 0.10 ms | 2.96 ms | 0.04 ms | 8.2 ms |
| 400 keyed rows, one changes | 400 | 0.51 ms | 5.67 ms | 0.02 ms | 2.1 ms |
| the same 400 rows in 20 components | 400 | 0.05 ms | 1.09 ms | 0.02 ms | 2.1 ms |
The signals column times the cheapest possible signal update: set the value, rebuild the one dependent leaf, compute its damage. It leaves out dependency tracking and subscription bookkeeping, so a real signals system costs more.
What the numbers say:
- For the screens this library was built for (under 60 nodes), view plus reconcile is a fraction of a millisecond except when every line moves, and repaint costs more than either.
- When every visible line moves (the boot log scrolling by one line), repaint dominates at 8.2 ms, and signals would not reduce it: every line still moves, so every line still has to be updated and repainted. Moving a leaf translates its items instead of rebuilding them, which took this case from 3.8 ms to 3.0 ms.
- Reconciling costs about 10 to 15 microseconds per node that did not change (
MICRO reconcile, nothing changedin the bench output). That limits a single flat view to a few hundred nodes per frame at 60 Hz. Components restore the gap: splitting 400 rows into 20 components makes an update cost 1.1 ms, because 19 components are skipped after oneequal?on their arguments.
Signals would make each update proportional to what changed, at the price of a dependency graph, subscription lifetimes, and a second way to write views. Whole re-run keeps views as plain functions of state, keeps the retained tree the only state sigil-ui owns, and makes the "equals a fresh render" invariant easy to test. Components give the cases that need it most of the benefit, with the developer choosing the boundaries.
Revisit this if a program needs thousands of nodes that change often and cannot be split into components; the per-node reconcile cost is the number to improve first.
Themes
A theme maps names to colors, font sets and mask sets. Views use the names. ui-set-theme! replaces the theme and drops the retained tree, so the next update repaints everything; that is the simplest correct behavior, since a theme change can change any item.
Surfaces
- Offscreen: a canvas with nothing behind it; used for tests and test renders.
- fbdev: maps
/dev/fbNin the mode it has. Only 32 bpp XRGB8888 is accepted. At open it puts the same mode back withFB_ACTIVATE_FORCE: on a DRM driver's fbdev emulation this commits the emulated framebuffer to the display, and without it nothing written to the mapping is seen. Each present callsfsync, which flushes the emulation's deferred I/O at once instead of about 50 ms later. - DRM: finds a connected connector and its CRTC, keeps the CRTC's current mode (or uses the connector's preferred mode when the CRTC has none, and reports that it set a mode), allocates a dumb buffer, and shows it on the first present. Later presents copy the damaged rectangle and mark it with
DIRTYFB. Dropping and setting DRM master is exposed for handing the display to another process.
A present copies a rectangle of the canvas to the device, so the damage list from ui-update! (scaled by s) is what a program presents.
The Wayland surface
(sigil ui wayland) shows a canvas in a Wayland compositor and reports input. It is its own module, not a fourth kind of surface: the size and scale of a Wayland surface change while it is open, it delivers input, and the compositor paces its frames. None of that fits the fixed-size surface record. Both take a canvas in device pixels and damage rectangles, so the code that renders is the same.
Roles
- toplevel: an xdg-toplevel window with a title and app id. The compositor may resize it (tiling, the user dragging an edge) and may ask it to close; both arrive as events.
- fullscreen: a layer-shell surface on the overlay layer, anchored to every edge of the chosen output, with exclusive keyboard focus. This is what an installer, launcher or lock screen wants. When the compositor offers no
zwlr_layer_shell_v1, the surface is a fullscreen xdg-toplevel on the same output instead, andwayland-surface-rolesaysfullscreenrather thanlayer. A program that needs to know which one it got asks.
open-wayland-surface returns once the compositor has configured the surface, so the size and scale are known before the first frame. An output name that does not exist is an error that lists the outputs there are.
Presenting
Pixels go through wl_shm in two XRGB8888 buffers. Each buffer remembers the damage it has not seen yet, so a present copies only the rectangles that changed since that buffer was last shown, then commits with exactly the damage it was given (wl_surface.damage_buffer, in device pixels). After more than 32 rectangles, damage collapses to their bounding box.
One frame callback is in flight at a time. A present made while it is outstanding, or while the compositor holds both buffers, is deferred: the damage is kept, wayland-present! returns #f, and wayland-dispatch presents it from the same canvas once the compositor can take it. A program can present on every state change without flooding the compositor, and it never draws into a buffer the compositor is reading.
A resize or a new scale changes the buffer size. Buffers of the old size that the compositor still holds are retired: never written again, destroyed when released. The next present must be a canvas of the new device size, and it is the one that acknowledges the configure; it goes out even while a frame callback is outstanding, since a hidden surface gets no frame callbacks and the compositor waits for the acknowledgement. Once the surface shows a buffer of its current size, a configure that changes nothing is acknowledged at once, because some compositors (sway) hold their layout until every window has acknowledged.
Input
The keyboard uses the compositor's keymap through xkbcommon. Key events carry the keysym name, the evdev code, the active modifiers and the UTF-8 text a text field should insert: empty for keys that type nothing, such as Return, BackSpace or Ctrl with a letter. Dead keys and the compose key go through xkbcommon's compose tables for the locale when the library has them. Key repeat follows the rate and delay the compositor sends and is generated inside wayland-dispatch, which wakes in time for the next repeat.
Pointer positions are logical pixels, rounded down. Buttons have names for the five usual ones and evdev codes otherwise. Scroll gives the distance in logical pixels plus wheel steps (zero on a touchpad). Keyboard and pointer focus changes are events. The cursor shape is set through wp_cursor_shape_v1 when the compositor has it; otherwise the compositor keeps whatever cursor it shows.
Scale
The buffer scale is an integer: the compositor's wl_surface.preferred_buffer_scale when it sends one, else the largest scale among the outputs the surface is on. The logical size stays what the compositor configured, the canvas is that size times the scale, and a ui made with wayland-make-ui draws at that scale with the matching fonts. A scale change is a resize event like a size change.
A fractional-scale output (1.5, say) reports the next integer up through wl_output.scale. The surface renders at that integer scale (2) and the compositor scales the buffer down to 1.5. Text is resampled, so it is slightly soft, and every frame costs the pixels of the larger scale. The wp_fractional_scale_v1 protocol is not used, because sigil-ui has only integer scales. Supporting it would need fonts and masks drawn for fractional scales and a viewport to map the buffer.
The event loop
The program owns the loop. wayland-dispatch waits up to a timeout (or without limit, or not at all) and returns the events that arrived, so a program can fit its own timers around it. wayland-surface-fd gives the connection's descriptor for a program that polls several descriptors itself. The connection is not shared between surfaces: each surface opens its own.
Loading the libraries
The native code does not link against libwayland-client or libxkbcommon. It loads libwayland-client.so.0 and libxkbcommon.so.0 with dlopen when the first surface opens, so a program that only uses fbdev or DRM gains no dependency. SIGIL_UI_LIBWAYLAND_CLIENT and SIGIL_UI_LIBXKBCOMMON name other paths. The protocol code (wayland-scanner output for the core protocol, xdg-shell, wlr-layer-shell, cursor-shape and the tablet protocol it refers to) is checked in under native/wayland/, beside the protocol XML; scripts/generate-wayland-protocols regenerates it, and the test driver's protocol code under test/wayland/. The other wayland-client headers in native/wayland/include/ are copied from libwayland. Building sigil-ui needs no Wayland headers.
A program linked fully statically against musl cannot dlopen, so it cannot open a Wayland surface.
Events and text come back from C one at a time, as fixnums in a vector the Sigil side owns, plus one string per key event. C never builds Sigil lists: the collector moves young objects, and a half-built list in a C local is not a root.
Tests
test/test-wayland.sgl runs in the default suite and needs no compositor. test/wayland/run starts a headless sway (pixman renderer, its own runtime directory and socket), builds a small virtual keyboard and pointer client (test/wayland/input-driver.c), and runs test/wayland/live.sgl. The live tests compare screenshots with the canvas byte for byte at scale 1 and 2. They also cover: damage carried into the other buffer, the two-buffer limit and deferred presents, a resize while a buffer is in flight, close requests, typed text, repeat at a rate set for the test and compose, focus, pointer and scroll, layer-shell, the fallback without it, the scale chosen on a fractional output and the error for an unknown output.
Not covered, and where it would go
- GPU rendering: sigil-ui renders on the CPU into a canvas. A GPU renderer would be a new renderer for the display list (next to
(sigil ui display)), drawing into a GPU image instead of a canvas. The surface would then need an EGL or Vulkan swapchain beside the shm path. - DMA-BUF: buffers from
zwp_linux_dmabuf_v1would replace the shm pair inside the native present path. They pay off with a GPU renderer, or when scanning out directly; for a CPU-drawn canvas, shm is the right buffer. - Clipboard:
wl_data_deviceselection, an offer/receive pair of calls on the surface plus events for a new selection. Data arrives through a pipe, so it would hand the program a descriptor to read. - Drag and drop: the same
wl_data_device, with enter, motion, drop and leave events like the pointer's, plus a way to start a drag from a pointer press. - IME:
zwp_text_input_v3, with preedit and commit events for a text field and a call to report the cursor rectangle. Text fields would need a preedit state in the tree. Compose and dead keys already work without it. - Accessibility: an AT-SPI tree built from the retained tree (element roles, labels, focus) and published over D-Bus. It belongs above the surface, beside
(sigil ui tree), since it describes elements, not pixels.
Rendering rules
- Text is a bitmap font per scale. Set bits write the color; clear bits and spaces leave pixels as they are. A code point the font cannot draw is an error when the item is built, so it surfaces where the view produced it. Text that would leave the canvas is an error when it is drawn.
- Blends and masks use
out = (bg (255 - a) + fg a + 127) / 255per channel, with integer division. A level of 255 writes the color exactly. - No color management: colors go to the device as given.
Known limits
- No layout engine, no widget-level input handling, no animation clock. The Wayland surface reports raw input; hit testing, focus order and timing belong to the program, which re-runs the view when its state changes.
- The display list is flat and repaint scans all of it per damaged rectangle. That is linear in the item count and fine for hundreds of items; a spatial index would be the next step.
- Damage merging is quadratic in the number of rectangles. A scroll that moves every line produces about two rectangles per line.