AtlatestRepositorysigil-ui
1# sigil-ui design
2
3sigil-ui is a retained-mode UI library for Sigil. A program describes what
4the screen should show as plain data; sigil-ui keeps the last description,
5works out what changed, and repaints only that. It renders in software onto
6a pixel canvas, which it shows through an offscreen buffer, a Linux fbdev
7framebuffer, a DRM dumb buffer or a Wayland surface.
8
9This document covers the model, the choices behind it, and the measurement
10that decided how much of a view runs again on each change.
12## The pieces
14| 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 |
27The flow on every change:
29```
30state --view--> element tree --reconcile--> retained tree + damage
31 |
32 display list ------+--> repaint damage --> canvas --> surface
33```
35## Units and scale
37Everything above the canvas is in logical pixels. A ui has one integer scale
38`s`; a logical pixel is an `s` x `s` block of device pixels. Fonts and masks
39come in sets with one entry per scale, and a font set refuses fonts whose
40advance is not the same number of logical pixels at every scale, so layout
41never depends on the scale. There is no fractional scaling and no
42antialiasing beyond what a mask carries.
44## Elements
46A view is an ordinary function from state to an element tree. Elements are
47lists, compared with `equal?`:
49```scheme
50(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```
60Colors are theme tokens (`'fg1`) or integers. Fonts and images are theme
61names. An element never holds an asset, so the same view renders under any
62theme that defines the names it uses, and comparing two elements is cheap.
64Layout is explicit: a view computes positions itself. `text-advance` gives a
65string's logical width in a theme font, which is what centering and
66right-alignment need. A layout engine (rows, columns, constraints) can be
67built as functions that produce elements; it is not part of this version.
69## The retained tree and reconciliation
71`ui-update!` takes the next element tree, reconciles it with the retained
72one and repaints the damage. The rules:
74- **Identity.** A child is matched with an old sibling by its key if it has
75 one (`keyed`), otherwise by its position among its siblings. Kinds must
76 match too: a group never turns into a leaf in place. Duplicate keys among
77 siblings are an error.
78- **Leaves.** A leaf whose element and origin are unchanged keeps its display
79 items and costs no repaint. If only its origin changed (a parent group
80 moved), its items are moved, not rebuilt. Otherwise its items are built
81 again, and both its old and new bounds are damaged.
82- **Components.** `(component fn arg)` runs `(fn arg)` to get its element. It
83 is not run again while `fn` is the same procedure (`eq?`) and `arg` is
84 `equal?` to the last one; its subtree is kept, or moved if its origin
85 changed.
86- **Removal and order.** A removed child damages its old bounds. A keyed
87 child that now comes before a sibling it used to follow damages its
88 bounds, because paint order changed.
89- **Repaint.** Damaged rectangles are merged where they touch, clipped to
90 the screen, cleared to the ui's background and repainted from the whole
91 display list, clipped to each rectangle.
93The invariant is that after any update the canvas equals a fresh render of
94the latest tree. `test/test-tree.sgl` checks it after 40 random updates at
95scale 1 and 2, and it fails when either damage rule above is removed.
97### Keyed identity
99Keys matter when children are inserted, removed or reordered. Matched by
100position, inserting one row at the top of a list makes every row differ
101from the row that used to be at its position, so everything is rebuilt.
102Matched by key, only the new row is built (the tests check both cases). Use
103a key that names the thing the row shows: a generation number, a service
104name, a log line's sequence number. Keys only need to be unique among
105siblings.
107## Re-run granularity: whole view, with components
109The choice was between re-running the whole view on every change and
110reconciling, as above, or tracking dependencies with signals so that a
111change updates only the leaves that read it.
113**Decision: whole re-run with reconciliation, with components to skip
114subtrees whose input did not change.** Signals are not part of sigil-ui.
116The measurement, `bench/` (run it with `sigil build --config release` and
117then `build/release/bin/sigil-ui-bench`). It builds natively at optimize 2,
118the way a shipping program is built, and runs on an AMD Ryzen 7 7840U at
1191920x1080, scale 1, with a synthetic 8x16 font. Times are per update, the
120median 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 |
129The signals column times the cheapest possible signal update: set the value,
130rebuild the one dependent leaf, compute its damage. It leaves out dependency
131tracking and subscription bookkeeping, so a real signals system costs more.
133What the numbers say:
135- For the screens this library was built for (under 60 nodes), view plus
136 reconcile is a fraction of a millisecond except when every line moves, and
137 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 line
140 still moves, so every line still has to be updated and repainted. Moving
141 a leaf translates its items instead of rebuilding them, which took this
142 case from 3.8 ms to 3.0 ms.
143- Reconciling costs about 10 to 15 microseconds per node that did not
144 change (`MICRO reconcile, nothing changed` in the bench output). That
145 limits a single flat view to a few hundred nodes per frame at
146 60 Hz. Components restore the gap: splitting 400 rows into 20 components
147 makes an update cost 1.1 ms, because 19 components are skipped after one
148 `equal?` on their arguments.
150Signals would make each update proportional to what changed, at the price of
151a dependency graph, subscription lifetimes, and a second way to write views.
152Whole re-run keeps views as plain functions of state, keeps the retained
153tree the only state sigil-ui owns, and makes the "equals a fresh render"
154invariant easy to test. Components give the cases that need it most of the
155benefit, with the developer choosing the boundaries.
157Revisit this if a program needs thousands of nodes that change often and
158cannot be split into components; the per-node reconcile cost is the number
159to improve first.
161## Themes
163A 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 next
165update repaints everything; that is the simplest correct behavior, since a
166theme change can change any item.
168## Surfaces
170- **Offscreen**: a canvas with nothing behind it; used for tests and test
171 renders.
172- **fbdev**: maps `/dev/fbN` in the mode it has. Only 32 bpp XRGB8888 is
173 accepted. At open it puts the same mode back with `FB_ACTIVATE_FORCE`: on
174 a DRM driver's fbdev emulation this commits the emulated framebuffer to
175 the display, and without it nothing written to the mapping is seen. Each
176 present calls `fsync`, which flushes the emulation's deferred I/O at once
177 instead of about 50 ms later.
178- **DRM**: finds a connected connector and its CRTC, keeps the CRTC's
179 current mode (or uses the connector's preferred mode when the CRTC has
180 none, and reports that it set a mode), allocates a dumb buffer, and shows
181 it on the first present. Later presents copy the damaged rectangle and
182 mark it with `DIRTYFB`. Dropping and setting DRM master is exposed for
183 handing the display to another process.
185A present copies a rectangle of the canvas to the device, so the damage list
186from `ui-update!` (scaled by `s`) is what a program presents.
188## The Wayland surface
190`(sigil ui wayland)` shows a canvas in a Wayland compositor and reports
191input. It is its own module, not a fourth kind of `surface`: the size and
192scale of a Wayland surface change while it is open, it delivers input, and
193the compositor paces its frames. None of that fits the fixed-size
194`surface` record. Both take a canvas in device pixels and damage
195rectangles, so the code that renders is the same.
197### Roles
199- **toplevel**: an xdg-toplevel window with a title and app id. The
200 compositor may resize it (tiling, the user dragging an edge) and may ask
201 it to close; both arrive as events.
202- **fullscreen**: a layer-shell surface on the overlay layer, anchored to
203 every edge of the chosen output, with exclusive keyboard focus. This is
204 what an installer, launcher or lock screen wants. When the compositor
205 offers no `zwlr_layer_shell_v1`, the surface is a fullscreen xdg-toplevel
206 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 the
210surface, so the size and scale are known before the first frame. An output
211name that does not exist is an error that lists the outputs there are.
212Initial configuration waits for compositor policy for up to five seconds
213on a monotonic clock; protocol synchronization replies do not substitute
214for configuration. With `SIGIL_UI_TRACE_CONFIGURE=1`, stderr reports the
215empty-commit-to-configure duration and pending-event dispatch batch count,
216including a diagnostic when the wait fails.
217An initial close ends that wait even if a configure follows it. Once a
218window is configured, close remains an event for the application to handle.
219The deadline also applies when unrelated protocol traffic never becomes idle.
221### Presenting
223Pixels go through `wl_shm` in two XRGB8888 buffers. Each buffer remembers
224the damage it has not seen yet, so a present copies only the rectangles
225that changed since that buffer was last shown, then commits with exactly
226the damage it was given (`wl_surface.damage_buffer`, in device pixels).
227After more than 32 rectangles, damage collapses to their bounding box.
229One frame callback is in flight at a time. A present made while it is
230outstanding, or while the compositor holds both buffers, is deferred: the
231damage is kept, `wayland-present!` returns `#f`, and `wayland-dispatch`
232presents it from the same canvas once the compositor can take it. A program
233can present on every state change without flooding the compositor, and it
234never draws into a buffer the compositor is reading.
236A resize or a new scale changes the buffer size. Buffers of the old size
237that the compositor still holds are retired: never written again, destroyed
238when released. The next present must be a canvas of the new device size,
239and it is the one that acknowledges the configure; it goes out even while a
240frame callback is outstanding, since a hidden surface gets no frame
241callbacks and the compositor waits for the acknowledgement. Once the surface
242shows a buffer of its current size, a configure that changes nothing is
243acknowledged at once, because some compositors (sway) hold their layout
244until every window has acknowledged.
246### Input
248The keyboard uses the compositor's keymap through xkbcommon. Key events
249carry the keysym name, the evdev code, the active modifiers and the UTF-8
250text a text field should insert: empty for keys that type nothing, such as
251Return, BackSpace or Ctrl with a letter. Dead keys and the compose key go
252through xkbcommon's compose tables for the locale when the library has
253them. Key repeat follows the rate and delay the compositor sends and is
254generated inside `wayland-dispatch`, which wakes in time for the next
255repeat.
257Pointer positions are logical pixels, rounded down. Buttons have names for
258the five usual ones and evdev codes otherwise. Scroll gives the distance in
259logical pixels plus whole wheel steps (zero on a touchpad). The legacy
260`wayland-dispatch` shape is `(scroll dx dy steps-x steps-y x y)`, seven
261items. On seat v8 and later, fractional value120 input accumulates across
262frames into whole steps; direction changes, source changes and axis stops
263reset the unfinished fraction. Older seats supply discrete steps directly.
264Legacy dispatch omits zero-motion stop-only frames.
266`wayland-window-dispatch`, and `window-dispatch` on Wayland, add one eighth
267item: the nested list `(source value120-x value120-y stops)`. Source is
268`wheel`, `finger`, `continuous`, `wheel-tilt` or `unknown`. Each wheel notch
269is 120 value120 units; these fields are zero below seat v8 and for finger
270or continuous input. Stops is an axis bitmask: 1 horizontal, 2 vertical.
271This dispatch includes stop-only frames so consumers can end gestures.
272AppKit `window-dispatch` scroll events keep seven items.
274Keyboard and pointer focus changes are events. The cursor shape is set through
275`wp_cursor_shape_v1` when the compositor has it; otherwise the compositor
276keeps whatever cursor it shows.
278### Scale
280The buffer scale is an integer: the compositor's
281`wl_surface.preferred_buffer_scale` when it sends one, else the largest
282scale among the outputs the surface is on. The logical size stays what the
283compositor configured, the canvas is that size times the scale, and a ui
284made with `wayland-make-ui` draws at that scale with the matching fonts. A
285scale change is a `resize` event like a size change.
287A fractional-scale output (1.5, say) reports the next integer up through
288`wl_output.scale`. The surface renders at that integer scale (2) and the
289compositor scales the buffer down to 1.5. Text is resampled, so it is
290slightly soft, and every frame costs the pixels of the larger scale. The
291`wp_fractional_scale_v1` protocol is not used, because sigil-ui has only
292integer scales. Supporting it would need fonts and masks drawn for
293fractional scales and a viewport to map the buffer.
295### The event loop
297The program owns the loop. `wayland-dispatch` waits up to a timeout (or
298without limit, or not at all) and returns the events that arrived, so a
299program can fit its own timers around it. `wayland-surface-fd` gives the
300connection's descriptor for a program that polls several descriptors
301itself. The connection is not shared between surfaces: each surface opens
302its own.
304### Loading the libraries
306The native code does not link against libwayland-client or libxkbcommon. It
307loads `libwayland-client.so.0` and `libxkbcommon.so.0` with `dlopen` when
308the first surface opens, so a program that only uses fbdev or DRM gains no
309dependency. `SIGIL_UI_LIBWAYLAND_CLIENT` and `SIGIL_UI_LIBXKBCOMMON` name
310other paths. The protocol code (wayland-scanner output for the core
311protocol, xdg-shell, wlr-layer-shell, cursor-shape and the tablet protocol
312it refers to) is checked in under `native/wayland/`, beside the protocol
313XML; `scripts/generate-wayland-protocols` regenerates it, and the test
314driver's protocol code under `test/wayland/`. The other wayland-client
315headers in `native/wayland/include/` are copied from libwayland. Building
316sigil-ui needs no Wayland headers.
318A program linked fully statically against musl cannot `dlopen`, so it
319cannot open a Wayland surface.
321Events and text come back from C one at a time, as fixnums in a vector the
322Sigil side owns, plus one string per key event. C never builds Sigil lists:
323the collector moves young objects, and a half-built list in a C local is
324not a root.
326### Tests
328`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 runtime
330directory and socket), builds a small virtual keyboard and pointer client
331(`test/wayland/input-driver.c`), and runs `test/wayland/live.sgl` and
332`test/wayland/bridge.sgl`. The bridge cases additionally require `wl-copy`
333and `wl-paste`. The live
334tests compare screenshots with the canvas byte for byte at scale 1 and 2.
335They also cover: damage carried into the other buffer, the two-buffer limit
336and deferred presents, a resize while a buffer is in flight, close
337requests, typed text, repeat at a rate set for the test and compose,
338focus, pointer and scroll, layer-shell, the fallback without it, the scale
339chosen on a fractional output and the error for an unknown output.
341### Embedded pages and overlays
343`open-wayland-subsurface` creates a child on an existing toplevel's connection.
344Page children (`overlay?: #f`) are below the parent; overlays are above it and
345have empty input regions so pointer input passes through. Present and dispatch
346use the same canvas and event APIs as a toplevel. Each child has its own buffers
347and frame callback. Closing a parent closes its children before disconnecting;
348closing either handle again is harmless. Child handles retain the parent.
350An opaque toplevel covers pages below it. Open the toplevel with
351`transparent?: #t` and use `wayland-set-alpha!` for the chrome's opaque regions.
352The mask has one byte per device pixel and is copied immediately. Presentation
353premultiplies RGB by this mask for Wayland ARGB8888, including full-damage
354presents. Overlays use the same mask API. Without a mask, an alpha surface is
355opaque. Set a new mask after a resize or scale change before presenting again.
356The ordinary toplevel remains XRGB8888 unless transparency is requested.
358`wayland-keymap` returns the compositor's XKB text, or `#f` until a valid map
359arrives. Key events continue to use that compositor map and compose handling.
360Queued compositor input is read before generating overdue synthetic repeats,
361so 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 it
364from an input action; it returns `#f` without an input serial or data device,
365for invalid UTF-8, or above 4 MiB. Keep dispatching to serve other clients.
366Outgoing pipes are nonblocking and have two-second deadlines, with at most
367eight transfers retained. `wayland-clipboard-read` returns UTF-8 text or `#f`;
368external reads have the same size limit and a two-second deadline. Supported
369MIME types are `text/plain` and `text/plain;charset=utf-8`.
371Native embedders use `wayland-native-handle` with `native/wayland-bridge.h`.
372Acquire a reference before storing the handle and unref it after use. The
373bridge owns all protocol state. SHM presentation copies the supplied rows,
374then reports release on the compositor's buffer release, and frame completion
375on its frame callback. A rejected present owns no callback data. Teardown
376reports a pending frame as canceled and releases retained buffers exactly
377once; cancellation is never reported as presentation. Calls and callbacks
378belong to the same thread. Native buffers for an overlay are premultiplied
379ARGB8888; page buffers are XRGB8888.
381Native embedders can change child geometry in logical pixels, read the
382compositor's current XKB modifier masks and group, and observe a selection
383generation plus whether text is offered. Read these snapshots after UI
384dispatch. Geometry changes use the existing buffer retirement rules on the
385next present. The native include directory is exposed to direct dependents
386so 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.
389Compile it with the matching Sigil runtime headers/archive, the checked-in
390Wayland protocol include directories and `-D_GNU_SOURCE`, then run it in a
391private compositor. It checks release after replacement, compositor pacing,
392rejected presentation, cancellation before dispatch, and parent close when
393the final notification drops the child's last reference. It also checks final
394unref without close, connection failure before parent or child cleanup, a
395clipboard reader disappearing after a partial write, and an unread pipe
396reaching its transfer deadline. The Sigil bridge case also stops a real
397clipboard owner and checks that an incoming read times out and closes its
398pipe. Build the native fixture with
399`-fsanitize=address -fno-omit-frame-pointer` to check callback-driven teardown
400for memory errors; disable leak detection for the embedded runtime if needed.
401Run 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 go
406- **GPU rendering**: sigil-ui renders on the CPU into a canvas. A GPU
407 renderer would be a new renderer for the display list (next to
408 `(sigil ui display)`), drawing into a GPU image instead of a canvas. The
409 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 pair
411 inside the native present path. They pay off with a GPU renderer, or when
412 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 and
416 leave events like the pointer's, plus a way to start a drag from a
417 pointer press.
418- **IME**: `zwp_text_input_v3`, with preedit and commit events for a text
419 field and a call to report the cursor rectangle. Text fields would need a
420 preedit state in the tree. Compose and dead keys already work without it.
421- **Accessibility**: an AT-SPI tree built from the retained tree (element
422 roles, labels, focus) and published over D-Bus. It belongs above the
423 surface, beside `(sigil ui tree)`, since it describes elements, not
424 pixels.
426## Rendering rules
428- Text is a bitmap font per scale. Set bits write the color; clear bits and
429 spaces leave pixels as they are. A code point the font cannot draw is an
430 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 limits
438- No layout engine, no widget-level input handling, no animation clock.
439 The Wayland surface reports raw input; hit testing, focus order and timing
440 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 damaged
442 rectangle. That is linear in the item count and fine for hundreds of
443 items; a spatial index would be the next step.
444- Damage merging is quadratic in the number of rectangles. A scroll that
445 moves every line produces about two rectangles per line.