Atv0.2.2Repositorysigil-ui
Document

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

modulewhat 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 --> surface

Units 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 while fn is the same procedure (eq?) and arg is equal? 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:

scenarionodesviewreconcilesignals, lower boundrepaint
loading screen, 31 progress events90.006 ms0.19 ms0.03 ms0.10 ms
boot log, 200 lines, following the newest~500.10 ms2.96 ms0.04 ms8.2 ms
400 keyed rows, one changes4000.51 ms5.67 ms0.02 ms2.1 ms
the same 400 rows in 20 components4000.05 ms1.09 ms0.02 ms2.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 changed in 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 one equal? 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/fbN in the mode it has. Only 32 bpp XRGB8888 is accepted. At open it puts the same mode back with FB_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 calls fsync, 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, and wayland-surface-role says fullscreen rather than layer. 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. Initial configuration waits for compositor policy for up to five seconds on a monotonic clock; protocol synchronization replies do not substitute for configuration. With SIGIL_UI_TRACE_CONFIGURE=1, stderr reports the empty-commit-to-configure duration and pending-event dispatch batch count, including a diagnostic when the wait fails. An initial close ends that wait even if a configure follows it. Once a window is configured, close remains an event for the application to handle. The deadline also applies when unrelated protocol traffic never becomes idle.

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 whole wheel steps (zero on a touchpad). The legacy wayland-dispatch shape is (scroll dx dy steps-x steps-y x y), seven items. On seat v8 and later, fractional value120 input accumulates across frames into whole steps; direction changes, source changes and axis stops reset the unfinished fraction. Older seats supply discrete steps directly. Legacy dispatch omits zero-motion stop-only frames.

wayland-window-dispatch, and window-dispatch on Wayland, add one eighth item: the nested list (source value120-x value120-y stops). Source is wheel, finger, continuous, wheel-tilt or unknown. Each wheel notch is 120 value120 units; these fields are zero below seat v8 and for finger or continuous input. Stops is an axis bitmask: 1 horizontal, 2 vertical. This dispatch includes stop-only frames so consumers can end gestures. AppKit window-dispatch scroll events keep seven items.

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 and test/wayland/bridge.sgl. The bridge cases additionally require wl-copy and wl-paste. 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.

Embedded pages and overlays

open-wayland-subsurface creates a child on an existing toplevel's connection. Page children (overlay?: #f) are below the parent; overlays are above it and have empty input regions so pointer input passes through. Present and dispatch use the same canvas and event APIs as a toplevel. Each child has its own buffers and frame callback. Closing a parent closes its children before disconnecting; closing either handle again is harmless. Child handles retain the parent.

An opaque toplevel covers pages below it. Open the toplevel with transparent?: #t and use wayland-set-alpha! for the chrome's opaque regions. The mask has one byte per device pixel and is copied immediately. Presentation premultiplies RGB by this mask for Wayland ARGB8888, including full-damage presents. Overlays use the same mask API. Without a mask, an alpha surface is opaque. Set a new mask after a resize or scale change before presenting again. The ordinary toplevel remains XRGB8888 unless transparency is requested.

wayland-keymap returns the compositor's XKB text, or #f until a valid map arrives. Key events continue to use that compositor map and compose handling. Queued compositor input is read before generating overdue synthetic repeats, so a release already on the connection prevents an extra repeat.

wayland-clipboard-set! owns UTF-8 text through the seat's data device. Call it from an input action; it returns #f without an input serial or data device, for invalid UTF-8, or above 4 MiB. Keep dispatching to serve other clients. Outgoing pipes are nonblocking and have two-second deadlines, with at most eight transfers retained. wayland-clipboard-read returns UTF-8 text or #f; external reads have the same size limit and a two-second deadline. Supported MIME types are text/plain and text/plain;charset=utf-8.

Native embedders use wayland-native-handle with native/wayland-bridge.h. Acquire a reference before storing the handle and unref it after use. The bridge owns all protocol state. SHM presentation copies the supplied rows, then reports release on the compositor's buffer release, and frame completion on its frame callback. A rejected present owns no callback data. Teardown reports a pending frame as canceled and releases retained buffers exactly once; cancellation is never reported as presentation. Calls and callbacks belong to the same thread. Native buffers for an overlay are premultiplied ARGB8888; page buffers are XRGB8888.

Native embedders can change child geometry in logical pixels, read the compositor's current XKB modifier masks and group, and observe a selection generation plus whether text is offered. Read these snapshots after UI dispatch. Geometry changes use the existing buffer retirement rules on the next present. The native include directory is exposed to direct dependents so they can include wayland-bridge.h through their normal package build.

test/wayland/native-bridge.c is a native client fixture for this contract. Compile it with the matching Sigil runtime headers/archive, the checked-in Wayland protocol include directories and -D_GNU_SOURCE, then run it in a private compositor. It checks release after replacement, compositor pacing, rejected presentation, cancellation before dispatch, and parent close when the final notification drops the child's last reference. It also checks final unref without close, connection failure before parent or child cleanup, a clipboard reader disappearing after a partial write, and an unread pipe reaching its transfer deadline. The Sigil bridge case also stops a real clipboard owner and checks that an incoming read times out and closes its pipe. Build the native fixture with -fsanitize=address -fno-omit-frame-pointer to check callback-driven teardown for memory errors; disable leak detection for the embedded runtime if needed. Run it without arguments, then with each of --failed-child, --failed-parent and --failed-child-unref to cover the connection failures.

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_v1 would 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.
  • Rich clipboard formats: the data device currently supports UTF-8 text. Images and application-specific MIME types need a format-aware transfer API.
  • 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) / 255 per 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.