AtlatestRepositorysigil-ui
1# sigil-ui
2
3Wayland windows support [named and image cursors](docs/wayland-cursors.md)
4through their owned connection. Named requests prefer compositor shapes;
5explicit theme/size configuration prefers optional library images. The loader
6combines theme, default and builtin fallback without identifying their origin.
7Applications select desktop theme preferences. Existing applications retain
8compositor-default behavior until making a cursor call.
9
10A retained-mode UI library for Sigil, with a software renderer and offscreen,
11Linux framebuffer, DRM, Wayland and macOS AppKit surfaces. It draws rectangles,
12bitmap text and alpha masks into XRGB8888 pixel buffers, and can save renders as
13PNG files.
15A view is a function from application state to an element tree. On each update,
16sigil-ui reconciles that description with the tree it retained from the previous
17frame, keeps unchanged display items and repaints damaged rectangles. Keys keep
18children's identity across reordering; components skip a subtree when their
19function and input are unchanged. Positions are explicit logical pixels, with
20integer scaling and named theme colors, fonts and images.
22## Install
24Requires Sigil 0.24.8. Add the registry dependency to your package's
25`dependencies` list, then run `sigil deps install`:
27```scheme
28(from-pkg name: "sigil/sigil-ui" version: "^0.2")
29```
31This release is 0.2.7; see [NEWS](NEWS.md) for changes.
33## Minimal example
35This draws a progress bar offscreen and saves it to `progress.png`:
37```scheme
38(import (sigil math)
39 (sigil ui raster)
40 (sigil ui theme)
41 (sigil ui tree)
42 (sigil ui png))
44(define theme
45 (make-theme
46 (list (cons 'background #x101820)
47 (cons 'accent #xEDBB45))
48 '()
49 '()))
51(define ui
52 (make-ui theme (make-canvas 320 80) 1 'background))
54(define (view progress)
55 (group 0 0
56 (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 a
63surface, multiply each coordinate by `ui-scale` and pass each rectangle with the
64canvas to `surface-present!`.
66## Renderer and surfaces
68The display list supports solid and blended rectangles, bitmap text, colored
69text runs, [grayscale outline text](docs/text.md) and alpha masks. Pixel loops,
70PNG encoding and device access are C; the retained tree, themes and display
71list are Sigil. Bitmap rendering needs no external graphics library. Outline
72text uses the shared `(sigil font)` interface and explicitly supplied font
73files. Native platform backends provide grayscale glyphs and metrics.
75`(sigil ui surface)` provides offscreen buffers, 32-bit XRGB8888 fbdev devices
76and Linux DRM dumb buffers. DRM master can be dropped and reacquired for display
77handoff; `surface-close!` with `keep-frame?: #t` preserves active scanout on
78Linux 6.8 or later. Hardware surfaces require access to the device.
80`(sigil ui wayland)` provides windows and fullscreen surfaces, keyboard and
81pointer events, resizing, integer buffer scaling and damage-aware presentation.
82It loads libwayland-client and libxkbcommon at runtime. Use a dynamically linked
83program for Wayland: a fully static musl executable cannot load those libraries.
84The 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 and
87macOS, including [title, clipboard, and acknowledged fullscreen services](docs/window-services.md).
88See [macOS support](docs/macos.md) for the drawing adapter, sigil-window's
89prebuilt Mac qualification packet, scheduler integration and remaining gates.
91## Popup chooser
93`(sigil ui chooser)` provides an immutable chooser model, a local keyboard
94adapter and a retained view. Applications supply stable item IDs, labels and
95values; the control handles focus, filtering, marks and selection display.
97```scheme
98(import (sigil ui chooser))
99(define choices
100 (make-chooser
101 (list (chooser-item 'first "First item" 1)
102 (chooser-item 'second "Second item" 2))
103 multiple?: #t
104 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```
110Single selection is the default and confirms the focused item. Multiple
111selection returns marked records in canonical model order, including marks
112hidden by filtering. Cancellation and accepted empty selection have distinct
113statuses. `chooser-set-items` preserves marks/focus by ID, removes vanished
114IDs and resolves acceptance against the current records. IDs must be unique
115and stable; equal labels and duplicate values are allowed. Applications must
116recheck selected resources before acting on them.
118`(chooser-item id label value selectable?: #f)` supplies a context row: it
119remains visible to filtering and layout but cannot be focused, marked or
120accepted. `chooser-item-selectable?` reports the flag; it defaults to `#t`
121for existing callers. Initial marks on context rows are refused. Changing a
122marked item to context through `chooser-set-items` clears its mark, so later
123ID reuse cannot inherit it. Movement skips context rows, including on wrap;
124an all-context list accepts an empty selection. The single-selection match
125count excludes context rows. `chooser-view` uses `context-color:` for their
126text and leaves their mark column blank in multiple-selection mode.
128`chooser-key` accepts a shared UI key event while the chooser owns focus.
129Control-Space toggles, Up/Down or Control-p/n moves focus, Alt-a marks matching
130rows, Alt-u clears every mark, Return confirms, and Escape cancels. Printable
131text, including spaces, filters; Backspace removes the final query character.
132These keys require exact modifiers. Only press events act; releases and repeats are ignored. An `action-for-key:`
133callback overrides the local action map without an application mode dependency.
134The default filter matches case-insensitive label substrings; `matches?:`
135can supply application-specific matching.
137`chooser-view` takes the chooser, theme and logical width, with optional
138`max-rows:`, `font:` and color values. It keeps focus visible, clips labels
139using theme measurements, keys rows by stable ID, and shows total/hidden
140selection counts. Render it with the ordinary retained tree. The application
141owns the popup surface, query prompt, focus transfer and action policy.
142Font coverage follows the selected shared text path; the chooser does not
143replace missing characters in the stored labels.
145## Development and status
147Version 0.2 is an early API and may change. Layout, input handling and animation
148timing belong to the application. Fonts may be supplied bitmap fonts or
149explicit Regular/Bold outline faces. The text API does not include a shaping
150engine. Native fractional scaling, GPU rendering, drag and drop, IME and
151accessibility support remain outside this release.
153```sh
154sigil deps install
155sigil build
156sigil test
157cd bench
158sigil deps install
159sigil build --config release
160./build/release/bin/sigil-ui-bench
161```
163The benchmark normally uses the published library. For local changes, use Sigil
164dependency redirects for `sigil/sigil-ui` to your checkout.
165The benchmark and demo generate their own untracked locks on installation, so
166they don't pin an older archive of this repository inside the package itself.
168The 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 bitmap
170fonts under their [own license](demo/assets/spleen-LICENSE).
172The default suite needs no display or installed fonts. Outline-text tests use
173the checked-in OFL fixtures and SHA-256 manifest in
174[test/fixtures](test/fixtures/README.md); `SIGIL_UI_TEST_REGULAR` and
175`SIGIL_UI_TEST_BOLD` are optional path overrides. On Linux,
176`sigil scripts/test-discovery-error.sgl` also checks file fallback when loading
177Fontconfig fails. Additional checks are
178`sigil scripts/check-surface-close.sgl` (GCC and libdrm through Guix),
179`sigil scripts/test-wayland-configure.sgl` (a C compiler, wayland-scanner and
180Wayland server development files), and `test/wayland/run` (headless sway,
181swaymsg, grim and a C compiler). The live tests start their own compositor.
183Native embedders can opt into linux-dmabuf v4 surface feedback through
184`native/wayland-bridge.h`. Ordinary SHM surfaces never bind the optional
185global. Enabling is asynchronous: dispatch the existing connection, check
186pending/ready/invalid/unavailable status, then acquire a snapshot. Its copied
187data preserves tranche preference, raw target devices, flags and exact
188format/modifier pairs. Device IDs are metadata, not device-selection policy.
190Snapshots are immutable and independently reference counted on the owner
191thread. They remain readable through table replacement, later updates,
192capability removal and surface teardown. Partial updates retain the last
193completed snapshot; an invalid completed update revokes new acquisition
194until a valid batch arrives. Check status/generation before choosing current
195formats. Closing a surface makes its status unavailable and generation zero;
196already acquired snapshots retain their original generation and contents.
197No descriptors or mappings escape into snapshots. Parsing is bounded to a
1981-MiB table, 64 tranches and 4,096 resolved format entries per update; malformed
199or larger updates become invalid without failing the SHM connection. This
200API does not import GPU buffers or choose synchronization/fallback policy.
202The owned socketpair fixture requires no compositor or GPU. With matching
203Sigil runtime headers and archive already available, run its plain and
204ASan/UBSan controls using a C compiler with those sanitizers:
206```sh
207CC=cc sigil scripts/check-dmabuf-feedback.sgl /path/to/runtime/include build/dev/native/libsigil.a /tmp/feedback-checks
208```
210The controls cover opt-in binding, absent/legacy globals, atomic updates,
211replacement/reused tables, invalid lengths/indices/devices/duplicates, bounds,
212recovery, global removal, retained readers and descriptor cleanup. Existing
213Wayland live tests continue to exercise SHM rendering, input and clipboard.
214`wayland-set-title!` updates a live toplevel's metadata without presenting or
215committing its surface. It returns false for an identical title and rejects
216embedded NUL, text longer than 4095 UTF-8 bytes, subsurfaces and closed handles.
217The owned-compositor `test/wayland/title.sgl` checks the compositor's title and
218client trace, including duplicate suppression and unchanged surface commits.
219`open-wayland-surface` also accepts `server-decorations?: #t` for a toplevel.
220It requests server mode before the initial commit and waits for its configure
221before allowing a buffer. `wayland-decoration-mode` reports the compositor's
222chosen `server-side`/`client-side` mode, or false when not negotiated. Ordinary
223opens do not bind xdg-decoration. The owned `test/wayland/decoration.sgl` covers
224server mode, unchanged defaults, protocol absence and preference validation.
226`(wayland-activate! surface (getenv "XDG_ACTIVATION_TOKEN"))` submits a
227compositor-issued token for a live toplevel. It returns `#t` when the request
228is submitted. The compositor decides whether to focus the window. An omitted,
229`#f`, empty, or invalid token returns `#f`, as does an unavailable activation
230protocol. 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 true
233result means sent; `wayland-surface-fullscreen?` and `(fullscreen on?)` events
234change only after the compositor's configure. Child/layer roles refuse the
235request, and closed surfaces remain errors. The native bridge exposes the same
236request and confirmed state for embedders. The owned fullscreen control checks
237both transitions and the state before dispatching the compositor's answer.
239`sui_wayland_dmabuf_import` adds asynchronous import ownership, without
240attaching buffers. The caller supplies negotiated format/modifier/plane
241layout, retains its original descriptors and observes pending/ready/failed/
242canceled status through an opaque reference-counted handle. Metadata checks
243do not establish that a GPU or compositor supports a layout. The connection
244allows at most 64 live handles. Each plane's span must fit in 32 bits and
245lie within its DMA-BUF's real size, which the kernel reports through
246`lseek(SEEK_END)`; the first plane's offset + stride * height must fit too.
247These are the compositor's own import checks, so a refused layout fails
248locally instead of ending the connection with a protocol error.
249Canceling or dropping a pending handle keeps
250a bounded private listener until its terminal reply or connection close,
251then destroys any late-created buffer. Parent close cancels surviving
252handles; child close leaves connection-owned imports intact. No dispatch or
253wait happens inside create/cancel/unref. Presentation and fences are separate.
255Run `scripts/check-dmabuf-import.sgl` with the same header/archive/evidence
256arguments as the feedback harness. Its plain and sanitizer controls use
257owned wire peers and memfd descriptors, check transport/cancellation/cleanup,
258and require zero surface attachments. They do not qualify hardware import.
260`sui_wayland_present_dmabuf` submits a ready same-connection import to a child
261whose current device-pixel dimensions match it exactly. Frame pacing and
262buffer reuse are independent: child close cancels a pending frame, while a
263submitted import remains alive until real compositor release. Canceling or
264dropping a busy handle cannot destroy its buffer early. Its release callback
265reports 1 for actual release, or 0 only after connection teardown disconnects;
266the latter requires retiring the producer, not reusing its allocation. The
267producer must already meet implicit synchronization requirements; this call
268does not wait for rendering fences. `scripts/check-dmabuf-present.sgl` runs
269owned-wire plain/sanitizer ordering, refusal and teardown controls with the
270same arguments as the other native harnesses. Hardware pixels and fences need
271their own qualification before an embedder enables GPU presentation.
273An embedder can gate an idle ready import with
274`sui_wayland_dmabuf_import_fence`: it borrows a producer fence FD, keeps a
275private CLOEXEC duplicate and advances readiness in the existing GUI
276dispatcher. The monotonic timeout is bounded to five seconds. Pending,
277failed or timed-out waits reject presentation; every terminal path closes
278the duplicate. Errors and cancellation do not authorize producer reuse.
279This readiness wait uses implicit synchronization and enables no explicit
280sync protocol. `scripts/check-dmabuf-fence.sgl` uses owned pipes to check
281readiness, delayed progress alongside Wayland dispatch, errors/deadlines,
282the full 64-handle poll set and cancellation/teardown FD ownership. Those
283controls do not qualify real GPU sync files.
285A completion callback may close the parent and drop its final handle
286references. Close becomes visible immediately, but connection teardown and
287disconnect wait until the outermost GUI dispatch or child teardown unwinds,
288including nested dispatch. Presentation controls exercise this from real frame and release
289listeners with sanitizers, so libwayland never resumes on a freed display.
291See [the design document](docs/design.md) for reconciliation rules, the module
292map and benchmark measurements. Licensed under [BSD-3-Clause](LICENSE).