AtlatestRepositorysigil-ui
1
# sigil-ui design3
sigil-ui is a retained-mode UI library for Sigil. A program describes what4
the screen should show as plain data; sigil-ui keeps the last description,5
works out what changed, and repaints only that. It renders in software onto6
a pixel canvas, which it shows through an offscreen buffer, a Linux fbdev7
framebuffer, a DRM dumb buffer or a Wayland surface.9
This document covers the model, the choices behind it, and the measurement10
that decided how much of a view runs again on each change.12
## The pieces14
| module | what it is |15
|---|---|16
| `(sigil ui color)` | colors as 24-bit integers, `rgb` and `hex` |17
| `(sigil ui raster)` | the canvas: XRGB8888 pixels, clipped fills, blends, masks, bitmaps and copies in C |18
| `(sigil ui font)` | bitmap fonts and font sets (one font per integer scale, same logical advance) |19
| `(sigil ui mask)` | 8-bit alpha masks, 4-bit run-length decoding, mask sets per scale |20
| `(sigil ui display)` | the display list: fill, blend, text and mask items, rendering and clipped repaint |21
| `(sigil ui theme)` | names for colors, fonts and images |22
| `(sigil ui tree)` | elements, the retained tree, reconciliation, and the `ui` object |23
| `(sigil ui surface)` | offscreen, fbdev and DRM surfaces |24
| `(sigil ui wayland)` | a Wayland window or fullscreen surface, with keyboard and pointer input |25
| `(sigil ui png)` | PNG output for test renders |27
The flow on every change:29
```30
state --view--> element tree --reconcile--> retained tree + damage31
|32
display list ------+--> repaint damage --> canvas --> surface33
```35
## Units and scale37
Everything above the canvas is in logical pixels. A ui has one integer scale38
`s`; a logical pixel is an `s` x `s` block of device pixels. Fonts and masks39
come in sets with one entry per scale, and a font set refuses fonts whose40
advance is not the same number of logical pixels at every scale, so layout41
never depends on the scale. There is no fractional scaling and no42
antialiasing beyond what a mask carries.44
## Elements46
A view is an ordinary function from state to an element tree. Elements are47
lists, compared with `equal?`:49
```scheme50
(rect x y w h color)51
(blend-rect x y w h color alpha)52
(label x y string color [font])53
(runs x y ((string . color) ...) [font])54
(image x y name color)55
(group x y children)56
(keyed key element)57
(component fn arg)58
```60
Colors are theme tokens (`'fg1`) or integers. Fonts and images are theme61
names. An element never holds an asset, so the same view renders under any62
theme that defines the names it uses, and comparing two elements is cheap.64
Layout is explicit: a view computes positions itself. `text-advance` gives a65
string's logical width in a theme font, which is what centering and66
right-alignment need. A layout engine (rows, columns, constraints) can be67
built as functions that produce elements; it is not part of this version.69
## The retained tree and reconciliation71
`ui-update!` takes the next element tree, reconciles it with the retained72
one and repaints the damage. The rules:74
- **Identity.** A child is matched with an old sibling by its key if it has75
one (`keyed`), otherwise by its position among its siblings. Kinds must76
match too: a group never turns into a leaf in place. Duplicate keys among77
siblings are an error.78
- **Leaves.** A leaf whose element and origin are unchanged keeps its display79
items and costs no repaint. If only its origin changed (a parent group80
moved), its items are moved, not rebuilt. Otherwise its items are built81
again, and both its old and new bounds are damaged.82
- **Components.** `(component fn arg)` runs `(fn arg)` to get its element. It83
is not run again while `fn` is the same procedure (`eq?`) and `arg` is84
`equal?` to the last one; its subtree is kept, or moved if its origin85
changed.86
- **Removal and order.** A removed child damages its old bounds. A keyed87
child that now comes before a sibling it used to follow damages its88
bounds, because paint order changed.89
- **Repaint.** Damaged rectangles are merged where they touch, clipped to90
the screen, cleared to the ui's background and repainted from the whole91
display list, clipped to each rectangle.93
The invariant is that after any update the canvas equals a fresh render of94
the latest tree. `test/test-tree.sgl` checks it after 40 random updates at95
scale 1 and 2, and it fails when either damage rule above is removed.97
### Keyed identity99
Keys matter when children are inserted, removed or reordered. Matched by100
position, inserting one row at the top of a list makes every row differ101
from the row that used to be at its position, so everything is rebuilt.102
Matched by key, only the new row is built (the tests check both cases). Use103
a key that names the thing the row shows: a generation number, a service104
name, a log line's sequence number. Keys only need to be unique among105
siblings.107
## Re-run granularity: whole view, with components109
The choice was between re-running the whole view on every change and110
reconciling, as above, or tracking dependencies with signals so that a111
change updates only the leaves that read it.113
**Decision: whole re-run with reconciliation, with components to skip114
subtrees whose input did not change.** Signals are not part of sigil-ui.116
The measurement, `bench/` (run it with `sigil build --config release` and117
then `build/release/bin/sigil-ui-bench`). It builds natively at optimize 2,118
the way a shipping program is built, and runs on an AMD Ryzen 7 7840U at119
1920x1080, scale 1, with a synthetic 8x16 font. Times are per update, the120
median of three runs:122
| scenario | nodes | view | reconcile | signals, lower bound | repaint |123
|---|---|---|---|---|---|124
| loading screen, 31 progress events | 9 | 0.006 ms | 0.19 ms | 0.03 ms | 0.10 ms |125
| boot log, 200 lines, following the newest | ~50 | 0.10 ms | 2.96 ms | 0.04 ms | 8.2 ms |126
| 400 keyed rows, one changes | 400 | 0.51 ms | 5.67 ms | 0.02 ms | 2.1 ms |127
| the same 400 rows in 20 components | 400 | 0.05 ms | 1.09 ms | 0.02 ms | 2.1 ms |129
The signals column times the cheapest possible signal update: set the value,130
rebuild the one dependent leaf, compute its damage. It leaves out dependency131
tracking and subscription bookkeeping, so a real signals system costs more.133
What the numbers say:135
- For the screens this library was built for (under 60 nodes), view plus136
reconcile is a fraction of a millisecond except when every line moves, and137
repaint costs more than either.138
- When every visible line moves (the boot log scrolling by one line),139
repaint dominates at 8.2 ms, and signals would not reduce it: every line140
still moves, so every line still has to be updated and repainted. Moving141
a leaf translates its items instead of rebuilding them, which took this142
case from 3.8 ms to 3.0 ms.143
- Reconciling costs about 10 to 15 microseconds per node that did not144
change (`MICRO reconcile, nothing changed` in the bench output). That145
limits a single flat view to a few hundred nodes per frame at146
60 Hz. Components restore the gap: splitting 400 rows into 20 components147
makes an update cost 1.1 ms, because 19 components are skipped after one148
`equal?` on their arguments.150
Signals would make each update proportional to what changed, at the price of151
a dependency graph, subscription lifetimes, and a second way to write views.152
Whole re-run keeps views as plain functions of state, keeps the retained153
tree the only state sigil-ui owns, and makes the "equals a fresh render"154
invariant easy to test. Components give the cases that need it most of the155
benefit, with the developer choosing the boundaries.157
Revisit this if a program needs thousands of nodes that change often and158
cannot be split into components; the per-node reconcile cost is the number159
to improve first.161
## Themes163
A theme maps names to colors, font sets and mask sets. Views use the names.164
`ui-set-theme!` replaces the theme and drops the retained tree, so the next165
update repaints everything; that is the simplest correct behavior, since a166
theme change can change any item.168
## Surfaces170
- **Offscreen**: a canvas with nothing behind it; used for tests and test171
renders.172
- **fbdev**: maps `/dev/fbN` in the mode it has. Only 32 bpp XRGB8888 is173
accepted. At open it puts the same mode back with `FB_ACTIVATE_FORCE`: on174
a DRM driver's fbdev emulation this commits the emulated framebuffer to175
the display, and without it nothing written to the mapping is seen. Each176
present calls `fsync`, which flushes the emulation's deferred I/O at once177
instead of about 50 ms later.178
- **DRM**: finds a connected connector and its CRTC, keeps the CRTC's179
current mode (or uses the connector's preferred mode when the CRTC has180
none, and reports that it set a mode), allocates a dumb buffer, and shows181
it on the first present. Later presents copy the damaged rectangle and182
mark it with `DIRTYFB`. Dropping and setting DRM master is exposed for183
handing the display to another process.185
A present copies a rectangle of the canvas to the device, so the damage list186
from `ui-update!` (scaled by `s`) is what a program presents.188
## The Wayland surface190
`(sigil ui wayland)` shows a canvas in a Wayland compositor and reports191
input. It is its own module, not a fourth kind of `surface`: the size and192
scale of a Wayland surface change while it is open, it delivers input, and193
the compositor paces its frames. None of that fits the fixed-size194
`surface` record. Both take a canvas in device pixels and damage195
rectangles, so the code that renders is the same.197
### Roles199
- **toplevel**: an xdg-toplevel window with a title and app id. The200
compositor may resize it (tiling, the user dragging an edge) and may ask201
it to close; both arrive as events.202
- **fullscreen**: a layer-shell surface on the overlay layer, anchored to203
every edge of the chosen output, with exclusive keyboard focus. This is204
what an installer, launcher or lock screen wants. When the compositor205
offers no `zwlr_layer_shell_v1`, the surface is a fullscreen xdg-toplevel206
on the same output instead, and `wayland-surface-role` says `fullscreen`207
rather than `layer`. A program that needs to know which one it got asks.209
`open-wayland-surface` returns once the compositor has configured the210
surface, so the size and scale are known before the first frame. An output211
name that does not exist is an error that lists the outputs there are.212
Initial configuration waits for compositor policy for up to five seconds213
on a monotonic clock; protocol synchronization replies do not substitute214
for configuration. With `SIGIL_UI_TRACE_CONFIGURE=1`, stderr reports the215
empty-commit-to-configure duration and pending-event dispatch batch count,216
including a diagnostic when the wait fails.217
An initial close ends that wait even if a configure follows it. Once a218
window is configured, close remains an event for the application to handle.219
The deadline also applies when unrelated protocol traffic never becomes idle.221
### Presenting223
Pixels go through `wl_shm` in two XRGB8888 buffers. Each buffer remembers224
the damage it has not seen yet, so a present copies only the rectangles225
that changed since that buffer was last shown, then commits with exactly226
the damage it was given (`wl_surface.damage_buffer`, in device pixels).227
After more than 32 rectangles, damage collapses to their bounding box.229
One frame callback is in flight at a time. A present made while it is230
outstanding, or while the compositor holds both buffers, is deferred: the231
damage is kept, `wayland-present!` returns `#f`, and `wayland-dispatch`232
presents it from the same canvas once the compositor can take it. A program233
can present on every state change without flooding the compositor, and it234
never draws into a buffer the compositor is reading.236
A resize or a new scale changes the buffer size. Buffers of the old size237
that the compositor still holds are retired: never written again, destroyed238
when released. The next present must be a canvas of the new device size,239
and it is the one that acknowledges the configure; it goes out even while a240
frame callback is outstanding, since a hidden surface gets no frame241
callbacks and the compositor waits for the acknowledgement. Once the surface242
shows a buffer of its current size, a configure that changes nothing is243
acknowledged at once, because some compositors (sway) hold their layout244
until every window has acknowledged.246
### Input248
The keyboard uses the compositor's keymap through xkbcommon. Key events249
carry the keysym name, the evdev code, the active modifiers and the UTF-8250
text a text field should insert: empty for keys that type nothing, such as251
Return, BackSpace or Ctrl with a letter. Dead keys and the compose key go252
through xkbcommon's compose tables for the locale when the library has253
them. Key repeat follows the rate and delay the compositor sends and is254
generated inside `wayland-dispatch`, which wakes in time for the next255
repeat.257
Pointer positions are logical pixels, rounded down. Buttons have names for258
the five usual ones and evdev codes otherwise. Scroll gives the distance in259
logical pixels plus whole wheel steps (zero on a touchpad). The legacy260
`wayland-dispatch` shape is `(scroll dx dy steps-x steps-y x y)`, seven261
items. On seat v8 and later, fractional value120 input accumulates across262
frames into whole steps; direction changes, source changes and axis stops263
reset the unfinished fraction. Older seats supply discrete steps directly.264
Legacy dispatch omits zero-motion stop-only frames.266
`wayland-window-dispatch`, and `window-dispatch` on Wayland, add one eighth267
item: the nested list `(source value120-x value120-y stops)`. Source is268
`wheel`, `finger`, `continuous`, `wheel-tilt` or `unknown`. Each wheel notch269
is 120 value120 units; these fields are zero below seat v8 and for finger270
or continuous input. Stops is an axis bitmask: 1 horizontal, 2 vertical.271
This dispatch includes stop-only frames so consumers can end gestures.272
AppKit `window-dispatch` scroll events keep seven items.274
Keyboard and pointer focus changes are events. The cursor shape is set through275
`wp_cursor_shape_v1` when the compositor has it; otherwise the compositor276
keeps whatever cursor it shows.278
### Scale280
The buffer scale is an integer: the compositor's281
`wl_surface.preferred_buffer_scale` when it sends one, else the largest282
scale among the outputs the surface is on. The logical size stays what the283
compositor configured, the canvas is that size times the scale, and a ui284
made with `wayland-make-ui` draws at that scale with the matching fonts. A285
scale change is a `resize` event like a size change.287
A fractional-scale output (1.5, say) reports the next integer up through288
`wl_output.scale`. The surface renders at that integer scale (2) and the289
compositor scales the buffer down to 1.5. Text is resampled, so it is290
slightly soft, and every frame costs the pixels of the larger scale. The291
`wp_fractional_scale_v1` protocol is not used, because sigil-ui has only292
integer scales. Supporting it would need fonts and masks drawn for293
fractional scales and a viewport to map the buffer.295
### The event loop297
The program owns the loop. `wayland-dispatch` waits up to a timeout (or298
without limit, or not at all) and returns the events that arrived, so a299
program can fit its own timers around it. `wayland-surface-fd` gives the300
connection's descriptor for a program that polls several descriptors301
itself. The connection is not shared between surfaces: each surface opens302
its own.304
### Loading the libraries306
The native code does not link against libwayland-client or libxkbcommon. It307
loads `libwayland-client.so.0` and `libxkbcommon.so.0` with `dlopen` when308
the first surface opens, so a program that only uses fbdev or DRM gains no309
dependency. `SIGIL_UI_LIBWAYLAND_CLIENT` and `SIGIL_UI_LIBXKBCOMMON` name310
other paths. The protocol code (wayland-scanner output for the core311
protocol, xdg-shell, wlr-layer-shell, cursor-shape and the tablet protocol312
it refers to) is checked in under `native/wayland/`, beside the protocol313
XML; `scripts/generate-wayland-protocols` regenerates it, and the test314
driver's protocol code under `test/wayland/`. The other wayland-client315
headers in `native/wayland/include/` are copied from libwayland. Building316
sigil-ui needs no Wayland headers.318
A program linked fully statically against musl cannot `dlopen`, so it319
cannot open a Wayland surface.321
Events and text come back from C one at a time, as fixnums in a vector the322
Sigil side owns, plus one string per key event. C never builds Sigil lists:323
the collector moves young objects, and a half-built list in a C local is324
not a root.326
### Tests328
`test/test-wayland.sgl` runs in the default suite and needs no compositor.329
`test/wayland/run` starts a headless sway (pixman renderer, its own runtime330
directory and socket), builds a small virtual keyboard and pointer client331
(`test/wayland/input-driver.c`), and runs `test/wayland/live.sgl` and332
`test/wayland/bridge.sgl`. The bridge cases additionally require `wl-copy`333
and `wl-paste`. The live334
tests compare screenshots with the canvas byte for byte at scale 1 and 2.335
They also cover: damage carried into the other buffer, the two-buffer limit336
and deferred presents, a resize while a buffer is in flight, close337
requests, typed text, repeat at a rate set for the test and compose,338
focus, pointer and scroll, layer-shell, the fallback without it, the scale339
chosen on a fractional output and the error for an unknown output.341
### Embedded pages and overlays343
`open-wayland-subsurface` creates a child on an existing toplevel's connection.344
Page children (`overlay?: #f`) are below the parent; overlays are above it and345
have empty input regions so pointer input passes through. Present and dispatch346
use the same canvas and event APIs as a toplevel. Each child has its own buffers347
and frame callback. Closing a parent closes its children before disconnecting;348
closing either handle again is harmless. Child handles retain the parent.350
An opaque toplevel covers pages below it. Open the toplevel with351
`transparent?: #t` and use `wayland-set-alpha!` for the chrome's opaque regions.352
The mask has one byte per device pixel and is copied immediately. Presentation353
premultiplies RGB by this mask for Wayland ARGB8888, including full-damage354
presents. Overlays use the same mask API. Without a mask, an alpha surface is355
opaque. Set a new mask after a resize or scale change before presenting again.356
The ordinary toplevel remains XRGB8888 unless transparency is requested.358
`wayland-keymap` returns the compositor's XKB text, or `#f` until a valid map359
arrives. Key events continue to use that compositor map and compose handling.360
Queued compositor input is read before generating overdue synthetic repeats,361
so a release already on the connection prevents an extra repeat.363
`wayland-clipboard-set!` owns UTF-8 text through the seat's data device. Call it364
from an input action; it returns `#f` without an input serial or data device,365
for invalid UTF-8, or above 4 MiB. Keep dispatching to serve other clients.366
Outgoing pipes are nonblocking and have two-second deadlines, with at most367
eight transfers retained. `wayland-clipboard-read` returns UTF-8 text or `#f`;368
external reads have the same size limit and a two-second deadline. Supported369
MIME types are `text/plain` and `text/plain;charset=utf-8`.371
Native embedders use `wayland-native-handle` with `native/wayland-bridge.h`.372
Acquire a reference before storing the handle and unref it after use. The373
bridge owns all protocol state. SHM presentation copies the supplied rows,374
then reports release on the compositor's buffer release, and frame completion375
on its frame callback. A rejected present owns no callback data. Teardown376
reports a pending frame as canceled and releases retained buffers exactly377
once; cancellation is never reported as presentation. Calls and callbacks378
belong to the same thread. Native buffers for an overlay are premultiplied379
ARGB8888; page buffers are XRGB8888.381
Native embedders can change child geometry in logical pixels, read the382
compositor's current XKB modifier masks and group, and observe a selection383
generation plus whether text is offered. Read these snapshots after UI384
dispatch. Geometry changes use the existing buffer retirement rules on the385
next present. The native include directory is exposed to direct dependents386
so they can include `wayland-bridge.h` through their normal package build.388
`test/wayland/native-bridge.c` is a native client fixture for this contract.389
Compile it with the matching Sigil runtime headers/archive, the checked-in390
Wayland protocol include directories and `-D_GNU_SOURCE`, then run it in a391
private compositor. It checks release after replacement, compositor pacing,392
rejected presentation, cancellation before dispatch, and parent close when393
the final notification drops the child's last reference. It also checks final394
unref without close, connection failure before parent or child cleanup, a395
clipboard reader disappearing after a partial write, and an unread pipe396
reaching its transfer deadline. The Sigil bridge case also stops a real397
clipboard owner and checks that an incoming read times out and closes its398
pipe. Build the native fixture with399
`-fsanitize=address -fno-omit-frame-pointer` to check callback-driven teardown400
for memory errors; disable leak detection for the embedded runtime if needed.401
Run it without arguments, then with each of `--failed-child`,402
`--failed-parent` and `--failed-child-unref` to cover the connection failures.404
### Not covered, and where it would go406
- **GPU rendering**: sigil-ui renders on the CPU into a canvas. A GPU407
renderer would be a new renderer for the display list (next to408
`(sigil ui display)`), drawing into a GPU image instead of a canvas. The409
surface would then need an EGL or Vulkan swapchain beside the shm path.410
- **DMA-BUF**: buffers from `zwp_linux_dmabuf_v1` would replace the shm pair411
inside the native present path. They pay off with a GPU renderer, or when412
scanning out directly; for a CPU-drawn canvas, shm is the right buffer.413
- **Rich clipboard formats**: the data device currently supports UTF-8 text.414
Images and application-specific MIME types need a format-aware transfer API.415
- **Drag and drop**: the same `wl_data_device`, with enter, motion, drop and416
leave events like the pointer's, plus a way to start a drag from a417
pointer press.418
- **IME**: `zwp_text_input_v3`, with preedit and commit events for a text419
field and a call to report the cursor rectangle. Text fields would need a420
preedit state in the tree. Compose and dead keys already work without it.421
- **Accessibility**: an AT-SPI tree built from the retained tree (element422
roles, labels, focus) and published over D-Bus. It belongs above the423
surface, beside `(sigil ui tree)`, since it describes elements, not424
pixels.426
## Rendering rules428
- Text is a bitmap font per scale. Set bits write the color; clear bits and429
spaces leave pixels as they are. A code point the font cannot draw is an430
error when the item is built, so it surfaces where the view produced it.431
Text that would leave the canvas is an error when it is drawn.432
- Blends and masks use `out = (bg (255 - a) + fg a + 127) / 255` per channel,433
with integer division. A level of 255 writes the color exactly.434
- No color management: colors go to the device as given.436
## Known limits438
- No layout engine, no widget-level input handling, no animation clock.439
The Wayland surface reports raw input; hit testing, focus order and timing440
belong to the program, which re-runs the view when its state changes.441
- The display list is flat and repaint scans all of it per damaged442
rectangle. That is linear in the item count and fine for hundreds of443
items; a spatial index would be the next step.444
- Damage merging is quadratic in the number of rectangles. A scroll that445
moves every line produces about two rectangles per line.