AtlatestRepositorysigil-ui
1
# sigil-ui3
Wayland windows support [named and image cursors](docs/wayland-cursors.md)4
through their owned connection. Named requests prefer compositor shapes;5
explicit theme/size configuration prefers optional library images. The loader6
combines theme, default and builtin fallback without identifying their origin.7
Applications select desktop theme preferences. Existing applications retain8
compositor-default behavior until making a cursor call.10
A retained-mode UI library for Sigil, with a software renderer and offscreen,11
Linux framebuffer, DRM, Wayland and macOS AppKit surfaces. It draws rectangles,12
bitmap text and alpha masks into XRGB8888 pixel buffers, and can save renders as13
PNG files.15
A view is a function from application state to an element tree. On each update,16
sigil-ui reconciles that description with the tree it retained from the previous17
frame, keeps unchanged display items and repaints damaged rectangles. Keys keep18
children's identity across reordering; components skip a subtree when their19
function and input are unchanged. Positions are explicit logical pixels, with20
integer scaling and named theme colors, fonts and images.22
## Install24
Requires Sigil 0.24.8. Add the registry dependency to your package's25
`dependencies` list, then run `sigil deps install`:27
```scheme28
(from-pkg name: "sigil/sigil-ui" version: "^0.2")29
```31
This release is 0.2.7; see [NEWS](NEWS.md) for changes.33
## Minimal example35
This draws a progress bar offscreen and saves it to `progress.png`:37
```scheme38
(import (sigil math)39
(sigil ui raster)40
(sigil ui theme)41
(sigil ui tree)42
(sigil ui png))44
(define theme45
(make-theme46
(list (cons 'background #x101820)47
(cons 'accent #xEDBB45))48
'()49
'()))51
(define ui52
(make-ui theme (make-canvas 320 80) 1 'background))54
(define (view progress)55
(group 0 056
(list (rect 20 30 (quotient (* 280 progress) 100) 20 'accent))))58
(ui-update! ui (view 50))59
(write-png! "progress.png" (ui-canvas ui))60
```62
`ui-update!` returns damaged rectangles in logical pixels. To present them on a63
surface, multiply each coordinate by `ui-scale` and pass each rectangle with the64
canvas to `surface-present!`.66
## Renderer and surfaces68
The display list supports solid and blended rectangles, bitmap text, colored69
text runs, [grayscale outline text](docs/text.md) and alpha masks. Pixel loops,70
PNG encoding and device access are C; the retained tree, themes and display71
list are Sigil. Bitmap rendering needs no external graphics library. Outline72
text uses the shared `(sigil font)` interface and explicitly supplied font73
files. Native platform backends provide grayscale glyphs and metrics.75
`(sigil ui surface)` provides offscreen buffers, 32-bit XRGB8888 fbdev devices76
and Linux DRM dumb buffers. DRM master can be dropped and reacquired for display77
handoff; `surface-close!` with `keep-frame?: #t` preserves active scanout on78
Linux 6.8 or later. Hardware surfaces require access to the device.80
`(sigil ui wayland)` provides windows and fullscreen surfaces, keyboard and81
pointer events, resizing, integer buffer scaling and damage-aware presentation.82
It loads libwayland-client and libxkbcommon at runtime. Use a dynamically linked83
program for Wayland: a fully static musl executable cannot load those libraries.84
The application owns the event loop; see [the demo](demo/src/demo/main.sgl).86
`(sigil ui window)` provides the common window and input interface on Linux and87
macOS, including [title, clipboard, and acknowledged fullscreen services](docs/window-services.md).88
See [macOS support](docs/macos.md) for the drawing adapter, sigil-window's89
prebuilt Mac qualification packet, scheduler integration and remaining gates.91
## Popup chooser93
`(sigil ui chooser)` provides an immutable chooser model, a local keyboard94
adapter and a retained view. Applications supply stable item IDs, labels and95
values; the control handles focus, filtering, marks and selection display.97
```scheme98
(import (sigil ui chooser))99
(define choices100
(make-chooser101
(list (chooser-item 'first "First item" 1)102
(chooser-item 'second "Second item" 2))103
multiple?: #t104
selected: '(first)))105
(define accepted (chooser-action choices 'confirm))106
;; status: is accepted, canceled or pending; items: is the accepted list.107
;; state: is the next immutable chooser, including after keyboard input.108
```110
Single selection is the default and confirms the focused item. Multiple111
selection returns marked records in canonical model order, including marks112
hidden by filtering. Cancellation and accepted empty selection have distinct113
statuses. `chooser-set-items` preserves marks/focus by ID, removes vanished114
IDs and resolves acceptance against the current records. IDs must be unique115
and stable; equal labels and duplicate values are allowed. Applications must116
recheck selected resources before acting on them.118
`(chooser-item id label value selectable?: #f)` supplies a context row: it119
remains visible to filtering and layout but cannot be focused, marked or120
accepted. `chooser-item-selectable?` reports the flag; it defaults to `#t`121
for existing callers. Initial marks on context rows are refused. Changing a122
marked item to context through `chooser-set-items` clears its mark, so later123
ID reuse cannot inherit it. Movement skips context rows, including on wrap;124
an all-context list accepts an empty selection. The single-selection match125
count excludes context rows. `chooser-view` uses `context-color:` for their126
text and leaves their mark column blank in multiple-selection mode.128
`chooser-key` accepts a shared UI key event while the chooser owns focus.129
Control-Space toggles, Up/Down or Control-p/n moves focus, Alt-a marks matching130
rows, Alt-u clears every mark, Return confirms, and Escape cancels. Printable131
text, including spaces, filters; Backspace removes the final query character.132
These keys require exact modifiers. Only press events act; releases and repeats are ignored. An `action-for-key:`133
callback overrides the local action map without an application mode dependency.134
The default filter matches case-insensitive label substrings; `matches?:`135
can supply application-specific matching.137
`chooser-view` takes the chooser, theme and logical width, with optional138
`max-rows:`, `font:` and color values. It keeps focus visible, clips labels139
using theme measurements, keys rows by stable ID, and shows total/hidden140
selection counts. Render it with the ordinary retained tree. The application141
owns the popup surface, query prompt, focus transfer and action policy.142
Font coverage follows the selected shared text path; the chooser does not143
replace missing characters in the stored labels.145
## Development and status147
Version 0.2 is an early API and may change. Layout, input handling and animation148
timing belong to the application. Fonts may be supplied bitmap fonts or149
explicit Regular/Bold outline faces. The text API does not include a shaping150
engine. Native fractional scaling, GPU rendering, drag and drop, IME and151
accessibility support remain outside this release.153
```sh154
sigil deps install155
sigil build156
sigil test157
cd bench158
sigil deps install159
sigil build --config release160
./build/release/bin/sigil-ui-bench161
```163
The benchmark normally uses the published library. For local changes, use Sigil164
dependency redirects for `sigil/sigil-ui` to your checkout.165
The benchmark and demo generate their own untracked locks on installation, so166
they don't pin an older archive of this repository inside the package itself.168
The demo also uses the registry package. From `demo/`, run `sigil deps install`,169
`sigil build`, then `./build/dev/bin/sigil-ui-demo`. It includes Spleen bitmap170
fonts under their [own license](demo/assets/spleen-LICENSE).172
The default suite needs no display or installed fonts. Outline-text tests use173
the checked-in OFL fixtures and SHA-256 manifest in174
[test/fixtures](test/fixtures/README.md); `SIGIL_UI_TEST_REGULAR` and175
`SIGIL_UI_TEST_BOLD` are optional path overrides. On Linux,176
`sigil scripts/test-discovery-error.sgl` also checks file fallback when loading177
Fontconfig fails. Additional checks are178
`sigil scripts/check-surface-close.sgl` (GCC and libdrm through Guix),179
`sigil scripts/test-wayland-configure.sgl` (a C compiler, wayland-scanner and180
Wayland server development files), and `test/wayland/run` (headless sway,181
swaymsg, grim and a C compiler). The live tests start their own compositor.183
Native embedders can opt into linux-dmabuf v4 surface feedback through184
`native/wayland-bridge.h`. Ordinary SHM surfaces never bind the optional185
global. Enabling is asynchronous: dispatch the existing connection, check186
pending/ready/invalid/unavailable status, then acquire a snapshot. Its copied187
data preserves tranche preference, raw target devices, flags and exact188
format/modifier pairs. Device IDs are metadata, not device-selection policy.190
Snapshots are immutable and independently reference counted on the owner191
thread. They remain readable through table replacement, later updates,192
capability removal and surface teardown. Partial updates retain the last193
completed snapshot; an invalid completed update revokes new acquisition194
until a valid batch arrives. Check status/generation before choosing current195
formats. Closing a surface makes its status unavailable and generation zero;196
already acquired snapshots retain their original generation and contents.197
No descriptors or mappings escape into snapshots. Parsing is bounded to a198
1-MiB table, 64 tranches and 4,096 resolved format entries per update; malformed199
or larger updates become invalid without failing the SHM connection. This200
API does not import GPU buffers or choose synchronization/fallback policy.202
The owned socketpair fixture requires no compositor or GPU. With matching203
Sigil runtime headers and archive already available, run its plain and204
ASan/UBSan controls using a C compiler with those sanitizers:206
```sh207
CC=cc sigil scripts/check-dmabuf-feedback.sgl /path/to/runtime/include build/dev/native/libsigil.a /tmp/feedback-checks208
```210
The controls cover opt-in binding, absent/legacy globals, atomic updates,211
replacement/reused tables, invalid lengths/indices/devices/duplicates, bounds,212
recovery, global removal, retained readers and descriptor cleanup. Existing213
Wayland live tests continue to exercise SHM rendering, input and clipboard.214
`wayland-set-title!` updates a live toplevel's metadata without presenting or215
committing its surface. It returns false for an identical title and rejects216
embedded NUL, text longer than 4095 UTF-8 bytes, subsurfaces and closed handles.217
The owned-compositor `test/wayland/title.sgl` checks the compositor's title and218
client trace, including duplicate suppression and unchanged surface commits.219
`open-wayland-surface` also accepts `server-decorations?: #t` for a toplevel.220
It requests server mode before the initial commit and waits for its configure221
before allowing a buffer. `wayland-decoration-mode` reports the compositor's222
chosen `server-side`/`client-side` mode, or false when not negotiated. Ordinary223
opens do not bind xdg-decoration. The owned `test/wayland/decoration.sgl` covers224
server mode, unchanged defaults, protocol absence and preference validation.226
`(wayland-activate! surface (getenv "XDG_ACTIVATION_TOKEN"))` submits a227
compositor-issued token for a live toplevel. It returns `#t` when the request228
is submitted. The compositor decides whether to focus the window. An omitted,229
`#f`, empty, or invalid token returns `#f`, as does an unavailable activation230
protocol. Tokens must be valid UTF-8, at most 1024 bytes, and contain no NUL.232
`wayland-set-fullscreen!` sends an asynchronous xdg-toplevel request. Its true233
result means sent; `wayland-surface-fullscreen?` and `(fullscreen on?)` events234
change only after the compositor's configure. Child/layer roles refuse the235
request, and closed surfaces remain errors. The native bridge exposes the same236
request and confirmed state for embedders. The owned fullscreen control checks237
both transitions and the state before dispatching the compositor's answer.239
`sui_wayland_dmabuf_import` adds asynchronous import ownership, without240
attaching buffers. The caller supplies negotiated format/modifier/plane241
layout, retains its original descriptors and observes pending/ready/failed/242
canceled status through an opaque reference-counted handle. Metadata checks243
do not establish that a GPU or compositor supports a layout. The connection244
allows at most 64 live handles. Each plane's span must fit in 32 bits and245
lie within its DMA-BUF's real size, which the kernel reports through246
`lseek(SEEK_END)`; the first plane's offset + stride * height must fit too.247
These are the compositor's own import checks, so a refused layout fails248
locally instead of ending the connection with a protocol error.249
Canceling or dropping a pending handle keeps250
a bounded private listener until its terminal reply or connection close,251
then destroys any late-created buffer. Parent close cancels surviving252
handles; child close leaves connection-owned imports intact. No dispatch or253
wait happens inside create/cancel/unref. Presentation and fences are separate.255
Run `scripts/check-dmabuf-import.sgl` with the same header/archive/evidence256
arguments as the feedback harness. Its plain and sanitizer controls use257
owned wire peers and memfd descriptors, check transport/cancellation/cleanup,258
and require zero surface attachments. They do not qualify hardware import.260
`sui_wayland_present_dmabuf` submits a ready same-connection import to a child261
whose current device-pixel dimensions match it exactly. Frame pacing and262
buffer reuse are independent: child close cancels a pending frame, while a263
submitted import remains alive until real compositor release. Canceling or264
dropping a busy handle cannot destroy its buffer early. Its release callback265
reports 1 for actual release, or 0 only after connection teardown disconnects;266
the latter requires retiring the producer, not reusing its allocation. The267
producer must already meet implicit synchronization requirements; this call268
does not wait for rendering fences. `scripts/check-dmabuf-present.sgl` runs269
owned-wire plain/sanitizer ordering, refusal and teardown controls with the270
same arguments as the other native harnesses. Hardware pixels and fences need271
their own qualification before an embedder enables GPU presentation.273
An embedder can gate an idle ready import with274
`sui_wayland_dmabuf_import_fence`: it borrows a producer fence FD, keeps a275
private CLOEXEC duplicate and advances readiness in the existing GUI276
dispatcher. The monotonic timeout is bounded to five seconds. Pending,277
failed or timed-out waits reject presentation; every terminal path closes278
the duplicate. Errors and cancellation do not authorize producer reuse.279
This readiness wait uses implicit synchronization and enables no explicit280
sync protocol. `scripts/check-dmabuf-fence.sgl` uses owned pipes to check281
readiness, delayed progress alongside Wayland dispatch, errors/deadlines,282
the full 64-handle poll set and cancellation/teardown FD ownership. Those283
controls do not qualify real GPU sync files.285
A completion callback may close the parent and drop its final handle286
references. Close becomes visible immediately, but connection teardown and287
disconnect wait until the outermost GUI dispatch or child teardown unwinds,288
including nested dispatch. Presentation controls exercise this from real frame and release289
listeners with sanitizers, so libwayland never resumes on a freed display.291
See [the design document](docs/design.md) for reconciliation rules, the module292
map and benchmark measurements. Licensed under [BSD-3-Clause](LICENSE).