Goldberry
A fast and modern UI toolkit for Java 25. A window is three lines, a screen is a KDL file that reloads while it runs, and the same application ships as a jar on any JDK or as one native binary with GraalVM.
Goldberry is a declarative desktop UI toolkit written in pure Java over a small
set of native C libraries, bound through the Foreign Function & Memory API.
There is no JNI, no bundled web engine and no wrapping of platform widgets.
Widgets are immutable records with a pure build(), or the same tree as KDL
markup. They are styled with a real CSS subset and laid out by flexbox. Frames
are rasterized on the CPU, and presented through the GPU when the optional GPU
module is present. Linux, Windows and macOS are peer platforms behind one
backend.

The showcase's Buttons screen. Every card shows one section of this guide and links to it.
Where to start
The shape of an application
A model is plain Java. A screen is markup that names the model’s values and actions. A stylesheet gives the screen its look. The application class joins the three and owns the window.
@Model
public final class Settings {
@Bind("app.gain") private Number gain = 40;
@Actions
public record Commands(Settings values) {
@Action("app.set-gain") public void setGain(double gain) { values.gain = gain; }
}
}
column id="settings" {
text class="heading" "Volume"
slider min=0 max=100 step=5 bind="app.gain" change="app.set-gain"
}
public final class Hello implements Application {
private final Settings settings = new Settings();
private final Settings.Commands actions = new Settings.Commands(settings);
@Override public List<Object> models() { return List.of(settings, actions); }
@Override public Widget root() {
return Widgets.inflater(actions, settings)
.inflate(KdlParser.resource(Hello.class, "settings.kdl").getFirst());
}
@Override public List<Stylesheet> stylesheets() {
return Controls.stylesheets(Theme.NORD_DARK);
}
public static void main(String[] args) {
Goldberry.launch(new Hello(), args);
}
}
Moving the slider calls setGain. Assigning the field notifies the slider and
asks the window for a frame. Nothing in the application repaints, subscribes or
registers a listener. Building an application explains each
part.
Status
This guide covers Goldberry 2026.3. See the
changelog
for changes and migration steps.
Important
There is no screen-reader support on any platform. The rest of the accessibility baseline is in place: keyboard reachability, a focus ring, WCAG AA contrast, hit targets, reduced motion and text scale. Limitations lists the rest.
About this book
The guide has six parts. The decision log on GitHub is the project’s memory: one record per significant choice, with the forces, the alternatives and the costs. Every page has an edit this page link to its source on GitHub.
Concept
Goldberry draws every pixel itself, describes a screen as data, and keeps the native code behind one boundary. This page is the idea in five parts and what each one buys.
One rendering pipeline, everywhere
Goldberry does not wrap the platform’s widgets and does not embed a browser. A button on Linux, Windows and macOS is the same button: the same CSS rule, the same Yoga layout, the same Blend2D rasterization, the same HarfBuzz-shaped text in the same embedded fonts. The platform supplies a window, input events, the clipboard and a surface to present into, through SDL3. Everything above that line is Java and runs identically on every desktop.
The result is deterministic. A frame is the same bytes on every machine, so an application can test itself with golden images.
A screen is a description
A widget is an immutable Java record with a pure build(). The toolkit calls
build(), diffs the result against the element tree it kept from the last
frame, and updates only what changed. State that must survive a rebuild, a hover
or a caret, lives on the element rather than on the widget.
The same tree can be written as KDL markup, and every built-in widget exists three ways: a record, a node name and a CSS type.
row id="confirm" {
spacer
button press="dismiss" "Cancel"
button class="danger" press="delete" "Delete"
}
new Row(
new Spacer(),
new Button("Cancel", this::dismiss),
new Button("Delete", this::delete).styled("danger")
)
Markup names things and never contains code. A press= names an action, a
bind= names a value, an icon= names an icon. Each resolves against a
registry the application supplied, and a name that resolves to nothing fails
when the document is inflated rather than when the user clicks.
Data flows down, events flow up
A control never owns its value. It is handed an Observable and draws what it
reads. When the user acts, the control raises an action, the application’s
handler assigns a field, and the new value flows back down. A checkbox whose
tick will not move is a handler that did not change the state, which is where
the bug is.
The model is plain Java: a class of fields marked @Bind, and methods marked
@Action. On the JVM the toolkit binds them reflectively at run time. For a
native image a build step rewrites the compiled class so that every assignment
notifies directly, with no reflection anywhere.
Ahead-of-time binding is the whole story.
Real CSS, real flexbox
Styling is a genuine subset of CSS: selectors, the cascade in layers, custom properties, inheritance, transitions on a frame clock, transforms and opacity. Layout is flexbox, through Yoga bound directly rather than reimplemented.
Every colour a control uses is a --gb-* token, so switching from the Nord
dark theme to the Nord light one restyles every control though no rule names a
colour. Density is three tokens on :root. Markup and stylesheets hot-reload
while the application runs (Styling).
Light to ship
The core runtime uses SLF4J for logging and FFM for native calls. The desktop library ships as a classifier jar per target. Optional media and SVG modules have their own native libraries, and the spelling provider uses Lucene.
An application runs on a JDK 25 or newer, or compiles with GraalVM into an executable that carries its native libraries. Native image
What it is built on
| Library | Role | Where it lives |
|---|---|---|
| Blend2D | 2D rasterization, with its PNG, JPEG and QOI codecs | inside libgoldberry |
| Yoga | flexbox layout | inside libgoldberry |
| HarfBuzz | text shaping | inside libgoldberry |
| SDL3 | windows, input, clipboard, popups, tray, SDL_GPU | inside libgoldberry |
| md4c | Markdown parsing | inside libgoldberry |
| libwebp | WebP decoding | inside libgoldberry |
| dav1d, libvpx, Opus, Vorbis, FLAC, minimp3, Theora and libyuv | audio and video decoding and conversion | goldberry-media, in one libgoldberry-media |
| ThorVG | SVG rasterization | goldberry-vector, in libgoldberry-vector |
| Lucene Hunspell | spelling dictionaries | optional goldberry-spell |
| Inter, JetBrains Mono | the UI and code typefaces | inside goldberry-core |
| Lucide | 1,870 icons as path data | inside goldberry-core |
| Noto Color Emoji | the emoji face | goldberry-emoji |
Everything in the table is open source, and the licences travel inside every
jar under META-INF/.
Read next
Architecture
Five layers, three trees and one native boundary. This page is the map an application developer needs. The design document in the repository has the rest.
The whole design is in
docs/ARCHITECTURE.md,
with the design system and the per-widget contracts beside it. This page is
the summary.
The layers

The layers. The application writes the top lane and only the bottom lane touches the platform.
The application writes the top row. Everything below it is the toolkit, and only the bottom row touches the platform.
The three trees
The widget layer follows Flutter’s model:
| Tree | Owned by | Lifetime | Holds |
|---|---|---|---|
| Widgets | the application | one build | an immutable description: a record with a pure build() |
| Elements | the toolkit | across rebuilds | state, the subscription a bind= made, who is hovered, focused or pressed |
| Render objects | the toolkit | across frames | a Yoga node, the box last applied to it, where it was painted |
A rebuild produces a new widget tree. The element tree is reconciled against it by type and key, so a parent re-describing its child does not lose the child’s state. The render tree is reconciled against the boxes the elements produce, and every Yoga setter is guarded by a comparison, so a frame in which nothing changed costs a few microseconds.
The frame loop
One UI thread runs the loop. Blend2D’s workers rasterize in bands beside it.

One frame, in order. Each stage touches only what changed.
Three properties of the loop shape what an application sees:
- It is idle when nothing moves. A frame is asked for by a value that
changed, a
setState, a transition in flight, or a widget that says it is animating. Nothing polls. - Hit testing reads the painted frame. A pointer event is about what the user can see, so dispatch runs against the snapshot taken while painting rather than a fresh layout.
- Only the damage is repainted, where the backend promises the buffer it lends back still holds the last frame.
Performance has the numbers for each stage.
The native boundary
Every C function the toolkit calls is bound by hand in one module,
dev.goldberry.natives, and no raw MemorySegment leaves it. A bound function
is a holder class whose method handle is a compile-time constant, which is what
makes a call cheap on the JVM and in a native image alike.
A layout probe checks every struct layout and constant against the compiled
library at run time, on every platform, so a long that is 32 bits on Windows
is caught before it is read.
The libraries are statically linked into one libgoldberry per platform by a
CMake superbuild. Four artifacts exist: linux-x64, linux-aarch64,
macos-aarch64 and windows-x64.
The optional media and vector modules load separate libraries,
libgoldberry-media and libgoldberry-vector. Both use FFM and ship a
classifier for each supported target.
The backend SPI
The SPI is the only platform-facing interface. Two implementations exist and
the list is closed: sdl3 for every desktop, and headless, which renders to
memory for tests and servers.
| The SPI answers | How |
|---|---|
| a window | logical pixels in, physical raster out, per-monitor fractional scale |
| present | the platform lends a surface and Blend2D draws straight into it |
| input | pointer, wheel in lines, keys and committed text as separate events |
| a popup | a second window with an owner, which a video driver may refuse |
| the clipboard | text as a value, everything else as an offer by MIME type |
| the desktop’s theme | light, dark, or the desktop does not say |
| a tray icon, file dialogs, a GPU surface | optional, and absent where the platform has none |
Binding and weaving
A model is a class with @Bind fields and @Action methods. Two mechanisms
make an assignment observable, and they are interchangeable:
| On the JVM | In a native image | |
|---|---|---|
| mechanism | reflection over the annotations at run time | the compiled class rewritten at build time |
| build step | none | the weaver, one Gradle plugin or one Maven execution |
| a change notifies | at the next sweep | inside the assignment |
The same model, the same paths and the same refusals both ways. Ahead-of-time binding explains the mechanism and Native image what an image needs.
The modules
| Module | Artifact | What it holds |
|---|---|---|
:common | goldberry-common | logging and the start-up timeline, the lowest module |
:natives | goldberry-natives and four classifier jars | the FFM bindings and libgoldberry |
:core | goldberry-core | the engines and the contracts: the three trees, style, layout, text, icons, paint, the backend SPI |
:widgets | goldberry-widgets | the widget catalogue, charts included |
:html | goldberry-html | optional: Markdown and HTML as widgets |
:emoji | goldberry-emoji | optional: the Noto Color Emoji face |
:media | goldberry-media and natives-<target> classifiers | optional: audio and video |
:mic, :camera | goldberry-mic, goldberry-camera | optional: capture and monitoring |
:vector | goldberry-vector and natives-<target> classifiers | optional: SVG |
:spell | goldberry-spell | optional: Hunspell dictionaries |
:gpu | goldberry-gpu | optional: canvas3d and GPU composition |
:toolkit | goldberry | the umbrella an application depends on |
:bom | goldberry-bom | the version table |
:assets, :weaver and :example are build-time tools and the showcase. They
are not published. The module graph is enforced by JPMS and the modules
:common ← :natives ← :core ← :widgets are the spine.
Repository layout has the packages.
Read next
Limitations
What Goldberry does not do, in one place, and why.
The gaps below are the ones an application developer meets first.
Accessibility
| Gap | Why |
|---|---|
| Screen readers. Nothing on any platform reads the UI aloud | Every widget carries a role and an accessible name in a semantics tree, and no bridge connects that tree to a platform accessibility API |
The rest of the baseline is in place: every control is reachable by keyboard, the focus ring is drawn, contrast meets WCAG AA, hit targets are 32 pixels, reduced motion is honoured and text scales to 150%.
Platforms
| Gap | Why |
|---|---|
| Windows on ARM and macOS on Intel | Four native artifacts, not six. Both targets are a shrinking share of desktops |
| A web view on Wayland | A page is a child window placed over the widget’s box. Wayland allows neither reparenting a foreign surface nor placing a window where a widget is, so there the widget opens nothing and says why |
Text
| Gap | Why |
|---|---|
| Automatic hyphenation outside English | Only English patterns ship. Soft hyphens work in any language in document views |
| Native preedit in password fields | Password fields display the committed text through their mask |
Widgets and content
| Gap | Why |
|---|---|
| PDF and terminal widgets | The toolkit has no widgets for these formats |
Full browser features in html-view | The document view supports a restricted author stylesheet and delegates links and images to the application. Use the web view for a real browser engine |
| SVG text and external resources | SVG supports a self-contained drawing subset. Use SVG paths for text in an SVG |
| Dragging out under a headless backend | A drag outside the window needs the desktop’s drag service. See Dragging out of the window |
Styling and motion
| Gap | Why |
|---|---|
| Transitions on layout properties | Transitions change paint properties. An unsupported transition declaration produces a warning |
| CSS Grid and 3D transforms | Layout uses flexbox and CSS transforms are two-dimensional |
| Cursors from a stylesheet URL | Provide static cursor pictures through Application.cursors() |
Build and distribution
| Gap | Why |
|---|---|
| A Gradle plugin that picks the platform’s natives jar | A BOM knows versions, not platforms, and module-metadata variants cannot match a consumer that declares no operating system. An application adds the classifier jars itself |
| A Maven plugin for the weaver | exec-maven-plugin runs the weaver at process-classes, which is the phase for it (Ahead-of-time binding) |
By design
Some absences are the design rather than a gap:
- No hand-written platform backends and no AWT bridge. SDL3 is the desktop layer.
- No expressions in markup. A
bind=is a dotted path. Negation, formatting and conditionals stay in Java, where they are testable. - No
repaint()in an application. A value that changed asks for its own frame. - No global font or icon cache. A
Fontsbook and anIconsregistry are opened by the application and closed by it, because they hold native memory. - No mobile or touch profile. Desktop only.
Requirements
A JDK 25 and a desktop. Everything else is inside the jars.
To run an application
| Need | Detail |
|---|---|
| Java | JDK 25 or newer, any vendor. The toolkit uses the Foreign Function & Memory API, which is final in 25, and the Vector API for the blur path |
| A desktop | Linux on Wayland or X11, Windows, or macOS. Native libraries are built for linux-x64, linux-aarch64, macos-aarch64 and windows-x64 |
| On Linux | glibc 2.28 or newer. The Linux libraries are built in a manylinux_2_28 container, so RHEL 8 and anything younger loads them |
| A writable temporary directory | libgoldberry travels inside a jar and is unpacked to a temporary file on first use, because a shared object has to be a real file to be loaded. -Dgoldberry.native.library=<path> points at one already on disk, for a read-only or noexec temp |
| No GPU | Frames are rasterized on the CPU. With goldberry-gpu on the module path a window presents through the GPU where a device exists and on the CPU where it does not |
| Logging and optional engines | The toolkit uses SLF4J. Add a logging provider to see diagnostics. Optional modules can bring dependencies of their own |
Important
On macOS the UI thread must be the process’s first thread. Launch with
-XstartOnFirstThread. Without it the window fails to open with No available video device, which says nothing about threads.
What the desktop provides at run time
The native library opens the platform’s own libraries when it needs them, so a desktop that can show a window already has what a window needs. Two integrations are worth knowing about on Linux:
- Audio goes through the system’s sound server, or straight to the sound card where none runs. A machine with no audio device plays silently rather than failing.
- The desktop’s theme, file dialogs and input method are asked through the
desktop’s own services. A build of the toolkit says what it can ask through
Goldberry.capabilities(), so an application can tell this desktop has no such setting from this build cannot ask.
A web view needs the desktop’s own engine, WebKitGTK, WebView2 or WKWebView, through a separate optional library. It is never a load-time dependency of the toolkit.
To build a native binary
| Need | Detail |
|---|---|
| GraalVM | GraalVM Community for JDK 25, the 25.3 line. A stock JDK has no native-image |
| A C toolchain | native-image links with the system compiler. On Linux it also needs zlib’s development package: build-essential zlib1g-dev on Debian and Ubuntu, gcc glibc-devel zlib-devel libstdc++-static on Fedora. Without it the build runs for a minute and fails at the last step with cannot find -lz |
| Ahead-of-time binding | A build step over your compiled classes, one Gradle plugin or one Maven execution. Ahead-of-time binding explains why an image needs it and a jar does not |
To build the toolkit itself
Only if you are working on Goldberry. A JDK 25, CMake 3.28 or newer, Ninja and a C and C++ toolchain. The first native build downloads about 330 MB of upstream sources. Building from source has the details and the Java-only build that skips all of it.
Read next
Installing
Add the BOM for the version, the umbrella artifact for the toolkit, and one natives jar per platform you run on.
Every artifact is published under the group dev.goldberry. Versions are
calendar versions: 2026.1, 2026.2, 2026.2.1.
Note
The coordinates below are for Goldberry
2026.3. Development builds are available from the snapshot repository.
Gradle
repositories {
mavenCentral()
}
dependencies {
implementation platform('dev.goldberry:goldberry-bom:2026.3')
implementation 'dev.goldberry:goldberry' // common, natives, core and widgets
// The native library, one classifier per platform you run on.
runtimeOnly 'dev.goldberry:goldberry-natives::linux-x64'
runtimeOnly 'dev.goldberry:goldberry-natives::linux-aarch64'
runtimeOnly 'dev.goldberry:goldberry-natives::macos-aarch64'
runtimeOnly 'dev.goldberry:goldberry-natives::windows-x64'
}
Maven
<dependencyManagement>
<dependencies>
<dependency>
<groupId>dev.goldberry</groupId>
<artifactId>goldberry-bom</artifactId>
<version>2026.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>dev.goldberry</groupId>
<artifactId>goldberry</artifactId>
</dependency>
<dependency>
<groupId>dev.goldberry</groupId>
<artifactId>goldberry-natives</artifactId>
<classifier>linux-x64</classifier>
<scope>runtime</scope>
</dependency>
</dependencies>
Snapshots
Every push to master publishes a -SNAPSHOT of the next version, the
goldberryVersion in
gradle.properties,
to the Central Portal’s snapshot repository. To follow master, add the
repository and use that version with -SNAPSHOT:
repositories {
mavenCentral()
maven { url = 'https://central.sonatype.com/repository/maven-snapshots/' }
}
Which natives jars to add
The BOM knows versions and not platforms. A POM has no notion of an operating system, so the umbrella depends on the bindings jar without a classifier and the platform jars are yours to add.
Add all four. NativeLibrary picks the right one at run time from
os.name and os.arch, so the application runs on every machine it is built
or run on. The one-platform form is the one that goes wrong quietly, on a
developer building on macOS for an application that ships to Linux.
| Classifier | Platform |
|---|---|
linux-x64 | Linux, x86-64, glibc 2.28 or newer |
linux-aarch64 | Linux, 64-bit ARM |
macos-aarch64 | macOS on Apple silicon |
windows-x64 | Windows, x86-64 |
Optional modules
Use modules and classifiers from the same release or snapshot. For
goldberry-media or goldberry-vector, add a natives-<target> classifier
for each platform you support. Upgrade notes
| Artifact | Adds | Chapter |
|---|---|---|
goldberry-html | markdown-view and html-view | Markdown, HTML and the web |
goldberry-emoji | the Noto Color Emoji face, drawn from its paint graphs | Text, fonts and icons |
goldberry-gpu | GPU composition for every window, and canvas3d | The GPU canvas |
goldberry-media | media-player, video-view and audio-player, plus natives-<target> classifier jars for each platform | Audio and video |
goldberry-vector | SVG images and svg-view, plus a natives-<target> classifier | Drawing |
goldberry-camera | Camera capture and camera-view | Camera |
goldberry-mic | Microphone capture, level, waveform and spectrum | Microphone |
goldberry-spell | Optional spelling engine. Supply a dictionary for each language | Spell checking |
implementation 'dev.goldberry:goldberry-html'
implementation 'dev.goldberry:goldberry-media'
runtimeOnly 'dev.goldberry:goldberry-media::natives-linux-x64'
Logging
The toolkit logs through SLF4J and binds no implementation. Add one and the toolkit’s diagnostics appear. Add none and you get silence, SLF4J’s own no-provider warning included.
runtimeOnly 'ch.qos.logback:logback-classic:1.6.5'
The module path
Goldberry’s modules are named: dev.goldberry.core, dev.goldberry.widgets,
dev.goldberry.natives, and dev.goldberry.html, dev.goldberry.emoji,
dev.goldberry.media and dev.goldberry.gpu for the optional ones. An
application on the module path requires the two it uses and opens the
packages the toolkit reads at run time:
module com.example.app {
requires dev.goldberry.core;
requires dev.goldberry.widgets;
// The reflective binder reads @Bind fields here, and the parser reads the
// .kdl and .css resources beside them.
opens com.example.app to dev.goldberry.core;
}
Native access is granted to the one module that touches native code:
java --enable-native-access=dev.goldberry.natives --module-path lib --module com.example.app/com.example.app.Hello
The opens is for what the toolkit reads itself: markup, a
Stylesheet.resource, a FontSource.resource. A resource directory is a
package of its own, so fonts/ beside the class is com.example.app.fonts,
and that is the package to open. The stream forms,
FontSource.stream(…, () -> Hello.class.getResourceAsStream("fonts/Forum.ttf"))
and Stylesheet.stream(…), read the file with your own code and need no
opens at all (Text, fonts and icons).
The natives jars are modules too, one per platform:
dev.goldberry.natives.linux_x64, dev.goldberry.natives.linux_aarch64,
dev.goldberry.natives.macos_aarch64 and dev.goldberry.natives.windows_x64.
They stay on the module path beside everything else. Nothing has to require
them: the library is found there by name.
An application on the class path needs no opens and grants
--enable-native-access=ALL-UNNAMED instead.
Read next
Your first Java application
A counter: a model with one value and one action, a document that names them, a stylesheet, and the application class that opens the window. About sixty lines, and no listener anywhere.
The finished project is six files:
hello/
├── build.gradle
├── settings.gradle
└── src/main/
├── java/
│ ├── module-info.java
│ └── com/example/hello/
│ ├── Counter.java the values and the actions
│ └── Hello.java the application
└── resources/com/example/hello/
├── hello.kdl the screen
└── hello.css its look
Create the build. The application plugin runs the program on the module
path and passes the one JVM flag native access needs. On macOS the UI thread
has to be the first thread, so the second flag is added there.
plugins {
id 'java'
id 'application'
}
java {
toolchain { languageVersion = JavaLanguageVersion.of(25) }
}
repositories {
mavenCentral()
}
dependencies {
implementation platform('dev.goldberry:goldberry-bom:2026.3')
implementation 'dev.goldberry:goldberry'
runtimeOnly 'dev.goldberry:goldberry-natives::linux-x64'
runtimeOnly 'dev.goldberry:goldberry-natives::linux-aarch64'
runtimeOnly 'dev.goldberry:goldberry-natives::macos-aarch64'
runtimeOnly 'dev.goldberry:goldberry-natives::windows-x64'
}
application {
mainModule = 'com.example.hello'
mainClass = 'com.example.hello.Hello'
applicationDefaultJvmArgs = ['--enable-native-access=dev.goldberry.natives']
if (System.getProperty('os.name').toLowerCase().contains('mac')) {
applicationDefaultJvmArgs += '-XstartOnFirstThread'
}
}
settings.gradle is one line: rootProject.name = 'hello'.
Declare the module. Two requires, and one opens so the toolkit can read
the model’s fields and the resources beside it.
module com.example.hello {
requires dev.goldberry.core;
requires dev.goldberry.widgets;
opens com.example.hello to dev.goldberry.core;
}
Write the model. A class of fields marked @Bind, with the actions nested
inside it as a record. Assigning a field is what notifies the window, so there
is no setter to call and no event to raise.
package com.example.hello;
import dev.goldberry.bind.Action;
import dev.goldberry.bind.Actions;
import dev.goldberry.bind.Bind;
import dev.goldberry.bind.Model;
@Model
public final class Counter {
@Bind("counter.label") private String label = "Pressed 0 times";
private int presses;
@Actions
public record Commands(Counter values) {
@Action("counter.press")
public void press() {
values.presses++;
values.label = "Pressed " + values.presses + (values.presses == 1 ? " time" : " times");
}
@Action("counter.reset")
public void reset() {
values.presses = 0;
values.label = "Pressed 0 times";
}
}
}
The record is called Commands and not Actions: a nested type named
Actions would shadow the annotation
(Building an application).
Write the screen. The document names the value with bind= and the
actions with press=. The text after bind= is what a preview shows when
nothing is bound.
column id="hello" {
text class="heading" "Hello, Goldberry"
text id="count" bind="counter.label" "Pressed 0 times"
row id="buttons" {
button class="primary" press="counter.press" "Press me"
button press="counter.reset" "Reset"
}
}
Give it a look. The toolkit’s stylesheets draw the controls. Yours lays out the window. Every colour is a token, so the same rule is right on both themes.
#hello { padding: 24px; gap: 12px; }
#buttons { gap: 8px; }
#count { color: var(--gb-accent); }
Write the application. The one class that knows a window exists. It names the models, inflates the document, lists the stylesheets, and hands itself to the launcher.
package com.example.hello;
import java.util.ArrayList;
import java.util.List;
import dev.goldberry.Application;
import dev.goldberry.Goldberry;
import dev.goldberry.css.cascade.CascadeLayer;
import dev.goldberry.css.Stylesheet;
import dev.goldberry.css.Theme;
import dev.goldberry.kdl.KdlParser;
import dev.goldberry.widget.Widget;
import dev.goldberry.widgets.Controls;
import dev.goldberry.widgets.Widgets;
public final class Hello implements Application {
private final Counter counter = new Counter();
private final Counter.Commands commands = new Counter.Commands(counter);
private final Stylesheet styles = Stylesheet.resource(CascadeLayer.APPLICATION, Hello.class, "hello.css");
@Override
public String title() {
return "Hello";
}
@Override
public List<Object> models() {
return List.of(counter, commands);
}
@Override
public Widget root() {
return Widgets.inflater(models().toArray())
.inflate(KdlParser.resource(Hello.class, "hello.kdl").getFirst());
}
@Override
public List<Stylesheet> stylesheets() {
var sheets = new ArrayList<>(Controls.stylesheets(Theme.NORD_DARK));
sheets.add(styles);
return sheets;
}
public static void main(String[] args) {
Goldberry.launch(new Hello(), args);
}
}
Run it.
./gradlew run
A window opens with a heading, a line of text and two buttons. Press the
first and the line counts. Nothing in the application repainted: assigning
label told the bound text and asked the window for a frame.
What just happened
models()is the whole of the wiring. The document’sbind=andpress=resolve against the objects in that list, and the same list is what the window subscribes to.- The inflater is built from
models()and not from a second list, so the two cannot disagree. A name the document uses that no model declares fails when the document is inflated, naming the text, rather than on the first click. - On the JVM the model is bound reflectively. In a native image the same class is bound ahead of time (Ahead-of-time binding).
Change it while it runs
Point a watcher at the stylesheet on disk and the window restyles when the file is saved. The same works for a document.
private final ReloadableSource<Stylesheet> styles = ReloadableSource.load(
Path.of("src/main/resources/com/example/hello/hello.css"),
css -> Stylesheet.parse(CascadeLayer.APPLICATION, css)
);
private HotReload reload;
@Override public void start(Host host) {
reload = HotReload.watch(List.of(styles), Goldberry.ui(), changed -> host.restyle());
}
@Override public List<Stylesheet> stylesheets() {
var sheets = new ArrayList<>(Controls.stylesheets(Theme.NORD_DARK));
sheets.add(styles.current());
return sheets;
}
@Override public void stop() {
reload.close();
}
HotReload and ReloadableSource are in dev.goldberry.reload. The callback
runs on the UI thread, which is why the watcher takes an executor. A file that
fails to parse keeps its last good value and logs the failure.
Markup covers reloading a document.
Switch the theme
Make the theme a bound value with restyle = true, and switching it is one
assignment:
@Bind(value = "app.light", restyle = true) private boolean light;
public Theme theme() {
return light ? Theme.NORD_LIGHT : Theme.NORD_DARK;
}
@Actions
public record Commands(Counter values) {
@Action("app.set-light") public void setLight(boolean light) { values.light = light; }
}
toggle bind="app.light" change="app.set-light" "Light"
stylesheets() is re-read only when a restyle is asked for, so returning
Controls.stylesheets(settings.theme()) from it costs nothing between
switches.
Where to go from here
Tip
Goldberry.launchreads--frames=Nand--size=WxHfrom the arguments, and-Dgoldberry.backend.videoDriver=dummyruns without a display. Together they are how an application paints three frames on a build server and exits. Testing an application has the rest.
Your first native application
The counter from the previous page as one executable: no JDK on the target machine, the native library inside the file.
A GraalVM native image is a closed world. It has to know every class, every resource and every foreign function before it runs, and it cannot bind a model by reflection. Goldberry is designed for that, and the toolkit’s jars carry most of what an image needs. Four things are yours:
- Weave the model, so that assignments notify without reflection.
- Declare your own resources, by glob.
- Trace one run, for what depends on your application.
- Run
native-image.
The recipe below is the showcase’s own. Native image explains every flag and every trap in depth.
Before you start
- A GraalVM Community for JDK 25, with
GRAALVM_HOMEpointing at it. A stock JDK has nonative-image. - On Linux, a C toolchain and zlib’s development package:
sudo apt install build-essential zlib1g-dev # Debian, Ubuntu
sudo dnf install gcc glibc-devel zlib-devel libstdc++-static
Without zlib1g-dev the build spends a minute on analysis and fails at the
last step with cannot find -lz.
Weave the model. The weaver rewrites Counter.class so that every write
to a @Bind field calls a synthesized setter that notifies. It is one jar
with no dependencies and a main that takes a directory of classes. The task
needs the classes and everything they were compiled against, because it
regenerates stack-map frames (Ahead-of-time binding).
configurations { goldberryWeaver }
dependencies { goldberryWeaver 'dev.goldberry:goldberry-weaver' }
def weaveModels = tasks.register('weaveModels', JavaExec) {
dependsOn tasks.compileJava
def classes = tasks.compileJava.flatMap { it.destinationDirectory }
classpath = files(configurations.goldberryWeaver, classes, sourceSets.main.compileClasspath)
mainClass = 'dev.goldberry.weaver.WeaverMain'
argumentProviders.add({ ['--models', classes.get().asFile.absolutePath] } as CommandLineArgumentProvider)
inputs.dir(classes)
outputs.file(layout.buildDirectory.file('tmp/weaveModels/stamp'))
outputs.upToDateWhen { false }
doLast { layout.buildDirectory.file('tmp/weaveModels/stamp').get().asFile.text = 'woven' }
}
tasks.named('jar') { mustRunAfter weaveModels }
The weaver’s version comes from the BOM, like every other artifact. The stamp file is deliberate: declaring the compiler’s own output directory as this task’s output makes Gradle recompile the whole module on every build.
Declare your resources. The document and the stylesheet are read by name at run time, and a trace only records what one run happened to touch. Globs are finite. The file goes in a directory the agent never writes to, so a new trace cannot overwrite it:
src/main/resources/META-INF/native-image/com.example/hello-manual/reachability-metadata.json
{
"resources": [
{ "module": "com.example.hello", "glob": "com/example/hello/*.kdl" },
{ "module": "com.example.hello", "glob": "com/example/hello/*.css" },
{ "module": "com.example.hello", "glob": "logback.xml" },
{ "glob": "dev/goldberry/natives/**" }
]
}
The last line is the native library itself. It lives in the classifier jar, which the image carries as a class-path resource and unpacks to a temporary file on first use.
The logback.xml line is there if you log through Logback. Logback asks a
ClassLoader for the file, so the agent records it without a module, and in
an image built from the module path it is then not there at all: Logback
starts with no appenders and the image prints nothing
(Native image).
Trace one run. What the toolkit’s jars cannot declare is what depends on
your run: the service the widget catalogue is found through, the upcall stubs
the native code calls back into, the JDK’s text resources, and whatever your
logging configuration reflects over. GraalVM’s agent records them. Run the
woven application once, headless, for a hundred frames, and keep the output
under src/main/resources so it is reviewed in a diff:
tasks.register('nativeImageMetadata', Exec) {
dependsOn weaveModels, tasks.jar
def output = layout.projectDirectory.dir('src/main/resources/META-INF/native-image/com.example/hello')
doFirst {
def split = splitPaths()
def command = ["${System.getenv('GRAALVM_HOME')}/bin/java",
'--enable-native-access=dev.goldberry.natives',
"-agentlib:native-image-agent=config-output-dir=${output.asFile.absolutePath}",
'-Dgoldberry.backend.videoDriver=dummy']
if (System.getProperty('os.name').toLowerCase().contains('mac')) {
command += '-XstartOnFirstThread'
}
command += ['--module-path', split.modules, '-cp', split.natives,
'--module', 'com.example.hello/com.example.hello.Hello', '--frames=120']
commandLine command
}
}
splitPaths is a small helper, used by both tasks. Each natives classifier
jar names its own module, dev.goldberry.natives.linux_x64 and so on, but
nothing requires one, and an image takes only the modules that are
resolved. So for an image they go on the class path, where the library is a
plain resource
(Native image):
def splitPaths = {
def jars = configurations.runtimeClasspath.files
def natives = jars.findAll { it.name.startsWith('goldberry-natives-') && it.name =~ /-(linux|macos|windows)-/ }
def modules = (jars - natives) + [tasks.jar.archiveFile.get().asFile]
[modules: modules*.absolutePath.join(File.pathSeparator), natives: natives*.absolutePath.join(File.pathSeparator)]
}
The agent writes reachability-metadata.json beside your manual one.
native-image reads every META-INF/native-image/** it finds, so the two
are merged for the tool and kept apart for you.
Build the image.
tasks.register('nativeImage', Exec) {
dependsOn weaveModels, tasks.jar
def target = layout.buildDirectory.file('native/hello')
doFirst {
def split = splitPaths()
commandLine "${System.getenv('GRAALVM_HOME')}/bin/native-image",
'--module-path', split.modules,
'-cp', split.natives,
'--module', 'com.example.hello/com.example.hello.Hello',
'-o', target.get().asFile.absolutePath,
'--enable-native-access=dev.goldberry.natives',
'-H:+ReportExceptionStackTraces'
}
}
./gradlew nativeImageMetadata nativeImage
./build/native/hello
The result is one file. No launcher, no lib/ directory, nothing to set.
What the toolkit’s jars bring
Nothing above names a Goldberry resource, a foreign function or a class
initialization policy, because the jars carry their own metadata and
native-image reads it from every jar on the path:
| Jar | Carries |
|---|---|
goldberry-natives | the descriptor of every bound C function, written because the function exists rather than because a run reached it, and the class-initialization policy that makes a downcall handle a constant |
goldberry-core | the fonts, the icon table, the two themes |
goldberry-widgets | the catalogue’s stylesheets |
goldberry-html, goldberry-media | their stylesheets, when they are on the path |
Warning
The one thing that fails silently is speed. A downcall handle that is not a compile-time constant costs a factor of 450 per call, and the image builds, runs and paints correctly at forty times the frame cost. The policy that prevents it travels in the natives jar. If you pass your own
--initialize-at-run-timeor--initialize-at-build-timeflags, read Native image first.
What to expect
The executable carries the libraries and resources included by its dependencies and metadata. Use the startup trace to measure the path to the first frame on a target machine.
Note
A screen the trace never reached contributes nothing to the metadata. After adding a screen, re-run
nativeImageMetadataand read the diff. A stylesheet a trace misses is absent from the image, which is why resources are declared by glob and not traced.
Read next
How layout works
Every box in a Goldberry window is placed by flexbox, and this chapter is the vocabulary the eight chapters after it share.
By the end of this chapter you can read a widget tree and say where each box lands. You also know which half of a layout the widget owns and which half the stylesheet owns.
A row, a stylesheet, and the same tree in Java
row id="toolbar" {
text "Goldberry"
spacer
button press="theme" "Theme"
}
#toolbar {
gap: 8px;
padding: 0 12px;
align-items: center;
}
var toolbar = new Row(
new Text("Goldberry"),
new Spacer(),
new Button("Theme", this::theme)
).withAttributes(Attributes.NONE.id("toolbar"));
The row says which way its children go. The stylesheet says everything else: the gap between them, the padding at the ends, and how they line up across the row. The spacer takes the space nobody else asked for, so the button sits at the far end.
Flexbox
Layout is done by a native flexbox engine, and the CSS subset compiles to its properties. The vocabulary an application sees is the toolkit’s own. Length, Insets, Limits, FlexDirection, Justify, Align, Wrap, Position and Overflow live in dev.goldberry.layout.
The engine runs with CSS’s defaults. A box shrinks when its row is too narrow, because flex-shrink is 1 unless a rule says otherwise. Keep that in mind when a control looks squashed. Sizing with CSS lists every property the subset accepts.
Logical pixels
A px in a stylesheet is a logical pixel. The window’s display scale is applied once, as a transform on the painting context, and nothing above it does arithmetic in device pixels. 8px of padding is the same distance on a 100% display and a 200% one.
Edges land on whole device pixels. The render tree hands the layout engine the window’s scale, and the engine rounds every edge to the device grid. At 1x a row of 101 points splits 51 and 50. At 2x it splits 50.5 and 50.5, which is the same tree on a finer grid.
The box model
A box has a width and a height, padding inside its edge, a margin outside it, and a border drawn on the edge. min-width, max-width, min-height and max-height bound it. An absolutely positioned child is placed from its parent’s border box rather than its padding box, which is where this layout differs from CSS.
Three trees
A widget is an immutable record describing what should be on screen. Building it produces an element, which persists across rebuilds and holds state and focus. The element produces a render object, which owns a layout node, is laid out, and is painted. Layout runs on the third tree, so a rebuild that re-describes a node with the same type, id and classes keeps its computed style and its layout node.
Text is a measured leaf
The layout engine knows nothing about glyphs. A box with text in it carries a measure function. The engine proposes a width, the paragraph wraps at it and reports a height, and the flexbox algorithm sizes everything around that answer. The paragraph is shaped once, and every re-wrap is arithmetic over the glyphs it already has. That is what makes the callback cheap enough to answer inside a layout pass.
A box therefore has text or children, never both. The engine asks a measured node for its size and never lays its children out.
What a widget owns and what CSS owns
A row is a row. Its render applies flex-direction after the stylesheet, so no rule can turn it into a column. That is the one layout property a widget keeps for itself. Gap, padding, margin, alignment, wrapping, growing, shrinking and sizes are all the stylesheet’s, and the same tree looks different under a different sheet.
The split holds across the catalogue. A scroll clips and translates. A split-pane sizes its first pane in pixels, because the divider’s fraction is a thing no flex-grow can express. A masonry deals cards into columns. Each of them leaves every number it does not have to own to CSS.
Controls do not shrink
CSS’s default flex-shrink: 1 is wrong for a checkbox. The controls declare flex-shrink: 0, once, over a list of types. Text is deliberately left off that list. A label shrinks by wrapping, which is what a label should do.
When a widget of your own has a fixed size, give it the same declaration.
my-widget { flex-shrink: 0; }
The layout widgets
For widget authors
A widget that lays out children returns a Box from render. The direction is a call on the box, the stylesheet arrives as style, and the children arrive already rendered.
@Override
public Box render(ComputedStyle style, List<Box> boxes, Context context) {
return Box.of()
.children(boxes.toArray(Box[]::new))
.style(style)
.direction(FlexDirection.ROW);
}
direction is called after style so that it wins. A box that should take the stylesheet’s direction leaves the call out. The rest is in Writing a widget.
Row and column
The two containers almost every tree is made of. A row lays its children out left to right, a column top to bottom, and the stylesheet decides everything else.
By the end of this chapter you can nest the two to build any arrangement flexbox describes, and you know which numbers belong in CSS rather than in the tree.
row
A row lays its children out along the horizontal axis.

Two buttons with a spacer between.
row id="toolbar" {
button press="find" "Find"
spacer
button class="primary" press="create" "New"
}
var toolbar = new Row(
new Button("Find", this::find),
new Spacer(),
new Button("New", this::create).styled("primary")
).withAttributes(Attributes.NONE.id("toolbar"));
new Row(Widget...) takes the children. new Row(List<Widget>, Attributes) takes them with an id and classes, and withAttributes adds those to a row built the short way.
The showcase writes a settings line as a row with a spacer in the middle, which puts the label at one end and the value at the other.
row class="setting" {
text "Guide"
spacer
text class="caption" "Gandalf the Grey"
}
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The node’s id, for #toolbar in a stylesheet and in tests |
class | string | none | Classes separated by spaces, for .setting in a stylesheet |
tooltip | string | none | Text shown when the pointer rests on the row |
context-menu | string | none | The id of a menu opened by a secondary click |
name | string | none | The accessible name |
The last three are the same on every layout widget in this part, and the tables after this one list only id and class.
Note
Set gaps in CSS, for example
#toolbar { gap: 8px }. The inflater rejectsrow gap=8because no factory reads it.
Styling
The CSS type is row. It has no parts and no pseudo-classes of its own.
controls.css ships no rule for it, so a bare row has no gap, no padding and no colour. Everything is the stylesheet’s except the direction: render applies flex-direction: row after the computed style, so a rule that says flex-direction: column on a row is ignored.
#toolbar {
gap: 8px;
padding: 4px 8px;
align-items: center;
}
There are no variant classes. The classes a row carries are the ones a document gives it.
column
A column lays its children out along the vertical axis.

Text over a row of buttons.
column id="confirm" {
text "Delete this file?"
row {
spacer
button press="dismiss" "Cancel"
button class="danger" press="delete" "Delete"
}
}
var confirm = new Column(
new Text("Delete this file?"),
new Row(
new Spacer(),
new Button("Cancel", this::dismiss),
new Button("Delete", this::delete).styled("danger")
)
).withAttributes(Attributes.NONE.id("confirm"));
new Column(Widget...) and new Column(List<Widget>, Attributes) are the two constructors, exactly as on row.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The node’s id |
class | string | none | Classes separated by spaces |
accordion | boolean | #false | Builds an accordion instead: one collapse child open at a time |
accordion=#true inflates to a different widget. The accordion reports column as its CSS type and adds an accordion class, so a stylesheet still sees a column and an ordinary column carries no state for a feature it does not use. The collapse children it manages are in Panels.
column accordion=#true id="chapters" {
collapse title="The Shire" { text "Second breakfast" }
collapse title="Rivendell" { text "The Council" }
}
Styling
The CSS type is column. No parts and no pseudo-classes of its own, and no rule in controls.css. The direction is applied after the computed style, as on row.
#confirm {
gap: 12px;
padding: 16px;
align-items: stretch;
}
Spacer
Empty space that takes whatever its row or column has left over.
By the end of this chapter you can push a button to the far end of a toolbar, centre a label between two things, and know the one thing a spacer cannot do.
spacer
A spacer is a box that grows into the free space of its container.

The spacer takes the room between.
row id="title-bar" {
text "Goldberry"
spacer
button press="theme" "Theme"
}
var bar = new Row(
new Text("Goldberry"),
new Spacer(),
new Button("Theme", this::theme)
).withAttributes(Attributes.NONE.id("title-bar"));
new Spacer() is the whole constructor. new Spacer(Attributes) gives it an id and classes.
Two spacers share the free space equally, so a label between two of them sits in the middle.
row {
spacer
text "Nine set out from Rivendell"
spacer
}
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The node’s id |
class | string | none | Classes separated by spaces |
Styling
The CSS type is spacer. It has no parts and no pseudo-classes, and controls.css ships no rule for it.
A spacer grows by 1 unless the stylesheet gives it a flex-grow of its own. A spacer with flex-grow: 2 takes twice the share of its siblings.
#title-bar spacer.wide { flex-grow: 2; }
A spacer cannot be told not to grow. flex-grow: 0 is the computed value when nothing was declared, so render reads it as unset and grows by 1 anyway. A fixed gap between two neighbours is gap on the container or margin on one of them, not a spacer with a width.
Stack
Children drawn on top of one another. The first child gives the stack its size, and every child after it floats over it.
By the end of this chapter you can put a badge on a corner of an avatar, an overlay over a picture, and know where an overlay lands when nothing says.
stack
A stack keeps its first child in flow and takes every later child out of flow, so adding an overlay cannot move or resize the thing it sits on.

A badge laid over a portrait.
stack id="avatar" {
panel class="portrait" { text "GB" }
badge class="info" "3"
}
var avatar = new Stack(
new Panel(new Text("GB")),
new Badge("3")
).withAttributes(Attributes.NONE.id("avatar"));
new Stack(Widget...) and new Stack(List<Widget>, Attributes) are the two constructors. A stack of one child is that child in a box.
Later children draw over earlier ones. That is the painter’s rule for siblings, and a stack adds nothing to it.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The node’s id |
class | string | none | Classes separated by spaces |
Styling
The CSS type is stack. It has no parts, no pseudo-classes of its own, and no rule in controls.css.
render sets position: absolute on every child after the first. Where an absolute child lands is the stylesheet’s, and there are two ways to say it.
With no inset, the child is placed by the stack’s align-items and justify-content and by its own align-self. A badge goes to a corner with two declarations and no arithmetic.
#avatar { align-items: flex-start; justify-content: flex-start; }
#avatar badge { align-self: flex-end; }
With an inset, the child goes where the inset says. Zero pins it to the stack’s edge.
#avatar badge { top: 0; right: 0; }
The difference between “no inset” and “an inset of zero” only shows on an absolute child, and stack is the widget that shows it. An inset is measured from the stack’s border box rather than its padding box. That is the layout engine’s rule.
Scroll
A viewport that shows part of something taller than itself, with overlay scrollbars, a wheel, a keyboard, and a position that survives rebuilds.
By the end of this chapter you can put a long column in a viewport, choose which axis it moves on, scroll it from Java, open a log at its end, and know what a long document costs a frame.
scroll
A scroll clips its content, moves it by an offset, and keeps that offset on its element so a rebuild does not lose it.

A vertical viewport over a column.
scroll id="chapters" axis="vertical" {
column {
text "Hobbiton"
text "Bree"
text "Rivendell"
text "Moria"
}
}
var chapters = new Scroll(
new Column(
new Text("Hobbiton"),
new Text("Bree"),
new Text("Rivendell"),
new Text("Moria")
)
).withAttributes(Attributes.NONE.id("chapters"));
new Scroll(Widget...) is vertical. new Scroll(List<Widget>, ScrollAxis, Attributes) chooses the axis. Several children are wrapped in one moving box, so they stack as they would in a column.
The viewport is three nodes, and each is one idea.

The three nodes of a viewport, each one idea.
A scroll has flex-grow: 1 from controls.css, so in a column it fills what is left. In a box that sizes to its content it needs a height from the stylesheet, which is why the showcase’s .scroll-demo is height: 260px.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
axis | string | vertical | vertical, horizontal or both. x and xy are accepted spellings, and an unknown word is vertical |
anchor | string | start | start opens at the top. end opens at the end and stays there while the viewport is already there. bottom is accepted for end |
preserve-on-prepend | boolean | the anchor’s | Whether content inserted above the viewport moves the offset by the height added, so what is on screen stays still. On for end and off for start unless written |
id | string | none | The node’s id, which lands on the scroll node |
class | string | none | Classes separated by spaces |
Three things are Java only, because each is a value a document cannot hold. height(double) caps the viewport in logical pixels, which is how a menu is kept no taller than the display. controlledBy(ScrollController) hands it a handle something outside the viewport keeps. anchor(ScrollAnchor) and preserveOnPrepend(boolean) are the two attributes above as methods.
var log = new Scroll(List.of(lines), ScrollAxis.VERTICAL, Attributes.NONE)
.anchor(ScrollAnchor.END)
.controlledBy(controller);
Scrollbars
The default bar overlays its content. Its thumb is 4 px wide with a transparent
track. Hovering over the viewport widens the thumb to 6 px and colours the
track with --gb-surface-2.
A click on the track pages by a whole viewport towards the side the click landed on. The thumb’s length is the viewport’s share of the content, floored at 24 px so a very long document still has something to grab.
The other arrangement is a classic reserved gutter: 12 px of layout beside the content, a track that is always there, and a thumb that neither widens nor fades. It is Scrollbars.ALWAYS, a token stylesheet added after the theme and the density, so a component that reads the tokens survives the gutter appearing as a narrower box rather than as text under a bar.
var sheets = Controls.stylesheets(Theme.NORD_DARK, Density.REGULAR, Scrollbars.ALWAYS);
Edges are hard. There is no overscroll bounce.
| Token | Overlay | Always |
|---|---|---|
--gb-scrollbar-size | 6px | 12px |
--gb-scroll-thumb-size | 4px | 8px |
--gb-scroll-thumb-hover-size | 6px | 8px |
The wheel
A wheel event arrives in lines, and a line is --gb-scroll-line, 20 px in controls.css. One notch of the wheel is three lines, which is what every other application on the machine does. A trackpad reports fractions of a notch and gets the same multiplier, so the same gesture covers the same ground it would anywhere else. An author who sets --gb-scroll-line on one scroll changes how far that viewport moves per line and nothing else.
A wheel is consumed only when it moved something. At the top of a list a further turn bubbles, and the viewport around it takes it. A disabled control between the pointer and the viewport does not stop it. A nested scroller on the same axis works, but the design system bans the arrangement and the viewport logs it once.
Keyboard
A scroll is a Tab stop. The keys act when it has focus and are consumed only when they moved something.
From Java, .tabStopOnlyWhenScrollable() makes it a Tab stop only while its content overflows. That is for a viewport that wraps content of its own, such as a dialog’s body: one that fits adds nothing to the Tab order, and one that overflows can be scrolled from the keyboard.
| Key | Moves |
|---|---|
| Up, Down, Left, Right | One line, --gb-scroll-line |
| Page Up, Page Down | The viewport’s height less 24 px, so one line of the old page stays on screen |
| Home | To the start |
| End | To the end |
Scrolling from Java
A ScrollController is a handle the application keeps and the viewport attaches to. It is created outside the viewport on purpose: whoever needs to scroll it is somewhere else, and a controller the state created would have a new identity on every rebuild.
private final ScrollController list = new ScrollController();
list.scrollBy(0, 240);
list.onChange(() -> status.set(list.position().offsetY() + ""));
reveal(self, clip) brings a rectangle into view with the least movement that does it. The rectangles come from a widget that implements Located, which the router tells where it is and what clips it, once a frame and only on a change. A programmatic scroll glides over --gb-motion-overlay, and a wheel, a key or a drag takes over at once.
A timeline
A chat, a log or a console wants three things of a viewport. It should open on the newest line. It should stay there while the reader is already there, and not move them when they are reading history. And when older lines are paged in above, the line they are reading should stay still. anchor="end" is the first two and preserve-on-prepend is the third.
scroll id="console" anchor="end" preserve-on-prepend=#true {
column {
text "[12:00:01] Started"
text "[12:00:04] Listening on 8080"
}
}
Preserving the offset means recognising a row that was on screen a frame ago, so the rows need keys. A list matched by position has no such row.
What a frame pays
The painter skips a subtree whose ink cannot land inside the clip in force, so a viewport costs what is visible and not what is in it. The culling is by the subtree’s ink rather than the box’s own rectangle, so a child drawn outside its parent is still painted. A wheel moves the offset by a transform on one box, and re-describing a node with the same type, id and classes keeps its cached style, so a notch does not re-style what it scrolls past.
A scroll does not virtualize. A list and a table build only the rows in their window, and that is in Collections. A masonry cannot virtualize at all, and the cull is what makes a long wall affordable.
Styling
The CSS type is scroll, and it is the viewport. The record itself styles nothing, so a document’s id and class land on the viewport node.
| Node | What it is | In controls.css |
|---|---|---|
scroll | The viewport | flex-grow: 1; overflow: hidden |
scroll-content | The moving box | flex-shrink: 0, pinned in code so no rule can undo it |
scrollbar | One axis’s bar, .vertical or .horizontal | position: absolute, track --gb-scrollbar-track |
scroll-thumb | The thumb, .vertical or .horizontal | --gb-text-muted, full radius, .dragging takes --gb-accent |
scroll:hover widens the thumbs and shows the track. The catalogue’s own viewports carry a class each, menu-viewport, select-viewport and tab-viewport, and the first two set flex-grow: 0 because their height is the opener’s.
The tokens, with the overlay default and the Scrollbars.ALWAYS value:
| Token | Overlay | Always |
|---|---|---|
--gb-scroll-line | 20px | 20px |
--gb-scrollbar-gutter | 0px | 12px |
--gb-scrollbar-size | 10px | 12px |
--gb-scrollbar-track | transparent | var(--gb-surface-2) |
--gb-scroll-thumb-size | 6px | 8px |
--gb-scroll-thumb-hover-size | 10px | 8px |
Split pane
Two children and a divider you can drag, with a position that survives a resize and minimums that do not.
By the end of this chapter you can put a list beside a detail view, keep either side from being squeezed to nothing, let the user collapse one, and move the divider from the keyboard.
split-pane
A split-pane lays out exactly two children along one axis with a draggable divider between them.

Two panels and a divider.
split-pane id="demo-split" first-min=120 second-min=140 collapsible=#true {
panel class="split-demo" {
text class="caption" "The map"
text "Tab to the divider and use the arrows, or Enter to collapse."
}
panel class="split-demo" {
text class="caption" "The road"
text "This one takes whatever is left."
}
}
var split = new SplitPane(map, road);
new SplitPane(first, second) is horizontal, starts in the middle, and keeps its own position. The controlled form takes the position from the application and reports a drag back to it.
new SplitPane(SplitAxis.HORIZONTAL, position, this::setSplit, map, road)
The full constructor is SplitPane(axis, position, source, onResize, firstMin, secondMin, collapsible, children, attributes), and there is one without source. A list of any size other than two is an IllegalArgumentException. A three-way split is two split panes, one inside the other.
The position is a fraction and the minimums are pixels, deliberately. A divider a third of the way across stays a third of the way across when the window widens. A list that needs 160 points or its labels wrap needs them whatever the window does. The fraction is clamped against the pixels on every layout, which needs the pane’s measured length, and that arrives once a frame through Measured.
The first pane is given its size in logical pixels and the second grows into the rest. Two flex-grows would not do it, because flex-grow shares out what is left after content and would ignore the fraction.
The position from a model
bind= names a number the position is read from, as a slider’s value is.
With resize= beside it the split is controlled: the bound number is where the
divider is, and a drag reports where it should go, which the application
writes back into the model. Nothing here writes the model itself, because data
flows down and events flow up.
split-pane bind="layout.split" resize="layout.set-split" first-min=160 {
panel { text "The list" }
panel { text "The detail" }
}
@Bind("layout.split") private double split = 0.3;
@Action("layout.set-split") void setSplit(double value) { split = value; }
With bind= alone the split keeps its own position. It starts at the bound
number, a drag moves it without telling anyone, and it goes back to the model’s
number whenever the model changes it. That is what restoring a saved layout
needs. A bound value that is not a number is ignored and position is used.
In Java, split.bound(observable) does the same.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
axis | string | horizontal | horizontal is side by side with a vertical bar. vertical is stacked with a horizontal bar |
position | number | 0.5 | Where the divider starts, as a fraction of the pane’s length from 0 to 1 |
bind | path | none | A number to read the position from. A bound number wins over position |
resize | action name | none | An action that takes a number. Naming one makes the pane controlled, and position is then where the divider is rather than where it starts |
first-min | number | 48 | The least the first child may be, in logical pixels |
second-min | number | 48 | The least the second child may be |
collapsible | boolean | #false | Whether dragging past a minimum collapses that child to nothing rather than stopping at it |
id | string | none | The node’s id, which lands on the split-pane node |
class | string | none | Classes separated by spaces |
The default minimum is 48 points. The design system’s hit-target floor is 32, and a pane squeezed to exactly that has no room for anything in it.
Styling
| Node | What it is | In controls.css |
|---|---|---|
split-pane | The whole pane | align-items: stretch; flex-grow: 1; flex-shrink: 1 |
split-pane-side | Each child’s box | flex-direction: column; overflow: hidden |
split-divider | The bar | 6 px thick, flex-shrink: 0, --gb-border |
The divider carries the axis as a class, horizontal or vertical, and collapsed when a side has gone to nothing. split-divider:hover and split-divider:focus-visible are both --gb-accent, on purpose: a divider has no state worth two appearances, and both mean “this is the thing you are about to move”. The focus ring is turned off because a ring at the usual offset would be drawn across both panes. split-divider.collapsed takes --gb-surface-2.
Each side clips what is in it, so a pane dragged narrower than its content does not spill across the divider.
A split pane grows to fill what it is given. In a column that sizes to its content it needs a height from the stylesheet, which is why the showcase gives its card a definite one. The pane measures its own length and asks for a rebuild when it changes, and that value cannot feed itself because what the rebuild changes is the children.
#demo-split { height: 220px; }
Keyboard
The divider is the Tab stop. The pane itself is not focusable and neither side is a composite.
| Key | Moves |
|---|---|
| The arrows along the axis | 16 px |
| Page Up, Page Down | 64 px |
| Home, End | As far as the minimums allow |
| Enter, Space | Collapses and restores, when collapsible |
The arrows across the axis are left alone, so a horizontal split has nothing to say about Up and the key reaches whatever does.
Masonry
Cards of unequal height packed into columns, each card under whichever column is shortest.
By the end of this chapter you can build a wall of cards that survives a window being dragged narrower, choose between a fixed count and a minimum width, and know why the wall settles a frame late.
masonry
A masonry deals its children into columns and places each one under the column that is currently shortest.

Cards in as many columns as fit.
masonry id="wall" min-column-width=320 {
card { text class="card-title" "Leagues"; statistic label="Walked" value="1,795" }
card { text class="card-title" "The Company"; text "Nine set out from Rivendell." }
card { text class="card-title" "Provisions"; text "Lembas, 30 days." }
}
var wall = new Masonry(List.of(leagues, company, provisions))
.withAttributes(Attributes.NONE.id("wall"));
new Masonry(List<Widget>) is responsive at 320 points. new Masonry(List<Widget>, int columns, Attributes) is a fixed count. columns(int) and minColumnWidth(int) switch a masonry from one mode to the other, dropping the setting it had.
This is the one container the catalogue cannot write in flexbox. A wrapping row aligns its lines, and a column per column cannot balance them, because balancing needs every item’s height and those are not known until they are laid out.
How it places
It reads last frame. Every cell reports what it came out as through Measured, the state banks the height, and the next frame puts each card under the column that is shortest. The first frame has no measurements, so a responsive wall is one column and the second frame is right. That is one frame of settling nobody sees.
Reading last frame is allowed here because moving a card between columns does not change its height. The columns are the same width, so the number being reported is stable under the thing it causes. That is also why columns is a count and not a list of widths.
A responsive wall counts its columns from its own width, banked the same way. With n columns needing n minimums and n - 1 gaps, the count is the largest n for which n times the minimum plus n - 1 gaps fits, and at least one. A column count changes the wall’s height and not its width, so that number is stable too.
Reading order is down each column, not across. The third card is not necessarily beside the second. Where order matters, a form or a ranked list, the answer is a column.
A masonry never virtualizes. Which column an item is in depends on every item before it, so there is no arithmetic from an index to a position. A long wall is affordable because a scroll does not paint what is off screen, which is in Scroll.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
columns | number | unset | A fixed count. Two columns at 1200 are two columns at 720, half as wide and twice as tall |
min-column-width | number | 320 when neither is written | As many columns as fit at this width, at least one |
id | string | none | The node’s id, which lands on the masonry node |
class | string | none | Classes separated by spaces |
The two are exclusive. A masonry given both is an IllegalArgumentException at construction, and so is columns=0. Neither is clamped, because a layout that silently disagrees with the document is found by looking at a picture and a document that throws is found by running anything.
Important
Put a wall where something gives it a width. A
masonry-columnisflex-basis: 0, so a masonry in a box that sizes to its content comes out zero wide with its cards hanging out of it, in either mode.
The showcase’s walls
Every screen in the showcase is a masonry, because a card is as tall as its contents and no two cards are the same height. Laid out in equal rows the short ones would sit in acres of empty surface. Most walls give a width rather than a count: no column is narrower than 360, so a screen is three columns at 1280 and one at 720. The Collections and Navigation screens keep a count of two, because a table and a strip of steps need the room. A screen written in Java hands Masonry.UNSET for the mode it did not choose.
Styling
| Node | What it is | In controls.css |
|---|---|---|
masonry | The wall | flex-direction: row; align-items: flex-start; gap: 12px |
masonry-column | One column | flex-direction: column; gap: 12px; flex-basis: 0; flex-grow: 1 |
masonry-cell | One card’s box, which exists to report a height | flex-direction: column |
The gap on both axes is the stylesheet’s: the wall’s gap is between columns and the column’s gap is between cards. The responsive count reads the wall’s resolved gap. There are no pseudo-classes and no variant classes of its own. The showcase’s .wall adds flex-shrink: 0.
#wall { gap: 16px; }
#wall masonry-column { gap: 16px; }
Affix
A child pinned to an edge of the nearest scroll once it would have scrolled past, leaving a same-sized hole behind so nothing below it jumps.
By the end of this chapter you can give a long list sticky section headers that hand over to each other, pin a table’s header on two axes, and bring a pinned section back into view.
affix
An affix keeps its child where the layout put it until that place leaves the viewport, then holds the child at the viewport’s edge.

The section header is held at the top of its scroll.
scroll id="chapters" {
column {
affix id="section-hobbiton" class="section" edge="top" {
panel class="section-header" { text "Hobbiton" }
}
text class="scroll-row" "Hobbiton, line 1"
text class="scroll-row" "Hobbiton, line 2"
affix id="section-bree" class="section" edge="top" {
panel class="section-header" { text "Bree" }
}
text class="scroll-row" "Bree, line 1"
}
}
var hobbiton = new Affix(
List.of(new Panel(new Text("Hobbiton"))),
Edge.TOP, 0,
Attributes.NONE.id("section-hobbiton").classes("section")
);
new Affix(Widget...) pins to the top with no offset. new Affix(children, edge, offset, attributes) is the usual form, and alsoPinnedTo(Edge) adds an edge on the other axis. Edge is dev.goldberry.widgets.core.affix.Edge.
The showcase's viewport, seven lines in. The first header has lifted and the rows slide under it.
It leaves a hole
The widget is two nodes. An outer affix stays exactly where the layout put it, and an inner affix-content slides. That is the difference from position: fixed, and it is also what stops the widget oscillating. The router tells the affix where it is once a frame, and a node that moved itself in response would be told a new position and move again forever. The outer node’s position is a function of the layout alone, so the inner node sliding under it changes nothing that is reported.
The CSS subset has no position: sticky. This is a widget precisely so the subset does not have to grow a layout mode. Two boxes and a translate are the whole of it.
It stays inside its container
An affix never travels past the far side of the nearest ancestor with a box. A section’s header leaves with its section and the next header takes over, which is CSS’s rule for sticky and needs no code: one column per section, each holding an affix and its rows. An affix directly in the scrolled column has the whole document as its container and pins until the end. A table wraps its head in an affix, so on a scrolling page the column names pin while the table is in view and leave with it.
Two axes
edge="top left" pins to one edge on each axis, for a header that is sticky at the top and held against the left of a table that scrolls sideways. Each axis is its own subtraction, so neither wins over the other. Two edges on the same axis are refused: in Java it is an IllegalArgumentException, and in markup the second word is ignored.
Revealing one
Pointing scrollIntoView at a pinned affix from the outside scrolls nowhere, because its content is already at the viewport’s edge and anything measuring it concludes it is in view. What travels with the document is the hole, and only the affix can hand that out. revealedBy(listener) gives it a callback that receives the hole’s rectangle and the viewport’s once a frame, which is exactly the pair ScrollController.reveal takes. The showcase’s “Jump to” buttons do this: a press records which section is wanted, that section’s affix is built with the callback, and the callback hands the controller the two rectangles only a laid-out frame knows.
rows.add(section.equals(wanted) ? affix.revealedBy(this::revealed) : affix);
private void revealed(LogicalRect self, LogicalRect clip) {
list.reveal(self, clip);
setState(() -> wanted = null);
}
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
edge | string | top | top, bottom, left or right. Two words, one per axis, pin on both. An unknown word is top |
offset | number | 0 | How far from that edge to sit, in logical pixels |
id | string | none | The node’s id, which lands on the affix node |
class | string | none | Classes separated by spaces |
Styling
| Node | What it is | In controls.css |
|---|---|---|
affix | The hole, which never moves | flex-shrink: 0 |
affix-content | The box that slides | flex-shrink: 0 |
:affixed matches the affix node the moment its content lifts, and not before. No selector can say “this node is currently over another one”, which is why it is a pseudo-class rather than a class an author writes. controls.css uses it to give a pinned child a surface and an elevation, and the transition on the shadow is how it arrives as the child lifts.
affix:affixed > affix-content {
background: var(--gb-surface);
box-shadow: var(--gb-elevation-1);
transition: box-shadow var(--gb-motion-fast);
}
The showcase keeps its headers transparent at rest and gives them --gb-surface-2 only while pinned, so a header at rest does not draw a band across the list.
.section:affixed > affix-content > section-header {
background: var(--gb-surface-2);
}
There are no variant classes of its own.
Sizing with CSS
Every layout property the CSS subset accepts, the units a length may be in, how a percentage resolves, and the tokens that move a control's size.
By the end of this chapter you can write a stylesheet that sizes a tree, know which declarations the engine drops, and switch a whole application to compact density with one argument.
The subset
The engine applies these layout properties and drops every other one. A dropped declaration is not an error. The engine logs it and carries on. StyleLint reports every dead declaration in a sheet, and the toolkit’s own sheets have none.
| Property | Values |
|---|---|
flex-direction | row, row-reverse, column, column-reverse |
justify-content | flex-start, center, flex-end, space-between, space-around, space-evenly |
align-items, align-self | auto, flex-start, center, flex-end, stretch, baseline |
align-content | The same words, and space-between, space-around, space-evenly for wrapped lines |
flex-wrap | nowrap, wrap, wrap-reverse |
width, height | A length, a percentage, or auto |
min-width, max-width, min-height, max-height | A length or a percentage |
padding, padding-top, padding-right, padding-bottom, padding-left | One to four lengths, no auto |
margin, margin-top, margin-right, margin-bottom, margin-left | One to four lengths, auto, negatives allowed |
gap | One length, for both axes |
flex-grow, flex-shrink | A number of zero or more |
flex-basis | A length, a percentage, or auto |
position | static, relative, absolute |
inset, top, right, bottom, left | One to four lengths |
overflow | visible, hidden, scroll, auto |
start and end are accepted for flex-start and flex-end wherever an alignment keyword is. left and right are not, because they are not the same under right-to-left text. A shorthand with one bad part is dropped whole, so padding: 8px nonsense applies to no edge rather than two.
Not in the subset: display, box-sizing, aspect-ratio, row-gap and column-gap, calc(), grid, and position: sticky. A sticky header is an affix. A value the engine cannot express is dropped rather than approximated.
Units
| Unit | Meaning |
|---|---|
px | A logical pixel. The display scale is applied once, below the stylesheet |
% | A percentage of the parent’s matching dimension |
em | The element’s own computed font size |
rem | The root element’s computed font size |
0 | Unitless zero is accepted. Any other unitless number is dropped |
auto | Where the property takes it: width, height, margin, flex-basis and align-self |
em and rem are resolved when the declaration is read, because the layout engine has no concept of a font size. em is the element’s own computed size and rem is the root element’s. vh, vw, pt and cm are not units here.
A percentage width is of the parent’s width, a percentage height of its height, and a percentage flex-basis of the parent’s main axis.
Direction and gap
column id="form" {
row class="field-row" { text "Name"; text-input }
row class="field-row" { text "Email"; text-input }
}
#form { gap: 12px; padding: 16px; }
.field-row { gap: 8px; align-items: center; }
gap is one length and applies between rows and between columns alike. A row and a column ignore flex-direction. On any other box, a panel or a card, the stylesheet chooses it.
Padding and margin
panel id="dialog" {
text "Delete this file?"
row class="actions" {
spacer
button press="dismiss" "Cancel"
button class="danger" press="delete" "Delete"
}
}
#dialog { padding: 16px 24px; margin: 0 auto; }
.actions { gap: 8px; margin-top: 16px; }
The shorthand is CSS’s: one value is every edge, two are vertical and horizontal, three add a bottom, and four go clockwise from the top. margin: 0 auto centres a box on the main axis of a container it does not control. align-self: center centres on the cross axis. Negative margins pull a box over its neighbour and are not clamped.
Alignment
row id="status" {
text "Listening on 8080"
spacer
badge class="success" "Live"
}
#status { align-items: center; justify-content: space-between; }
#status badge { align-self: flex-start; }
justify-content places children along the main axis and align-items across it. align-self is one child’s answer to align-items, and align-self: auto is a real declaration that undoes a more general rule.
Wrapping
row id="tags" {
chip "Unread"
chip "Starred"
chip "Archived"
chip "Shire"
chip "Rivendell"
}
#tags { flex-wrap: wrap; gap: 8px; align-content: flex-start; }
flex-wrap: wrap lets a row break into lines. align-content places the lines across the container. Wrapped lines share a cross axis.
Growing, shrinking and the basis
row id="editor" {
column id="files" { text "main.java"; text "Window.java" }
column id="source" { text "// the file" }
}
#files { flex-basis: 220px; flex-shrink: 0; }
#source { flex-grow: 1; flex-basis: 0; }
flex-grow shares out the space left after content. flex-shrink is 1 by default, which is CSS’s rule and the reason every control in controls.css declares flex-shrink: 0. flex-basis: 0 with flex-grow: 1 is a fixed share of the row, counted after the gaps, which is how a masonry’s columns are equal without anybody counting them. flex-basis: auto asks width or the content.
Width, height and limits
card id="note" {
text "A card no wider than a readable line and no narrower than its title."
}
#note { width: 50%; min-width: 320px; max-width: 640px; }
width and height are preferred sizes. A cramped row shrinks a box below its width unless flex-shrink is 0 or min-width holds it. “No limit” is undefined rather than zero, because a maximum of zero is a box that may not exist.
Position, inset and overflow
stack id="portrait" {
panel class="picture" { text "GB" }
badge "3"
}
#portrait badge { position: absolute; top: 4px; right: 4px; }
.picture { overflow: hidden; }
An absolute child is placed against the nearest ancestor that is not static, from its border box. inset takes the same one-to-four shorthand as padding. overflow: hidden clips the children to the content box. With a
border-radius, it also cuts them to the curve inside the border, so a picture
in a 34px box with border-radius: 17px is a circle. scroll and auto size the same as hidden and differ only in whether a scroll viewport offers bars. A stack sets position: absolute on its later children itself.
Density and the size tokens
A control’s height is the one metric that is a token rather than a literal, because the design system says a user preference moves it. Padding, gap and radius stay literal. The compact density is three custom properties and no rules, in the same cascade layer as a theme, and regular ships no stylesheet at all because it is what controls.css already is.
var sheets = Controls.stylesheets(Theme.NORD_DARK, Density.COMPACT);
| Token | Regular | Compact | Read by |
|---|---|---|---|
--gb-control-height | 32px | 28px | Every control’s height, through --gb-button-height, --gb-input-height and the rest |
--gb-list-row-height | 32px | 26px | list, tree, a select’s rows |
--gb-table-header-height | 36px | 30px | table |
--gb-code-box-width, --gb-code-box-height | 40px, 48px | 36px, 44px | code-input |
--gb-calendar-day | 32px | 28px | The date picker’s day cell |
The other size tokens a layout reads do not move with density.
| Token | Value | Read by |
|---|---|---|
--gb-field-label-width | 120px | A field’s label column |
--gb-scroll-line | 20px | A scroll, as one wheel line and one arrow key |
--gb-scrollbar-gutter | 0px, 12px with Scrollbars.ALWAYS | The room a scroll reserves beside its content |
--gb-scrollbar-size | 6px, 12px with Scrollbars.ALWAYS | The bar’s thickness |
A widget of your own that reads var(--gb-control-height) is compact-aware with no code. One that writes 32px cannot be made so by anything in the density sheet.
An application’s own sheet goes after the toolkit’s, in the application layer, and is written the same way.
var sheets = new ArrayList<>(Controls.stylesheets(Theme.NORD_DARK, Density.REGULAR));
sheets.add(Stylesheet.resource(CascadeLayer.APPLICATION, App.class, "app.css"));
How the layers cascade and what else a sheet may say is in Styling.
The catalogue
Every widget in Goldberry is a Java record, a KDL node and a CSS type, and this part documents each one under the name it has in markup.
By the end of this page you know what every widget shares, how a name in markup finds the thing it refers to, and which chapter holds the widget you are looking for. The chapters that follow show each widget three ways: a markup sample, the Java that builds the same tree, and the stylesheet rules that reach it.
Three ways to say one widget
A button is a Button record in Java, a button node in KDL and a button
type in CSS. A widget built from markup and the same widget built in Java are
equal values, so the three forms cannot drift.
column {
text "Delete this file?"
row {
spacer
button press="dismiss" "Cancel"
button class="danger" press="delete" "Delete"
}
}
new Column(
new Text("Delete this file?"),
new Row(
new Spacer(),
new Button("Cancel", this::dismiss),
new Button("Delete", this::delete).styled("danger")
)
);
Variants are classes. danger is class="danger" in markup,
.styled("danger") in Java and button.danger in a stylesheet, because a
class is the one spelling all three can use. styled, tooltip,
contextMenu and withAttributes are on Attributed, which every widget in
the catalogue implements. Nothing visual lives in a record. The
metrics are in controls.css and the colours are the theme’s tokens, so a theme
restyles a control whose rule never names one.
What every widget carries
Every widget holds an Attributes value. The inflater reads these properties off any node. In Java they have
withers on Attributes.NONE.
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The node’s id for #id rules. It doubles as the reconciler’s key, so a node with an id keeps its state and focus across a rebuild that reorders it |
class | string | none | Space-separated classes, for .name rules and variants |
tooltip | string | none | Text shown on hover, on any widget |
context-menu | string | none | The name of the menu a right-click opens, resolved by the application |
name | string | none | The accessible name, which wins over any name the widget derives |
lang | language tag | inherited | Locale for spelling and document hyphenation |
spellcheck | boolean | inherited | Enable or disable spelling in descendant fields |
var attributes = Attributes.NONE.id("save").classes("primary").tooltip("Ctrl+S");
new Button("Save", this::save).withAttributes(attributes);
In Java a key may differ from the id. Attributes.NONE.key(row) keys a list
item by its model row. The two hover hooks, onPointerEnter and
onPointerExit, are Java only, because a Runnable is not a KDL value.
Controls that can be disabled read disabled=#true. A disabled container
disables every descendant for input: nothing inside it is clicked, focused or
hovered. The cascade sees it too, so a rule can style a disabled subtree, while
the fade stays on the node that declared it.
What a name resolves against
Markup names things and cannot build them. Each kind of name has a registry,
and Widgets.inflater(named, icons, models) assembles all of them from a
model’s annotations.
| Attribute | Registry | What the name is |
|---|---|---|
press=, change=, link=, task= | ActionRegistry | A method. press names an action with no argument, the others one that is handed a value |
bind= | BindingRegistry | A value to follow, read-only. The widget subscribes and rebuilds when it changes |
icon= | Icons | An icon the application built and closes |
controller=, validator=, player=, renderer=, images= | Named | An object that neither changes nor needs closing |
A registry is strict by default, so press="delte" fails at inflation rather
than producing a button that does nothing. Widgets.inflater() with no
arguments binds nothing and complains about nothing, which is what a preview
wants. A value is named once, in its @Bind annotation, and a widget built in
Java follows it by the same path. Data flows down through bind= and events
flow up through actions. A widget is handed an Observable with no set on
it, so a control built from markup cannot write the model.
Parts are not widgets
A checkbox’s glyph, a chart’s plot and a legend’s swatch are parts. Each is a
CSS type a stylesheet can reach, check-indicator or chart-legend-swatch, and
none is a node a document can create. A part outside its widget means nothing,
so the inflater does not know its name. Each chapter’s Styling section lists
the parts a widget has.
The chapters
The GPU canvascanvas3d Layoutrow, column, spacer, stack, scroll, split-pane, masonry, affix
Every markup name
The 90 names the inflater knows, and where each is documented. The layout widgets have a part of their own.
| Name | Chapter |
|---|---|
action | Overlays |
affix | Layout |
area-chart | Charts |
audio-player | Audio and video |
badge | Buttons, badges and chips |
bar-chart | Charts |
breadcrumbs | Navigation |
button | Buttons, badges and chips |
camera-view | Camera |
canvas | Canvas, images and QR codes |
canvas3d | The GPU canvas |
card | Panels |
carousel | Panels |
checkbox | Choices |
chip | Buttons, badges and chips |
code-input | Fields and forms |
collapse | Panels |
color-picker | Fields and forms |
column | Layout |
crumb | Navigation |
date-picker | Fields and forms |
dialog | Overlays |
donut-chart | Charts |
entry | Panels |
field | Fields and forms |
form | Fields and forms |
group-box | Panels |
html-view | Markdown, HTML and the web |
hud | Overlays |
icon | Canvas, images and QR codes |
image | Canvas, images and QR codes |
item | Menus and the tray |
knob | Values and progress |
level-meter | Microphone |
line-chart | Charts |
link | Text and links |
list | Collections |
markdown-view | Markdown, HTML and the web |
marker | Panels |
masonry | Layout |
media-controls | Audio and video |
media-player | Audio and video |
menu | Menus and the tray |
menubar | Menus and the tray |
message | Overlays |
option | Choices |
page | Navigation |
panel | Panels |
point | Charts |
popover | Overlays |
pressable | Buttons, badges and chips |
progress | Values and progress |
qr-code | Canvas, images and QR codes |
radio | Choices |
radio-group | Choices |
rich-input | Fields and forms |
rich-text | Text and links |
row | Layout |
run | Text and links |
scroll | Layout |
segmented | Choices |
select | Choices |
separator | Menus and the tray |
series | Charts |
skeleton | Panels |
slider | Values and progress |
slot | Collections |
spacer | Layout |
sparkline | Charts |
spectrum-view | Microphone |
spinner | Values and progress |
split-pane | Layout |
stack | Layout |
statistic | Panels |
step | Navigation |
steps | Navigation |
svg-view | Canvas, images and QR codes |
tab | Panels |
table | Collections |
tabs | Panels |
text | Text and links |
text-area | Fields and forms |
text-input | Fields and forms |
time-picker | Fields and forms |
timeline | Panels |
toggle | Choices |
tree | Collections |
video-view | Audio and video |
waveform-view | Microphone |
wizard | Navigation |
Java only
Four widgets have no markup name, because each holds something a document cannot describe: a queue, a sequence of steps, a platform handle or a page.
- Toast and Tour are in Overlays.
- TrayIcon is in Menus and the tray.
- WebView is in Markdown, HTML and the web.
Text and links
A run of text that wraps where layout puts it, and a word that goes somewhere when pressed.
By the end of this chapter you can put a label on screen at any rank of the type scale, bind it to a value, and make a word open a screen or a web page.
text
A text is one run of text. It wraps at the width layout gives it and nothing
else about it is decided in Java.

A title, a caption and a bound value.
column {
text style="title" "The Red Book"
text class="caption" "Marked in a hand that was not steady"
text bind="app.status" "checking…"
}
import dev.goldberry.widgets.text.Text;
import dev.goldberry.widgets.text.TextRank;
new Column(
new Text("The Red Book").style(TextRank.TITLE),
new Text("Marked in a hand that was not steady").styled("caption"),
Text.of("checking…", Models.observable(app, "app.status"))
);
The argument is what the text says. With bind=, the argument is the fallback
shown until the bound value answers, and a null value draws as nothing rather
than as the word null. The value is read at render, so a change that lands
between a build and a frame is in that frame.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | the text, or the fallback when bind= is set |
bind | path | none | the value to follow, read-only |
style | rank name | none | one of the seven ranks below, added as a class; a name that is not one is refused |
class | string | none | CSS classes, space-separated |
id | string | none | the node’s id, which is also its reconciliation key |
tooltip | string | none | text shown on hover |
context-menu | string | none | the name of a menu a right-click opens |
name | string | none | the accessible name |
style= and class= are two spellings of one thing. text style="title" and
text class="title" both put the class title on the node, and a rule written
text.title matches either. The difference is that style= is checked when the
document inflates.
The type scale
The ranks are classes in controls.css. They inherit, so a class on a container
reaches every label under it.
| Class | Face | Size / line |
|---|---|---|
display | Inter 600 | 30 / 36 |
title | Inter 600 | 22 / 28 |
heading | Inter 600 | 17 / 22 |
body | Inter 400 | 15 / 20 |
body-strong | Inter 600 | 15 / 20 |
caption | Inter 400 | 13 / 16 |
mono | JetBrains Mono 400 | 15 / 20 |
The sizes are the theme’s tokens, --gb-font-title and so on, so a large-text
theme moves every rank at once. The showcase’s rank-display and card-title
classes are its own stylesheet’s and not the toolkit’s.
Wrapping and cutting
A text is a measured leaf: layout proposes a width, the paragraph wraps at it,
and the height that comes back sizes the box. The paragraph is shaped once and
re-wrapped by arithmetic.
To keep a label on one line, the stylesheet says so:
text.name { white-space: nowrap; text-overflow: ellipsis }
nowrap stops the wrap and ellipsis marks the cut. text-align places the
lines inside the box.
A log line keeps its spacing and cuts a word too long for the box:
text.log { white-space: pre-wrap; overflow-wrap: anywhere }
The paragraph never collapses spaces, so pre-wrap and pre-line wrap as
normal does and pre stays on one line as nowrap does. A word wider than
the whole line overflows unless overflow-wrap: anywhere cuts it between
grapheme clusters. word-break: break-all cuts any word at the edge.
Static text cannot be selected or copied. A text-input with
read-only=#true shows text a user can select, in
Fields and forms.
A sentence with two styles is a rich-text. Its individually
styled runs wrap as one paragraph.
Styling
- CSS type
text. - No parts.
- No pseudo-classes of its own. It is not focusable and takes no hover.
- Classes: the seven ranks above, and whatever the document writes.
A text sets no colour. color inherits from the nearest ancestor that sets
one, which is a card, a panel or the window.
Keyboard
None. A text is not a Tab stop.
rich-text
A rich-text is one paragraph made of runs, each in a style of its own. A
keyword can be gold and bold in the middle of a sentence, and the sentence still
wraps as one text.

Styled runs inside a paragraph.
column {
rich-text {
run "Give it "
run "Bleeding" class="keyword"
run " equal to the amount of boost it lost."
}
rich-text {
run "Order" class="keyword"
run ": Reset the power of a unit."
}
}
import dev.goldberry.widgets.text.RichText;
import dev.goldberry.widgets.text.Run;
new Column(
new RichText(
new Run("Give it "),
new Run("Bleeding", Set.of("keyword")),
new Run(" equal to the amount of boost it lost.")
),
new RichText(
new Run("Order", Set.of("keyword")),
new Run(": Reset the power of a unit.")
)
);
rich-text > run.keyword { color: var(--gb-warning-text); font-weight: bold }
A row of text nodes does not do this. Each text wraps inside its own box,
so a sentence split across three of them wraps as three columns. A rich-text
shapes each run in its own font, joins them into one paragraph and breaks the
lines over the whole of it. A line can end in the middle of a run and the next
one start there.
A line is as tall as the tallest font on it: the deepest ascent above the
baseline and the deepest share below it. A run at a larger size makes its own
line taller and leaves the others alone. Runs that look like the paragraph add
nothing, so a rich-text whose runs are unstyled draws exactly what a text
with the same words draws.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| children | run | none | the runs, in reading order; any other child is refused |
class | string | none | CSS classes, space-separated |
id | string | none | the node’s id, which is also its reconciliation key |
tooltip | string | none | text shown on hover |
context-menu | string | none | the name of a menu a right-click opens |
selectable | bool | #false | whether its words can be dragged across, selected and copied |
A rich-text takes no argument. Its words are its runs, and an argument is
refused when the document inflates.
Styling
- CSS type
rich-text. - Its children are
runnodes, styled by the cascade like any child, and onerich-text-selectionpart whosebackgroundis the selection’s highlight. - No pseudo-classes of its own. A selectable one is focusable.
- A run’s
backgroundis drawn behind its words, on every line they reach. run.pressableis a run with a press handler, which takes the link ink and the pointer cursor; the pointer over any run takes that run’scursor.run.spoileris covered until pressed:run.spoiler:not(.revealed)draws its words in no colour on a block of the muted ink, and a press addsrevealed.
The paragraph’s white-space, text-overflow, text-align, overflow-wrap,
word-break, padding and background are the rich-text’s. color, the font
and text-decoration are each run’s, inherited from the rich-text where a run
does not set them.
Keyboard
None, unless it is selectable: then it is a Tab stop, Ctrl+A selects all of
it and Ctrl+C copies what is selected. Losing the focus clears the
selection. Its accessible name is its runs’ text end to end, and its role is
text.
Pressing and selecting
new RichText(List.of(
new Run("Thanks "),
new Run("@frodo", Set.of("mention")).onPress(() -> openProfile("frodo")),
new Run(", the ending is "),
new Run("he leaves").spoiler(true)
), Attributes.NONE)
.selectable(true)
A click on a pressed run’s words, on any line they reach, runs its handler. A click on a covered spoiler reveals it and runs nothing. A drag across a selectable paragraph selects, and a drag that selected something is not a click. The selection belongs to one paragraph.
run
A run is one stretch of a rich-text: its argument is the words, spaces
included, and its classes are what the stylesheet styles it by. Runs are joined
as written, so the space between two words belongs to one of them.
rich-text {
run "Deal "
run "3" class="number"
run " damage."
}
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | the words |
class | string | none | CSS classes, space-separated |
id | string | none | the node’s id |
spoiler | bool | #false | covers the words until the run is pressed |
A run decides how its own words look: font-family, font-size,
font-weight, font-style, color, text-decoration and a solid
background, drawn behind its words. A run’s white-space, text-align and
padding are read by nothing, because a run has no box of its own inside the
paragraph. A press handler is code: Run.onPress(Runnable) in Java. A selector reaches it as a
child of its paragraph, rich-text > run.keyword, or by its classes alone.
Outside a rich-text, a run draws as a text with the same words would.
- CSS type
run. - No parts and no pseudo-classes.
link
A link is a word that does something: it runs an action, opens a URL through
the desktop, or both.

An action link, an external link and a visited one.
column {
link action="app.show-docs" "Read the docs"
link href="https://goldberry.dev" "Goldberry on the web"
link href="mailto:hello@example.org" visited=#true "Write to us"
}
import dev.goldberry.widgets.text.Link;
new Column(
new Link("Read the docs", actions::showDocs),
Link.external("Goldberry on the web", "https://goldberry.dev"),
Link.external("Write to us", "mailto:hello@example.org").visited(true)
);
action= is in-app navigation. href= is handed to the desktop’s own handler
for its scheme through Host.openExternal, and the link logs a warning when
the platform refuses it. A link with both runs the action and then opens the
target. A link with neither is a word in the link ink that takes no focus.
An external link draws the toolkit’s 12 px external-link icon after the word.
That icon is the one icon the toolkit builds itself, and the link’s state owns
it.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | required | the word; an empty label is refused |
action | action name | none | what an in-app link runs |
href | string | none | what an external link opens |
visited | boolean | #false | adds the visited class; the toolkit keeps no history, so this is the application’s to set |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
link. The record builds a node of this type. There are no parts. - Pseudo-classes:
:hoverunderlines,:focus-visibletakes the standard ring. - Classes:
visitedtakes--gb-text-muted;externalis set whenhref=is present.
The underline is text-decoration: underline in controls.css, drawn at the
face’s own position and thickness. The ink is --gb-button-link-text, a token
measured for 4.5:1 on every surface, and not the accent.
A link is block-level: a row of a word and sometimes an icon, on a line of its
own. It is not button.link, which is a button that reads as text and sits in a
toolbar. See Buttons, badges and chips.
Keyboard
| Key | Does |
|---|---|
Tab | reaches it, when it has an action or an href |
Enter | follows it |
Space does not activate a link, which is every browser’s rule. A link with
nothing behind it is not a Tab stop.
Buttons, badges and chips
Three stadium-shaped widgets: one you press, one you read, and one you choose. And a fourth with no shape at all, which makes anything pressable.
By the end of this chapter you can wire a button to an action, pick its variant with a class, float it in a window corner, show a count that follows a value, build a row of filter chips, and make a picture or a row pressable without a button’s box around it.
button
A button is a label, an icon, or both, with one action behind it.

The five variants. Each is a class, not a constructor argument.
row {
button press="app.save" "Save"
button class="primary" icon="plus" press="app.create" "New"
button class="danger" press="app.delete" "Delete"
button class="ghost" disabled=#true "Later"
button class="link" press="app.help" "What is this?"
}
import dev.goldberry.widgets.controls.button.Button;
new Row(
new Button("Save", actions::save),
new Button("New", actions::create).withIcon(plus).styled("primary"),
new Button("Delete", actions::delete).styled("danger"),
new Button("Later").styled("ghost").disabled(true),
new Button("What is this?", actions::help).styled("link")
);
The icon is borrowed. A widget is a value rebuilt every frame, so it must not
own something with a close(). The application builds its icons once in
start and keeps them. In markup icon= names an icon in the Icons
registry, and a button with an icon and no label is refused when the registry
does not supply that name, because it has nothing to fall back on.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | the label; a button needs a label or an icon |
icon | icon name | none | the icon before the label |
press | action name | none | what activating it runs |
disabled | boolean | #false | refuses every route to the action, leaves the Tab order, matches :disabled |
float | boolean | #false | lifts the button out of layout into the window’s overlay layer |
corner | top-start, top-end, bottom-start, bottom-end | bottom-end | which corner a floated button sits in; an unknown name falls back to the default |
name | string | none | the accessible name; an icon-only button needs one, and the label wins where there is one |
class, id, tooltip, context-menu | as on every widget |
A disabled button lays out, paints and hit-tests. It does not act, so a click on it lands nowhere rather than on whatever is behind it.
float=#true wraps the button in a Floated widget that keeps it at
--gb-window-margin from two window edges. It is placement, not appearance, so
it composes with every variant and shape. In Java the wrapper is
new Floated(button, Corner.BOTTOM_END).
Styling
- CSS type
button. - No parts. The label and the icon are child boxes the stylesheet does not address.
- Pseudo-classes:
:hover,:active,:focus-visible,:disabled. - Variant classes:
primary,danger,ghost,link, andoutlined, which composes withprimaryanddanger. - Shape classes:
squarefor radius 0,circlefor a full radius on a box as wide as it is tall. An icon-only button is acircleunless it sayssquare. - Placement class:
float, which the attribute sets.
The metrics are height 32, padding 12, gap 6, radius 8, in body-strong.
Compact density makes the height 28. button.link has 4 px of padding, the
regular weight and the ink --gb-button-link-text. It hovers with the ghost
wash and never underlines.
Disabled is 45% opacity on the whole control and never a colour remap, so a disabled danger button looks dangerous. The fade is applied once, by the outermost disabled node.
Keyboard
| Key | Does |
|---|---|
Tab | reaches it, unless disabled |
Space, Enter | activate it, once per press; a held key does not repeat |
A button activates on a click and not on a release. A press dragged off the button and let go is a cancelled click. A key with a modifier held is not consumed.
badge
A badge is a count or a status: text in a stadium that reports and takes
nothing back.

A count, a danger badge and a success badge bound to a value.
row {
badge "3"
badge class="danger" "offline"
badge class="success" bind="build.state" "passing"
}
import dev.goldberry.widgets.controls.badge.Badge;
new Row(
new Badge("3"),
new Badge("offline").styled("danger"),
Badge.of("passing", Models.observable(build, "build.state")).styled("success")
);
A count is the archetypal bound value. The argument stays as the fallback until
the binding answers, as a text’s does.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | what the badge says, or the fallback when bound |
bind | path | none | the value to show, as String.valueOf of whatever it holds |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
badge. - No parts.
- No pseudo-classes. A badge is not focusable, has no hover and no transition.
- Variant classes:
accent,danger,warning,success,info. The bare badge takes the neutral surface.
Height 20, minimum width 20, padding 4, full radius, in caption. The minimum
width equals the height so a one-digit badge is a circle. Each filled variant
pins its own foreground token, because white on the warning hue is 1.35:1.
Keyboard
None.
chip
A chip is a badge you can press: a filter that is on or off, a tag you can
take off, a token in a recipient row.

A selected chip, an outlined one with a dot, one with an icon and a dismiss, and a disabled one.
row {
chip bind="filter.unread" press="filter.toggle-unread" "Unread"
chip class="outlined success" dot=#true "Live"
chip icon="tag" dismiss="tags.drop-java" "java"
chip class="outlined" disabled=#true "Sealed"
}
import dev.goldberry.widgets.controls.chip.Chip;
new Row(
new Chip("Unread", false, actions::toggleUnread).bound(Models.observable(filter, "filter.unread")),
new Chip("Live").withDot(true).styled("outlined", "success"),
new Chip("java").withIcon(tag).onDismiss(() -> actions.drop("java")),
new Chip("Sealed").styled("outlined").disabled(true)
);
A chip selects nothing itself. Pressing raises press and the application
decides. The bound value, or the written selected, is what draws the
:checked state. That is the controlled loop every control runs. Dismissing
raises dismiss and removes nothing, because the list a row of chips shows is
the application’s.
Important
The dot and the icon are one slot. A chip asked for both is refused where it is built, because they are the same status at two resolutions.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | required | the word; an empty label is refused |
icon | icon name | none | a leading icon |
dot | boolean | #false | a 6 px status dot before the word |
dot-colour, dot-color | CSS colour | none | the dot’s colour as data; writing one turns the dot on |
selected | boolean | #false | the written state, mirrored to :checked when nothing is bound |
bind | path | none | a boolean the chip follows; wins over selected |
press | action name | none | what choosing it runs |
dismiss | action name | none | what the × runs; a chip with none has no × |
disabled | boolean | #false | drawn and hit-tested, neither pressable nor dismissable |
class, id, tooltip, context-menu, name | as on every widget |
The dot’s colour is a value and not a class, because a project’s hue lives in a
row of a database and a stylesheet cannot have a rule per project.
withDot(0xFFBF616A) is the Java spelling, and 0 means the stylesheet
decides.
Styling
- CSS type
chip. - Parts:
chip-dot,chip-label,chip-dismiss. - Pseudo-classes:
:hover,:active,:checked,:focus-visible. - Variant classes:
outlined,danger,warning,success,info. An outlined chip that is chosen is filled.
Height 24, padding 8, full radius, gap 6, in body. The dismiss mark is 12
square. A filled chip’s dot takes the foreground its fill guarantees contrast
against, and the hue itself only on an outlined chip.
A disabled chip has no opacity rule of its own in controls.css. It stops
responding and is left out of the Tab order, but it is drawn as an enabled one
is.
Keyboard
| Key | Does |
|---|---|
Tab | reaches it, when it has a press or a dismiss and is not disabled |
Space, Enter | press it |
Delete, Backspace | dismiss it, when it has a dismiss |
Both delete keys, because a chip is commonly the last thing before a text
field, where Backspace is what a hand reaches for.
pressable
Anything, made into something you press: a button’s behaviour with none of a button’s box.

A row made pressable, with no box of its own.
pressable name="Open release 2.4" press="app.open-release" class="release-row" {
row {
text "2.4.0"
text class="caption" "Released on Tuesday"
}
}
import dev.goldberry.widgets.controls.pressable.Pressable;
new Pressable("Open release 2.4", () -> open(release),
new Row(new Text("2.4.0"), new Text("Released on Tuesday").styled("caption")))
.styled("release-row");
A picture in a timeline that opens a viewer, a release row, a card on a board:
each already has a look, and a button around it would draw a second. A
pressable draws nothing of its own and behaves exactly as a button does. It
is a Tab stop, a click activates it, Space and Enter activate it, and
:hover, :active and :focus-visible match it from anywhere inside it.
disabled takes it out of the Tab order and refuses activation, for
everything inside it too. Behind a modal dialog it is out of reach, like the
rest of the application.
A press that something inside it handles belongs to that: a button in a
pressable row is pressed on its own and the row hears nothing. A key that
bubbles up from something focused inside it is left alone, so Enter in a
field does not also press the row the field is in.
A reader announces it as a button, so it must be named. Its content is a
picture or a row of texts, not a label, so the name cannot be worked out from
it the way a button’s is, and a pressable with no name is refused.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
name | string | required | What a reader announces it as. A pressable without one is refused |
press | action name | none | What activating it does |
disabled | boolean | #false | Refuses activation, leaves the Tab order and matches :disabled |
id, class | string | The usual |
Its children are its content, laid out in a column.
Styling
- CSS type
pressable, and no parts. - Pseudo-classes:
:hover,:active,:focus-visible,:disabled.
The stylesheet gives it the pointer cursor, the focus ring at a 4 px radius and the 45 % disabled fade, and nothing else: no padding, no surface, no hover wash. An application that wants a wash writes one on its own class:
.release-row:hover { background: var(--gb-overlay-hover); }
Keyboard
| Key | Does |
|---|---|
Tab | reaches it, unless disabled |
Space, Enter | activate it, once per press; a held key does not repeat |
Choices
A tick, a switch, one of several, and one or more from a list.
By the end of this chapter you can bind a checkbox or a switch to a boolean,
offer a choice as radios, a segmented bar or a dropdown, and let a user pick
several values from one select.
Every control here is controlled. Clicking a checkbox does not move the tick.
It raises change, the application sets the value, and the tick moves when the
bound value does. A control that will not move means the state did not change,
which is where the bug is.
checkbox
A checkbox is a tick with a label, in two states or three.

Checked, checked and disabled, and indeterminate.
column {
checkbox bind="prefs.frost" change="prefs.toggle-frost" "Frosted sidebar"
checkbox checked=#true disabled=#true "Sworn to the Fellowship"
checkbox indeterminate=#true "Some of them"
}
import dev.goldberry.widgets.controls.checkbox.Checkbox;
new Column(
Checkbox.of("Frosted sidebar", Models.observable(prefs, "prefs.frost"), actions::toggleFrost),
new Checkbox("Sworn to the Fellowship", Checkbox.Value.CHECKED).disabled(true),
new Checkbox("Some of them", Checkbox.Value.MIXED)
);
MIXED is a real state. A select-all over a partial selection is neither on
nor off, so it matches :indeterminate rather than :checked. Toggling never
produces it: clicking a mixed box asks for all of them. Only the application
can put a box there.
The bound value may be a Boolean or a Checkbox.Value. Anything else leaves
the written state standing.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | the label, which is part of the click target |
checked | boolean | #false | the written state |
indeterminate | boolean | #false | the mixed state; wins over checked |
bind | path | none | the value to follow; wins over the written state |
change | action name | none | raised on every toggle; it says that, not what |
disabled | boolean | #false | refuses the toggle and leaves the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
checkbox. - Parts:
check-indicator, the 16 px glyph, andcheck-mark, the tick inside it. - Pseudo-classes:
:checkedand:indeterminateon the control and oncheck-indicator;:hover,:active,:focus-visible,:disabled.
check-indicator:checked { background: var(--gb-accent) }
The glyph is a part, which is a CSS type that is not a node a document can
write. The mark exists in every state at opacity: 0 so that it can scale in
when checked. Every control and part declares flex-shrink: 0. The label does
not, so a cramped row ellipses the text and never squashes the glyph.
The hit target is at least 32 square and the label gap is 8.
Keyboard
| Key | Does |
|---|---|
Tab | reaches it, unless disabled |
Space | toggles it |
Enter deliberately does nothing. It belongs to a dialog’s default action, and
a checkbox that swallowed it would leave a form with no keyboard route to
submit.
toggle
A toggle is a switch: a pill with a disc that slides, and the one control
that acts on a release.

Bound, and on but disabled.
column {
toggle bind="prefs.frost" change="prefs.set-frost" "Frosted sidebar"
toggle on=#true disabled=#true "Bound by oath"
}
import dev.goldberry.widgets.controls.toggle.Toggle;
new Column(
Toggle.of("Frosted sidebar", Models.observable(prefs, "prefs.frost"), actions::setFrost),
new Toggle("Bound by oath", true).disabled(true)
);
change carries the state asked for, as a boolean, not “the other one”. A drag
of 8 px or more asks for the direction dragged, so dragging right on a switch
that is already on asks for on. A shorter drag is a click and flips it. The
8 is half of the thumb’s 16 px travel.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | the label |
on | boolean | #false | the written state |
bind | path | none | a boolean to follow; wins over on |
change | action name | none | told the state asked for, as "true" or "false" |
disabled | boolean | #false | refuses the gesture and leaves the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
In Java the handler is a Consumer<Boolean>. From markup the action receives
the string, so an @Action method takes a boolean.
Styling
- CSS type
toggle. - Parts:
toggle-track, the 36 by 20 pill, andtoggle-thumb, the 16 px disc. - Pseudo-classes:
:checkedon the control and ontoggle-track;:hover,:active,:focus-visible,:disabled.
toggle-track:checked toggle-thumb { transform: translate(16px) }
Where the thumb travels to is the stylesheet’s decision. The track’s padding is
2 because 2 + 16 + 16 + 2 = 36 is what makes the travel 16.
Keyboard
| Key | Does |
|---|---|
Tab | reaches it, unless disabled |
Space | flips it |
radio
A radio is one option in a group. It carries a value and a label, and the
group decides whether it is on.

A group with one selected and one disabled.
radio-group value="dark" {
radio value="dark" "Moria"
radio value="light" "Lothlórien"
radio value="system" disabled=#true "Follow the system"
}
import dev.goldberry.widgets.controls.radio.Radio;
import dev.goldberry.widgets.controls.radio.RadioGroup;
new RadioGroup("dark",
new Radio("dark", "Moria"),
new Radio("light", "Lothlórien"),
new Radio("system", "Follow the system").disabled(true));
selected is deliberately not an attribute. A document that could mark one
option selected could mark two, so the group rewrites each option with whether
its value matches on every build.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | required | what the group reports and matches on; an empty one is refused |
| argument | string | "" | the label |
disabled | boolean | #false | this option only; a disabled group fades once, not per option |
class, id, tooltip, context-menu, name | as on every widget |
The option’s key is its value, so a group whose options are filtered or reordered keeps each option’s element and the focus on it.
Styling
- CSS type
radio. - Parts:
radio-indicator, a 16 px ring, andradio-dotinside it. - Pseudo-classes:
:checkedon the control and onradio-indicator;:hover,:active,:focus-visible,:disabled.
Keyboard
| Key | Does |
|---|---|
Space | selects it |
The arrows are the group’s. See below.
radio-group
A radio-group holds the fact that exactly one of its options is on.

A group bound to a value, with a caption as a third child.
radio-group bind="prefs.theme" change="prefs.pick-theme" {
radio value="dark" "Moria"
radio value="light" "Lothlórien"
text class="caption" "The switch in the title bar moves these too"
}
RadioGroup.of(Models.observable(prefs, "prefs.theme"), actions::pickTheme,
new Radio("dark", "Moria"),
new Radio("light", "Lothlórien"));
A value no option carries selects nothing, which is right for a model that has
not loaded. A child that is not a radio, a caption or a separator, is left
exactly where it was written.
change has to say which one, so it is an action that takes an argument. In
Java the handler is a Consumer<String>. From markup, an @Action method with
one String parameter receives the value, and a plain Runnable also resolves
for a handler that reads the model itself.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | none | the written selection |
bind | path | none | the value to follow; wins over value |
change | action name | none | told the value of the option asked for |
disabled | boolean | #false | the whole group, out of the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
The children are the options.
Styling
- CSS type
radio-group. It is a column incontrols.css; the classinlinemakes it a row. - No parts of its own. The options are
radionodes. - Pseudo-classes:
:disabled.
The widget names the semantics and the stylesheet names the axis, which is why the direction is a class and not an attribute.
Keyboard
| Key | Does |
|---|---|
Tab | enters the group at the selected option, or leaves it |
Left, Up | move to the previous option and select it |
Right, Down | move to the next option and select it |
Space | selects the focused option |
The group is one Tab stop and the arrows rove inside it. The entry point is
derived from :checked rather than remembered, so the selection is the roving
position and the two cannot disagree. Selection follows focus the controlled
way: an arrow raises change and does not move the dot.
segmented
A segmented control is a radio group drawn as one bar, with the arrows on its
own axis.

Three options, the bound one filled.
segmented bind="view.mode" change="view.set-mode" {
option value="list" "List"
option value="grid" "Grid"
option value="map" icon="map" "Map"
}
import dev.goldberry.widgets.controls.segmented.Segmented;
import dev.goldberry.widgets.controls.option.Option;
Segmented.of(Models.observable(view, "view.mode"), actions::setMode,
new Option("list", "List"),
new Option("grid", "Grid"),
new Option("map", "Map").withIcon(map));
An icon-only segment is option value="map" icon="map" name="Map". In a
document that is only as real as its icon registry: with no icon bound to
map, the option has neither a label nor an icon and is refused.
It shares radio-group’s model exactly: one Tab stop, exactly one selected,
change reports the value. It is a separate widget because the two are not
substitutable in a layout. A bar belongs in a toolbar and a group belongs in a
form.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | none | the written selection |
bind | path | none | the value to follow; wins over value |
change | action name | none | told the value of the segment asked for |
disabled | boolean | #false | the whole bar |
class, id, tooltip, context-menu, name | as on every widget |
The children are option nodes.
Styling
- CSS type
segmented. - Parts:
segmented-track,segmented-indicator, which travels under the selected segment and matches:checked, andsegmented-divider, which takes the classbeside-selectionon the two hairlines that fade out. - The segments are
optionnodes with:checked,:hover,:active,:focus-visibleand:disabled. - Pseudo-classes on the bar:
:disabled.
Height 32, segment padding 12, radius 8 on the outer corners and 0 between,
in body-strong. Segments are equal, each exactly 1/n of the bar, so the indicator travels by a
percentage. Each is as wide as the widest segment’s label, so a bar that nothing
sizes is as wide as its segments. A column that stretches it, or a width,
still sizes it, and the segments share what they are given equally.
Keyboard
| Key | Does |
|---|---|
Tab | enters the bar at the selected segment |
Left, Right | move and select |
Space | selects the focused segment |
Up and Down stay with whatever is above and below, because a bar has an
axis of its own.
select
A select is a closed control and a list that opens in a window of its own,
so it is never clipped by the card it sits in.

Single, multiple as chips, and an autocomplete with a placeholder.
column {
select bind="prefs.theme" change="prefs.pick-theme" placeholder="Choose a light" {
option value="dark" "Moria"
option value="light" "Lothlórien"
}
select multiple=#true bind="prefs.tongues" change="prefs.toggle-tongue" {
option value="sindarin" "Sindarin"
option value="quenya" "Quenya"
option value="westron" "Westron"
}
select autocomplete=#true free=#true query="places.search" options="places.matches" \
bind="places.chosen" change="places.choose" placeholder="Anywhere in the West"
}
import dev.goldberry.widgets.controls.select.Select;
Select.of(Models.observable(prefs, "prefs.theme"), actions::pickTheme,
new Option("dark", "Moria"),
new Option("light", "Lothlórien"))
.placeholder("Choose a light");
Select.of(Models.observable(prefs, "prefs.tongues"), actions::toggleTongue, tongues)
.multiple(true);
new Select(place, actions::choose, matches.toArray(Option[]::new))
.autocomplete(actions::search)
.free(true);
The closed control shows the selected option’s label, or the placeholder. It is as wide as its widest option, so it does not change width as the value does.
multiple=#true makes the selection a set. The bound value is a
Collection, each chosen value is drawn as a chip inside the closed control
with a ×, and change is a toggle: asking for a value the set already holds
takes it out. The list stays open while values are picked.
autocomplete=#true puts a real text-input in the closed control. Typing
raises query with the text, the application answers by supplying new
options, and the list narrows. The filtering is the application’s, so a
remote-backed combobox is the same widget with a slower model. A free-typed
value is refused unless free=#true. In markup, options= names a bound list
of Option values that replaces the written ones each time it changes.
A tree is Java only. select.tree(roots) takes a list of TreeNode and
opens a tree instead of a flat list, leaf-only by default. A tree’s model is
nodes with suppliers under them, which a document has no way to write.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | none | the written selection |
bind | path | none | the value to follow; a Collection when multiple |
change | action name | none | told the value chosen, or toggled when multiple |
placeholder | string | "" | shown when nothing is selected |
multiple | boolean | #false | the selection is a set drawn as chips |
autocomplete | boolean | #false | the closed control is a field you type in |
free | boolean | #false | a typed value that matches no option is accepted |
query | action name | none | told the typed text, when autocomplete |
options | path | none | a bound List<Option> that replaces the written options |
disabled | boolean | #false | the whole control |
class, id, tooltip, context-menu, name | as on every widget |
The children are option nodes. Anything else is left where it was written.
Styling
- CSS type
select. - Parts:
select-value, which takes the classplaceholderwhen standing in for a value;select-chevron;select-chipsandselect-chipwithselect-chip-labelandselect-chip-remove, whenmultiple;select-list, the popup, holdingoptionrows; andselect text-input, the field, whenautocomplete. - Pseudo-classes:
:hover,:focus-visible,:disabled. - Classes:
openwhile the list is up, andmultiple.
The closed control is a well like text-input, height 32, padding 8, radius
4, in body. In the list a row is a list row’s height and its label is
body, the chosen row takes --gb-selection, and the row the keyboard is on
takes :focus-visible.
Keyboard
| Key | Does |
|---|---|
Tab | reaches the closed control |
Space | opens the list, unless autocomplete, where it types a space |
Down, Up, Alt+Down | open the list |
Down, Up in the list | move the focus between rows |
Enter | chooses the focused row |
Esc | closes the list; with autocomplete, restores the last committed value |
Arrows move and Enter chooses, which is the opposite of a segmented bar’s
roving selection. The shared option record carries which of the two it is in.
Typing on the closed control is typeahead over the labels.
option
An option is one choice, in a segmented bar or a select list. It carries
a value and a label, an icon, or both.

The chosen option, drawn with its icon.
select value="grid" {
option value="list" "List"
option value="grid" icon="grid" "Grid"
option value="map" disabled=#true "Map"
}
new Select("grid", actions::setMode,
new Option("list", "List"),
new Option("grid", "Grid").withIcon(grid),
new Option("map", "Map").disabled(true));
Whether it is selected and what selecting it does are its container’s, set on
every build. new Option("list") uses the value as the label.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | required | what the container reports and matches on |
| argument | string | "" | the label; an option needs a label or an icon |
icon | icon name | none | an icon before the label |
disabled | boolean | #false | this option only |
name | string | none | the accessible name an icon-only option needs |
class, id, tooltip, context-menu | as on every widget |
Styling
- CSS type
option. - No parts.
- Pseudo-classes:
:checked,:hover,:active,:focus-visible,:disabled.
A label that does not fit is cut with an ellipsis rather than wrapped.
Keyboard
Space selects it in a bar. Space or Enter chooses it in a list. The
arrows are the container’s.
Values and progress
Two controls whose value is a number, and two that report one back.
By the end of this chapter you can bind a slider or a knob to a numeric value, snap it to steps, label it, give a fader a decibel taper, and show progress that is known or unknown.
A slider and a knob are controlled like every other control. Dragging raises
change with the value asked for, the application sets the property, and the
thumb moves when the bound value does. The bound value is any Number.
Anything else leaves the written value standing.
slider
A slider is a thumb on a track whose position is a number between min and
max.

Horizontal, vertical, and disabled.
column {
slider min=0 max=100 step=5 ticks=5 format="%.0f%%" bind="audio.gain" change="audio.set-gain"
slider class="vertical" scale="db" max=1 format="%.2f" bind="audio.gain" change="audio.set-gain" commit="audio.seek"
slider min=0 max=100 value=70 disabled=#true
}
import dev.goldberry.widgets.controls.slider.Slider;
import dev.goldberry.widgets.controls.Scale;
new Column(
Slider.of(0, 100, 5, Models.observable(audio, "audio.gain"), actions::setGain)
.ticks(5)
.format("%.0f%%"),
Slider.of(0, 1, 0, Models.observable(audio, "audio.gain"), actions::setGain)
.scale(Scale.decibels())
.format("%.2f")
.onCommit(actions::seek)
.styled("vertical"),
new Slider(0, 100, 70, 0, null).disabled(true)
);
The control snaps and clamps so no application has to. Steps count from min,
an arrow offers the next reachable value, and both ends are always reachable
even when the range is not a whole number of steps.
format= is a String.format pattern over a double, checked when the slider
is built. format="%d" is refused at inflation rather than on the first frame
with a value to draw.
scale="db" places a linear gain at a position that is linear in decibels,
with the floor at −60 dB. Half gain sits 90% of the way up and the bottom of
the travel is silence exactly. It needs min >= 0 and max > 0.
commit= is told the settled value when a press or drag is released and after
each key step, for work that should not run per drag step, such as a media
seek. In Java, spans(List<Slider.Span>) marks stretches of the range in the
groove, such as a seek bar’s buffered ranges. A document cannot write them.
marks(List<Double>) notches points of the range across the groove, over the
fill and under the thumb (slider-mark, --gb-slider-mark-bg), such as where
a seek bar’s chapters start. A document cannot write them either.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
min | number | 0 | the low end |
max | number | 1 | the high end; must be above min |
value | number | min | the written value |
step | number | 0 | the grid, counted from min; 0 is continuous |
ticks | integer | 0 | tick marks along the travel, the ends included; 1 is refused |
format | pattern | none | draws a value label from this String.format pattern |
scale | linear, db | linear | how a value maps to a position |
bind | path | none | a Number to follow |
change | action name | none | told the value asked for, on every step of a drag |
commit | action name | none | told the value when the gesture ends |
disabled | boolean | #false | out of the Tab order, no gesture |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
slider. The classverticalmakes it a fader. - Parts:
slider-track,slider-groove,slider-fill,slider-rest,slider-span,slider-thumb,slider-ticks,slider-tick,slider-value. - Pseudo-classes:
:hoverand:activeonslider-thumb;:focus-visibleand:disabledon the control.
The thumb lands f of the way along the track because slider-fill grows by
f and slider-rest by 1 - f. Nothing in Java learns the track’s width. The
value is measured along slider-track and not along the control, which is what
keeps a labelled slider honest at its far end.
Track 4, thumb 16 with a full radius and a 1 px edge, a hit target of at least 32 across. The ticks sit in a row of height 0 so two sliders in one list, one with a scale and one without, sit at the same height.
Keyboard
| Key | Does |
|---|---|
Tab | reaches it, unless disabled |
Left, Down | one step down |
Right, Up | one step up |
PgDn, PgUp | ten steps, or a tenth of the range when step is 0 |
Home, End | min, max |
Every key step raises change and then commit. A key with a modifier is
left alone.
knob
A knob is a rotary control: a dial with a pointer, an arc that fills as the
value rises, and a vertical drag as its gesture.

A detented knob and a large circular one.
row {
knob min=0 max=100 step=5 detents=5 bind="audio.gain" change="audio.set-gain"
knob class="large" drag="circular" bind="audio.pan" change="audio.set-pan"
}
import dev.goldberry.widgets.controls.knob.Knob;
new Row(
Knob.of(0, 100, 5, Models.observable(audio, "audio.gain"), actions::setGain).detents(5),
Knob.of(0, 1, 0, Models.observable(audio, "audio.pan"), actions::setPan)
.circular(true)
.styled("large")
);
Dragging up turns it up: 200 px of drag is the whole range, and Shift makes
the drag ten times finer. The gesture is a rate from where the press started,
so the value does not jump to the pointer. A click on the ring positions the
value at that angle. A click on the dial grabs it and does not jump. The wheel
steps it, down the document is down.
drag="circular" turns the knob round its dial instead, following the angle
of the pointer, and refuses to jump across the gap at the bottom.
Detents are positions the value is pulled to when a drag comes within a quarter of their spacing. Five detents over 0 to 100 are 0, 25, 50, 75 and 100.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
min | number | 0 | the low end |
max | number | 1 | the high end; must be above min |
value | number | min | the written value |
step | number | 0 | the grid; 0 is continuous |
detents | integer | 0 | positions a drag is pulled to, the ends included; 1 is refused |
drag | circular | none | turn round the dial instead of up and down |
bind | path | none | a Number to follow |
change | action name | none | told the value asked for |
disabled | boolean | #false | out of the Tab order, no gesture |
class, id, tooltip, context-menu, name | as on every widget |
There is no commit= on a knob.
Styling
- CSS type
knob. The classlargemakes it 48 instead of 32. - Parts:
knob-track, the full arc in the muted ink;knob-arc, the filled part;knob-dial, the disc with the pointer. - Pseudo-classes:
:hoverand:activeonknob-dial;:focus-visibleand:disabledon the control.
The arc is 270 degrees starting at 7:30. The dial is inset 5 from the ring and
the pointer is a 2 px stroke in the dial’s own colour token. The arc and the
pointer are strokes, so they take color like every other mark.
Keyboard
| Key | Does |
|---|---|
Tab | reaches it, unless disabled |
Left, Down | one step down |
Right, Up | one step up |
PgDn, PgUp | ten steps, or a tenth of the range when step is 0 |
Home, End | min, max |
The keys are always consumed, even at an end, so a knob at its maximum owns
Right and focus does not leave it.
progress
A progress bar reports a value out of a maximum, or that something is
happening and nobody can say how much is left.

A value, a bound value, and indeterminate.
column {
progress value=0.4
progress max=100 bind="download.received"
progress indeterminate=#true
}
import dev.goldberry.widgets.controls.progressbar.Progress;
new Column(
new Progress(0.4),
Progress.of(100, Models.observable(download, "download.received")),
Progress.sweeping()
);
A determinate bar’s fill is a plain width, the value divided by max and
clamped to the track. An indeterminate bar sweeps by a transform, turns at
the ends rather than running off them, and keeps the frame loop awake while it
is on screen. Two indeterminate bars in one window are in step by
construction, because the phase is read from the clock and nothing is stored.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | number | 0 | the written value |
max | number | 1 | what a full bar is; must be positive |
indeterminate | boolean | #false | sweep instead of fill |
bind | path | none | a Number to follow |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
progress. - Parts:
progress-fill. - Pseudo-classes:
:indeterminate.
progress-fill { background: var(--gb-progress-fill-bg) }
progress:indeterminate progress-fill { background: var(--gb-accent) }
Track height 4, full radius, overflow: hidden on the track so the sweep is
cut at both edges. A value change moves the fill’s width instantly and
transitions its colour,
because width is not on the motion whitelist. Under reduced motion the sweep
holds still at a third of the track.
Keyboard
None. A progress bar takes nothing back.
spinner
A spinner is a ring that turns, for a wait with no measure.

Three sizes.
row {
spinner size="small"
spinner
spinner size="large"
}
import dev.goldberry.widgets.controls.spinner.Spinner;
import dev.goldberry.widgets.controls.spinner.SpinnerSize;
new Row(
new Spinner(SpinnerSize.SMALL),
new Spinner(),
new Spinner(SpinnerSize.LARGE)
);
Small sits beside a line of text or inside a busy control, medium is the default, and large stands on its own for a region that is not ready. A full turn takes 900 ms and the phase is the clock’s, so every spinner in a window turns together.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
size | small, medium, large | medium | 12, 16 or 32 px; another word is refused |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
spinner. - No parts. The ring is a mark the widget paints.
- No pseudo-classes.
- Classes:
small,medium,large, which the size puts on the node.
The diameter is the stylesheet’s and the stroke is the widget’s. size= puts
a class on the node, controls.css gives that class a width, and the widget
weights the stroke from the width the cascade resolved, so #busy { width: 48px } gets a stroke to match. The ring takes color. Under reduced motion it
stops.
Keyboard
None.
Fields and forms
A field owns its caret and tells the model, and a form is found by its fields.
By the end of this chapter you can put a text field on screen, bind it, filter
what it accepts, wrap it in a labelled field with a validator, submit a
form from a button, and take a date, a time, a colour or a one-time code.
How a field talks to the model
A field holds its own text, caret, selection and undo stack. None of those are
things a model can hold, so bind= is the initial text and an override, and
change= reports each new value. The field ignores the echo of its own
keystroke rather than resetting the caret on every letter.
An input method composes inline. The composition is drawn underlined at the
caret with its converting clause highlighted, held beside the value rather than
in it, so change= fires once for the accepted candidate and not once per
keystroke. A password refuses to compose, because a candidate window is a
second, unmasked window showing what is being typed. Committed text arrives
all the same.
Right-to-left text reads from the right in both fields. The caret, a click and
a selection follow the text as it is drawn, and the arrow keys move through it
in reading order: Left moves on in a right-to-left paragraph. A field’s base
direction is its direction; unicode-bidi: plaintext lets each paragraph
find its own.

The Forms screen of the showcase.
text-input
A text-input is a single line of text in a well.

Bound, filtered, password, read-only and disabled.
column {
text-input bind="app.name" change="app.set-name" placeholder="Your name" max-length=40
text-input bind="app.port" change="app.set-port" filter="digits" max-length=5
text-input password=#true placeholder="The word that opens the doors"
text-input value="Copied from the Red Book" read-only=#true
text-input value="Speak, friend" disabled=#true
}
import dev.goldberry.widgets.form.textinput.TextInput;
import dev.goldberry.widgets.form.textinput.TextFilter;
new Column(
TextInput.of(Models.observable(app, "app.name"), actions::setName)
.placeholder("Your name")
.maxLength(40),
TextInput.of(Models.observable(app, "app.port"), actions::setPort)
.filter(TextFilter.DIGITS)
.maxLength(5),
new TextInput().password(true).placeholder("The word that opens the doors"),
new TextInput("Copied from the Red Book", null).readOnly(true),
new TextInput("Speak, friend", null).disabled(true)
);
A filter rejects and never corrects: a keystroke or a paste the filter refuses
leaves the field as it was. A paste past max-length is clipped, not refused.
A read-only field has a caret and a selection and takes no edit. A disabled one
is out of the Tab order.
Suggestions under a field are TextInput.suggesting(options) in Java. The
field reports what was typed through change, is rebuilt with a list, and
reports a chosen suggestion through the same change. In markup,
suggestions= names a bound List<Option> the answer lands in.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | "" | the written text |
bind | path | none | the text to follow; the initial value and an override |
change | action name | none | told the whole value after every edit |
placeholder | string | "" | shown while empty, in --gb-text-placeholder |
max-length | integer | unlimited | characters; 0 or less means no limit |
password | boolean | #false | masks the text, refuses copy and cut, composes nothing |
read-only | boolean | #false | a caret and a selection, no edits |
filter | none, digits, integer, alnum | none | what the field accepts; an unknown name is logged and the field accepts anything |
suggestions | path | none | a bound List<Option> shown under the field |
disabled | boolean | #false | out of the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
alphanumeric is accepted as a spelling of alnum.
Styling
- CSS type
text-input. - Parts:
text-value, which takes the classplaceholderwhile empty;text-caret;text-selection;text-composition, the rule under an open composition. - Pseudo-classes:
:hover,:focus-visible,:disabled. Inside afield,field:invalid text-inputdraws the danger border.
Height 32, padding 8, radius 4, in body. The fill is --gb-surface-sunken,
an alpha, so a field is one step below the page, a panel or a card alike. The
caret and the selection are one line tall, and the caret is
--gb-caret-width wide. text-align places the value in the field and the
caret with it.
Keyboard
One key map serves text-input, text-area and the canvas Editor.
| Key | Does |
|---|---|
Left, Right | move the caret |
Ctrl+Left, Ctrl+Right | move by word; in a password, to the start or the end |
Home, End | the start and the end of the line |
Shift with any of these | extends the selection |
Ctrl+A | selects all |
Backspace, Delete | delete one character; with Ctrl, a word |
Ctrl+Z, Ctrl+Shift+Z, Ctrl+Y | undo and redo; a typing run is one step |
Ctrl+X, Ctrl+C, Ctrl+V | cut, copy and paste; a password refuses the first two |
Tab | moves focus; the field does not consume it |
The accelerators are on the platform’s modifier, so they are Cmd on macOS
and Ctrl elsewhere. Word movement stays on Ctrl everywhere.
A click places the caret and a drag is a selection. Where the platform has a primary selection, a finished selection is published and a middle click pastes it at the pointer.
A secondary click, the Menu key or Shift+F10 opens the field’s menu: Cut,
Copy, Paste and Select all, each disabled while it cannot run. Paste follows
the clipboard while the menu is open, so copying in another window enables it.
A password field’s Cut and Copy stay disabled. A context-menu= on the field
replaces this menu.
text-area
A text-area is text-input with a second dimension: soft wrap, a height that
grows between two row counts, and a scrollbar past the second.

Three rows, a gutter, and one that fills.
column {
text-area bind="app.bio" change="app.set-bio" rows=3 max-rows=6 placeholder="A few lines"
text-area class="mono" gutter=#true rows=8 max-rows=8 bind="app.notes" change="app.set-notes"
text-area fill=#true bind="doc.source" change="doc.set-source"
}
import dev.goldberry.widgets.form.textarea.TextArea;
new Column(
TextArea.of(Models.observable(app, "app.bio"), actions::setBio)
.rows(3, 6)
.placeholder("A few lines"),
TextArea.of(Models.observable(app, "app.notes"), actions::setNotes)
.rows(8, 8)
.gutter(true)
.styled("mono"),
TextArea.of(Models.observable(doc, "doc.source"), actions::setSource)
.fill(true)
.onEdit(actions::remember)
.edit(pending)
);
gutter=#true numbers the lines you typed, at the positions the wrap put
them. A paragraph that soft-wraps into three lines takes one number and three
lines’ height, which is why a column of numbers built beside the control does
not work.
fill=#true makes it an editor rather than a field: it takes the height
its container gives it and scrolls inside that.
onEdit and edit are Java only and are the seam a shortcut needs.
change= says what the text is and nothing about where. onEdit is told a
TextEdit of text, anchor and caret after every change, caret moves included,
and edit(TextEdit) offers an edit the application computed, caret and all. A
TextEdit is not a value a document can write.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | "" | the written text |
bind | path | none | the text to follow |
change | action name | none | told the whole value after every edit |
placeholder | string | "" | shown while empty |
rows | integer | 3 | the height to start at, in lines; at least 1 |
max-rows | integer | 10, or rows if larger | the height to grow to before scrolling |
max-length | integer | unlimited | characters |
fill | boolean | #false | take the container’s height and scroll inside it |
gutter | boolean | #false | number the hard lines down the left edge |
read-only | boolean | #false | a caret and a selection, no edits |
disabled | boolean | #false | out of the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
text-area. - Parts:
text-input’s four, one highlight and one composition rule per visual line, andtext-area-gutter, the strip of numbers. - Pseudo-classes:
:hover,:focus-visible,:disabled.
Minimum height 64, padding 8, radius 4. The gutter’s ink is
--gb-gutter-color and its room is --gb-gutter-gap, and the column is
measured in whatever font the node resolved, which is why the showcase gives a
gutter class="mono". Past max-rows it draws scroll’s overlay bar over its
own offset.
The height is the widget’s and not the stylesheet’s, because it is a function of how many lines the text wrapped into.
Keyboard
text-input’s map, and:
| Key | Does |
|---|---|
Enter | breaks a line |
Up, Down | move a line, keeping the column |
Home, End | the start and the end of the visual line |
Ctrl+Home, Ctrl+End | the start and the end of the text |
| wheel | three lines of this control’s own text per notch |
The same menu as text-input’s opens on a secondary click.
rich-input
A rich-input is a field that takes formatting: bold, italic, underline,
strike-through, code, spoilers, links and mentions, in a message being written.
It grows from rows to max-rows with its text and scrolls after that, as a
text-area does.

An empty rich input ready for a message.
column {
rich-input placeholder="Message" rows=1 max-rows=8
}
import dev.goldberry.text.mark.MarkedText;
import dev.goldberry.widgets.form.richinput.RichInput;
new RichInput(draft, next -> draft = next)
.placeholder("Message")
.maxRows(8);
Its value is a MarkedText: the words, and the marks over them as ranges of
char offsets. Those are the units a String is indexed by, and the ones a
messenger’s entities are counted in, so a message converts one mark to one
entity with no arithmetic. bind= follows a value that holds a MarkedText
or a plain String.
Keyboard
Every key a text-area takes, and the formatting keys, on the desktop’s own
modifier (Cmd on macOS):
| Keys | Does |
|---|---|
Ctrl+B, Ctrl+I, Ctrl+U | Bold, italic, underline |
Ctrl+Shift+X | Strike-through |
Ctrl+Shift+M | Code |
Ctrl+Shift+P | Spoiler |
Ctrl+Shift+N | Clear formatting |
Ctrl+K | A link: the address editor |
With a selection, a key turns its style on over all of it, or off when all of it has the style already. With nothing selected, it turns the style on or off for what is typed next, until the caret moves. Undo brings formatting back with the words: a style turned on is one step. A copy keeps its marks when it is pasted into another rich field, and is plain text everywhere else.
The formatting bar
Select words and let go, and a bar opens above them: bold, italic, underline, strike-through, code, spoiler, link and clear formatting. A button whose style covers the whole selection is lit. The bar never takes the keyboard, so the selection stays where it was while you press it, and it goes when the selection does.
new RichInput(draft, onChange).formatting(List.of(
new FormatButton("bold", "Bold", new FormatCommand.Toggle(MarkKind.Style.BOLD)),
new FormatButton("link", "Link", FormatCommand.Simple.LINK)
));
formatting(List.of()) takes the bar away, and formatting=#false does in
markup. The same commands are in the text menu, under Format.
Ctrl+K, or the bar’s Link, opens a small editor for the address under the
selection; with the caret in a link and nothing selected, it edits that link.
An address typed without a scheme is https.
Sending
new RichInput(draft, onChange).onSubmit(message -> send(message));
With onSubmit, Enter sends the text and Shift+Enter breaks the line, as a
message composer does. Without it, Enter breaks the line.
Mentions
Type @ at the start of a word and the field opens a query: it tells the
application what is typed after the trigger, letter by letter, and where it
is. The application looks people up and shows its own list. The field draws
none, because who can be mentioned, how a suggestion looks and where the list
goes are the application’s.
import dev.goldberry.widgets.form.richinput.MentionPrompt;
import dev.goldberry.widgets.form.richinput.Mentions;
new RichInput(draft, onChange)
.mentions(Mentions.on(this::suggest, "@", "#").keys(this::listKey));
void suggest(Optional<MentionPrompt> prompt) {
prompt.ifPresentOrElse(
open -> showPeople(lookUp(open.query().query()), open.anchor()),
this::hidePeople
);
}
void choose(Person person) {
prompt.complete("@" + person.name(), new MarkKind.Mention(person.id()));
}
A query is a trigger at the start of the text, after a space or after an
opening bracket or quote, and the letters, digits and _ after it. So
mail@example opens none, and a space, a comma or a caret moved away closes
one. onQuery hears it open, hears every change, and hears
Optional.empty() once when it ends. anchor() is the query’s line in window
coordinates, which is what a popup is opened against.
While a query is open, Up, Down, Enter, Tab and Escape are offered
to the key handler first, and it returns true for a key it takes. An Escape
it leaves closes the query until the caret leaves the word.
complete replaces the whole word, trigger included, with the text you give
under the kind you give, and adds a space after it. It is one undo step. A
MarkKind.Mention makes the text an atom; null puts in plain text, such as an
emoji for a : shortcode. A prompt answers only for the query it was made
for: once another letter is typed, completing the old one changes nothing.
A mention is an atom. The caret steps over it, a click inside lands at its
nearer end, a selection grows to cover it, and Backspace next to it removes
all of it. An input method cannot start a composition inside one.
Markdown and HTML
goldberry-html converts marked text both ways. MarkedMarkdown writes a
message’s Markdown and reads it back, and MarkedHtml does the same for HTML:
import dev.goldberry.html.marked.MarkedHtml;
import dev.goldberry.markdown.marked.MarkedMarkdown;
String markdown = MarkedMarkdown.write(draft); // "Ship it **today**"
MarkedText typed = MarkedMarkdown.read("Ship it **today**");
String html = MarkedHtml.write(draft); // "Ship it <strong>today</strong>"
The Markdown is the kind a messenger accepts: **bold**, *italic*,
underline, strikethrough, inline code, spoilers and links,
and a mention as a link to mention: and its id. Text that looks like markup
is escaped, so it reads back as itself. Markdown cannot say everything marks
can: a mark across a line break comes back as one per line, and whitespace at
the edge of bold or italic falls outside it.
To keep formatting on the clipboard beyond other rich fields, install the HTML format. A copy then offers HTML to a word processor, and a paste from a browser or a document editor keeps its bold, italic, links and code:
new RichInput(draft, onChange).clipboardFormats(List.of(MarkedHtml.format()));
A paste prefers the toolkit’s own type, then each installed format in turn, then the plain text.
A format is three methods, so an application can add its own: the type it is
offered under, how marked text is written in it, and how it is read back.
read gets bytes from another process, so it answers nothing rather than
throwing:
import dev.goldberry.text.mark.MarkedFormat;
record MarkdownFormat() implements MarkedFormat {
public String mime() { return "text/markdown"; }
public byte[] write(MarkedText text) {
return MarkedMarkdown.write(text).getBytes(StandardCharsets.UTF_8);
}
public Optional<MarkedText> read(byte[] bytes) {
return Optional.of(MarkedMarkdown.read(new String(bytes, StandardCharsets.UTF_8)));
}
}
new RichInput(draft, onChange).clipboardFormats(List.of(MarkedHtml.format(), new MarkdownFormat()));
Styling the marks
Each set of marks in the text is a mark node under the field, with a class
per kind: bold, italic, underline, strike, code, spoiler, link,
mention, or the name of a kind an application adds. The field draws its
marked words with what the cascade resolved for that node:
rich-input > mark.code { font-family: "JetBrains Mono"; background: var(--gb-surface); }
rich-input > mark.bold.italic { color: var(--gb-accent); }
A mark’s font, color, text-decoration and background are read. The lines
stay the field’s own height, so a mark in a larger face draws larger glyphs on
the same rows.
Spell checking
A text-input, a text-area or a rich-input draws a wavy line under a
word its dictionary does not know, when it is told to check:
column spellcheck=#true lang="en-US" {
text-input placeholder="A title"
text-area rows=4 placeholder="A note"
text-input password=#true placeholder="Never checked"
}
spellcheck and lang go on any node and pass down to the fields inside it,
as they do in HTML. A field’s own spellcheck=#false wins over its parents’.
Nothing is checked unless something says spellcheck=#true, and a password
never is. In Java, every widget has .spellcheck(true) and
.lang(Locale.UK).
Dictionaries
No dictionary ships with the toolkit, because their licences differ from one
language to the next. Add goldberry-spell to the application and load the
dictionaries it needs, in the common .aff and .dic format that office
suites and browsers use:
SpellCheckers.load(Locale.US, Path.of("dict/en_US.aff"), Path.of("dict/en_US.dic"));
SpellCheckers.load(Locale.of("ru"), Path.of("dict/ru_RU.aff"), Path.of("dict/ru_RU.dic"));
SpellCheckers.defaultLanguage(Locale.US);
A field checks with the dictionary for its lang. A dictionary for en_US
also answers en and en_GB when there is no closer one. A field with no
lang uses SpellCheckers.defaultLanguage, or the only dictionary loaded
when there is just one. A language with no dictionary checks nothing. A
dictionary can be loaded from the application’s resources as two streams.
Loading en_US takes a moment, so load it away from the UI thread with
Goldberry.async and the fields check as soon as it arrives.
The fields check the lines they show away from the UI thread, and remember
each line’s answer by its text, so typing costs one line’s check. A word is
not flagged while the caret is in it or just after it: it is still being
typed. In a rich-input, code, links and mentions are not checked.
The menu
A right-click on a flagged word opens the field’s menu on it, with up to five
suggestions above Cut, Copy and Paste. Then come Add to dictionary and
Ignore. Choosing a suggestion replaces the word as one step of undo, and
in a rich-input it keeps the word’s bold or italic. Ignore lasts as long
as the field. Add to dictionary adds the word to the language’s personal
dictionary, and every field in that language stops flagging it. The menu key
opens the same menu on the word at the caret.
The personal dictionary lives in memory. To keep it between runs, save it yourself:
var personal = SpellCheckers.personal(Locale.US);
personal.addAll(Files.readAllLines(saved));
personal.onChange(() -> Files.write(saved, personal.words()));
The menu’s words come from the toolkit’s labels, so a translation covers
them: goldberry.addToDictionary, goldberry.ignoreSpelling,
goldberry.noSuggestions and goldberry.findingSuggestions.
How it looks
The line is ::spelling-error, which takes color, background and the
text-decoration properties:
::spelling-error { text-decoration: wavy underline var(--gb-danger) }
text-area::spelling-error { text-decoration: dotted underline var(--gb-warning) }
The first rule is the theme’s. The line keeps its rhythm across a word that is half bold, and the word keeps its own colour unless the rule gives it one.
field
A field is a label, a control, and a message slot under it, with a validator
over the control’s value.

Two labelled fields and an actions row.
form class="horizontal" {
field label="Name" required=#true {
text-input bind="signup.name" change="signup.set-name" placeholder="Meriadoc Brandybuck"
}
field label="Port" required=#true validator="signup.port-rule" {
text-input bind="signup.port" change="signup.set-port" filter="digits" max-length=5
}
field class="actions" {
button class="primary" press="signup.submit" "Enlist"
}
}
import dev.goldberry.widgets.form.field.Field;
import dev.goldberry.widgets.form.form.Form;
import dev.goldberry.widgets.form.Validator;
new Form(
new Field("Name",
TextInput.of(Models.observable(signup, "signup.name"), actions::setName))
.required(true),
new Field("Port",
TextInput.of(Models.observable(signup, "signup.port"), actions::setPort)
.filter(TextFilter.DIGITS))
.required(true)
.validate(Validator.parsing(Integer::parseInt, "A port is a number")),
new Field("", new Button("Enlist", actions::submit).styled("primary"))
.styled("actions")
).styled("horizontal");
The validation model
A field is silent until you leave it once, and live from then on. It says nothing while the user is in it, however wrong the value is. Once it has complained, it re-checks on every change so the message goes the instant the value is fixed. Submitting is the third moment, and the only one that makes an unvisited field speak.
A validator returns a message, not a boolean, because a field that goes red
without saying why is one somebody has to guess at. required=#true is
Validator.required("This field is required") in front of whatever
validator= names, and and reports the first failure because the message
slot is one line. Validator.of(predicate, message), minLength, matching
and parsing are the built-in rules.
The field reads its value from the control’s own bind=. It walks its
children one level, so a hint under the control is not what gets validated.
A click on the label focuses the control.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
label | string | "" | the label beside or above the control |
required | boolean | #false | an asterisk on the label and a rule that refuses blank |
validator | object name | none | a Validator<String> the application registered under this name |
class, id, tooltip, context-menu, name | as on every widget |
The children are the controls. A validator= name resolves in the Named
registry, the fourth registry beside actions, icons and bindings. An
application builds one with Named.strict().bind("signup.port-rule", rule)
and hands it to Widgets.inflater(named, icons, models…).
Styling
- CSS type
field. - Parts:
field-label, which takes the classrequired;field-body, the column holding the control and the message;field-message, in--gb-danger-text. - Pseudo-classes:
:invalid, whichfield:invalid text-inputandfield:invalid selectuse for the danger border. - Classes:
horizontalputs the label in a column beside the body;verticaltakes it back inside aform.horizontal;actionsis a field with no label whose body lines up with the controls.
Stacked is the default. The label column’s width is --gb-field-label-width,
one token, so an application moves every form at once. A field is two boxes
because the subset has no grid: a label beside a body is a row, and a message
under a control is a column.
Keyboard
None of its own. The controls inside it have theirs.
form
A form finds the fields in its subtree and gates a submission on their
validity.

Two fields under a controller.
form controller="signup.form" submit="signup.enlist" {
field label="Name" required=#true { text-input placeholder="Peregrin Took" }
field label="Port" { text-input placeholder="8080" filter="digits" }
}
import dev.goldberry.widgets.form.form.FormController;
var controller = new FormController();
new Form(
new Field("Name", new TextInput().placeholder("Peregrin Took")).required(true),
new Field("Port", new TextInput().placeholder("8080").filter(TextFilter.DIGITS))
).controller(controller)
.onSubmit(actions::enlist);
controller.submit(); // validates every field, runs onSubmit when all pass
controller.isValid();
controller.errors(); // every field's message, in order
controller.reset(); // clears every message
A FormController is what submits, because a Save button is usually outside
the form. submit() makes every field check, returns whether all passed, and
runs submit= when they did. submit carries nothing: bind= reads from the
application’s model, so an event carrying the bound values would hand an
application its own data back.
The fields are anywhere in the subtree: inside rows, inside cards, inside a
collapse.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
controller | object name | none | a FormController the application registered under this name |
submit | action name | none | run when a submission passes |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
form. - No parts.
- No pseudo-classes.
- Classes:
horizontalgives every field in it a label column;form.horizontal field.verticaltakes one field back.
Keyboard
None. Enter in a field does not submit. A button’s action calls
FormController.submit().
code-input
A code-input is the one-time-code field: a row of single-character boxes
over one string.

Digits, masked, and alphanumeric.
column {
code-input length=6 type="digits" bind="app.code" change="app.set-code" complete="app.code-complete"
code-input length=6 mask=#true
code-input length=5 type="alnum"
}
import dev.goldberry.widgets.form.codeinput.CodeInput;
import dev.goldberry.widgets.form.codeinput.CodeType;
new Column(
CodeInput.of(Models.observable(app, "app.code"), actions::setCode)
.length(6)
.onComplete(actions::codeComplete),
new CodeInput(6, null).mask(true),
new CodeInput(5, null).type(CodeType.ALNUM)
);
The value is a string and the boxes are a drawing. There is no caret and no
per-box array: the active box is the first empty one, derived on every frame.
Typing appends, a paste of 123 456 drops the spaces and fills every box at
once, and complete fires on the edit that filled the last box. A character
the type refuses is dropped rather than rejecting the whole paste.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | "" | the written code |
bind | path | none | the code to follow |
change | action name | none | told the whole code after every edit |
complete | action name | none | told the code when the last box fills |
length | integer | 6 | the number of boxes; less than 1 falls back to 6 |
type | digits, alnum | digits | what a box accepts; an unknown name is logged and digits are taken |
mask | boolean | #false | draws a dot in a filled box |
disabled | boolean | #false | out of the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
Styling
- CSS type
code-input. - Parts:
code-group, one per half when the length is even;code-box, which takes the classesfilledandactive. - Pseudo-classes:
:focus-visible,:hover,:disabled.code-input:focus-visible code-box.activeis the ring.
Box 40 by 48, gap 8, radius 4, in title and centred. The group gap is 16 at
the midpoint of an even length. The ring moves between boxes instantly and
nothing travels.
Keyboard
| Key | Does |
|---|---|
| typing | fills the active box and moves on |
Backspace, Delete | clear the box before the ring |
Esc | clears the code |
Ctrl+V | pastes, dropping what the type refuses |
Arrow keys do nothing, because there is one insertion point. Copy and cut are not built, because a masked code must not have a way out.
date-picker
A date-picker is a text-input that parses, with a calendar in a popover.
The typed field is the source of truth.

Closed, showing its bound date.
date-picker bind="trip.date" change="trip.set-date" month="2026-09" \
min="2026-09-01" max="2026-12-31" today="2026-09-18" \
placeholder="When are you leaving?"
import java.time.LocalDate;
import java.time.YearMonth;
import dev.goldberry.widgets.form.datepicker.DatePicker;
DatePicker.of(Models.observable(trip, "trip.date"), actions::setDate, YearMonth.of(2026, 9))
.between(LocalDate.of(2026, 9, 1), LocalDate.of(2026, 12, 31))
.today(LocalDate.of(2026, 9, 18))
.placeholder("When are you leaving?");
The grid writes text into the field exactly as a user would, so a value takes
one path and is parsed in one place. A date outside min and max, or one the
disabledDates predicate refuses, cannot be pressed in the grid and is left in
the field unparsed rather than deleted. Parsing and formatting use the
locale’s short form, DateFormat.of(locale), and the toolkit invents no date
syntax of its own.
The month is an argument and today may be null. Nothing in the catalogue
reads the machine’s clock, so a picker that opened on “this month” would be
deciding what month it is. In Java, onChange receives a DateSelection,
range(true) selects a pair, and the bound value may be a LocalDate, a
DateSelection or text. From markup, change carries the formatted text.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | "" | the written text |
bind | path | none | the value to follow |
change | action name | none | told the formatted date |
placeholder | string | "" | shown while empty |
range | boolean | #false | select a pair and report it as one value |
month | ISO year-month | min’s month, else 1970-01 | the month the grid opens on; a malformed one is logged and ignored |
today | ISO date | none | the day marked as today |
min, max | ISO date | none | the reachable range, in the field and in the grid |
disabled | boolean | #false | out of the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
disabledDates, format and locale are Java only.
Styling
- CSS type
date-picker. - Parts:
date-picker text-input, the field;picker-toggle, the chevron;picker-panel, the popover, holding acalendar. - Pseudo-classes:
:checkedwhile the panel is open, sodate-picker:checked picker-toggleturns the chevron;:disabled.
Popup radius 12, padding 8, day cell 32 square with a full radius on the selected day.
Keyboard
| Key | Does |
|---|---|
| typing | edits the field, which is the value |
Alt+Down | opens the grid |
Esc | closes the grid and reverts |
Left, Right | a day |
Up, Down | a week |
PgUp, PgDn | a month; with Shift, a year |
Home, End | the start and the end of the week |
Enter, Space | choose the day |
time-picker
A time-picker is the same control as the date picker with wheels in the
popover instead of a grid.

Closed, showing its bound time.
time-picker bind="trip.time" change="trip.set-time" min="06:00" max="22:00" \
precision="minutes" placeholder="Boarding time"
import java.time.LocalTime;
import dev.goldberry.widgets.form.timepicker.TimePicker;
import dev.goldberry.widgets.form.timepicker.TimePrecision;
TimePicker.of(Models.observable(trip, "trip.time"), actions::setTime)
.between(LocalTime.of(6, 0), LocalTime.of(22, 0))
.precision(TimePrecision.MINUTES)
.placeholder("Boarding time");
Each column is a wheel: five rows centred on the value, wrapping at both ends,
so 58 59 00 01 02 says what comes next. The wheels report on every turn,
because there is no unchosen state for an hour. precision= is which columns
the picker has, and the default format follows it. In Java,
onChange receives a LocalTime, or null when the field is cleared. From
markup, change carries the formatted text.
A range that wraps past midnight is refused. It is two ranges, and the
disabledTimes predicate is how to say so.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | "" | the written text |
bind | path | none | the value to follow |
change | action name | none | told the formatted time |
placeholder | string | "" | shown while empty |
precision | hours, minutes, seconds | minutes | which wheels the picker has; an unknown name is logged and minutes are taken |
fallback | ISO time | 00:00 | where the wheels open when the field is empty |
min, max | ISO time | none | the reachable range |
disabled | boolean | #false | out of the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
disabledTimes and format are Java only.
Styling
- CSS type
time-picker. - Parts:
time-picker text-input;picker-toggle;picker-panel;time-columns;time-column;time-cell, which takes the classesselectedandroving. - Pseudo-classes:
:checkedwhile the panel is open;:disabled.
Column width 48, cell height 32 with radius 4, five rows a column with the
middle one filled with --gb-accent, gap 4 between columns.
Keyboard
| Key | Does |
|---|---|
| typing | edits the field, which is the value |
Alt+Down | opens the wheels |
Esc | closes them and reverts |
Up, Down | turn the wheel the focus is on |
Left, Right | choose which wheel |
Home, End | the first and the last wheel |
Enter, Space | commit |
The arrows split by axis where a calendar’s do not.
color-picker
A color-picker is a swatch that opens a board: a saturation and value plane,
a hue ramp, an optional alpha ramp, a hex field and preset swatches. The hex
field is the source of truth.

A bound colour and one with alpha.
row {
color-picker bind="paint.colour" change="paint.set-colour"
color-picker alpha=#true value="#bf616a80"
}
import dev.goldberry.widgets.form.colorpicker.ColorPicker;
new Row(
ColorPicker.of(Models.observable(paint, "paint.colour"), actions::setColour)
.presets(List.of(0xFFBF616A, 0xFFA3BE8C, 0xFF81A1C1)),
new ColorPicker("#bf616a80", null).alpha(true)
);
The plane, the ramps and the presets all write hex into the field, so a value takes one path and is parsed in one place. The plane is HSV, because a saturation and value plane is HSV, and a colour with no saturation keeps its hue beside the hex so the hue ramp does not swing to red at the left edge.
alpha is off by default and refuses in both directions: a picker with no
way to change alpha must not report one, so a translucent value is gated to
opaque. In Java, onChange receives the colour as 0xAARRGGBB and the bound
value may be an Integer or hex text. From markup, change carries the hex.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | hex string | "" | the written colour |
bind | path | none | the value to follow |
change | action name | none | told the hex |
alpha | boolean | #false | shows the alpha ramp and allows translucent values |
disabled | boolean | #false | out of the Tab order |
class, id, tooltip, context-menu, name | as on every widget |
presets is Java only: a List<Integer> of 0xAARRGGBB.
Styling
- CSS type
color-picker. - Parts:
color-swatch, the closed control, andcolor-swatch.presetin the board;color-board;color-plane;color-ramp;color-presets. - Pseudo-classes:
:focus-visibleoncolor-swatchandcolor-plane;:disabled.
Swatch 24 with radius 4, plane 200 by 160, ramps 12 tall, preset swatch 20 with gap 4. Everything in the board is painted rather than styled, because what it shows moves with the value.
Keyboard
| Key | Does |
|---|---|
Space, Enter on the swatch | opens the board |
| arrows on the plane | move the cursor one step |
Shift and arrows | ten steps |
Space, Enter on a preset | picks it |
Panels
The containers a window is made of: surfaces at three elevations, a titled frame, sections that fold, a strip of slides, placeholders, a labelled number, tabs, and a timeline.
A container holds children and draws a surface around them. None of these
holds a value, so a screen of panels needs no bind= and no Java at all. The
two that keep state, collapse and carousel, keep it themselves and can be
told what it is instead. Every rule below is controls.css’s, and an
application styles the layout around them, not the widgets.

The Panels screen of the showcase.
panel
The building block: a flat surface with the theme’s border and radius, and no elevation.

A surface with two lines of text.
panel class="side" {
text "The map"
text "Where the road goes next."
}
new Panel(
new Text("The map"),
new Text("Where the road goes next.")
).styled("side");
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id, class | string | The usual. Any children. |
Styling
The CSS type is panel: a column, --gb-surface, a 1px --gb-border, radius
8. No parts, no pseudo-classes, no variants. It is the one container a theme
can restyle completely.
card
A raised surface: a shadow and a stronger edge, level 1 of the design system’s ladder, lifting to level 2 under the pointer when asked.

An interactive card at rest.
card class="interactive" {
text class="card-title" "Surfaces"
text "Point at it and the shadow rises."
}
new Card(
new Text("Surfaces").styled("card-title"),
new Text("Point at it and the shadow rises.")
).styled("interactive");
The edge stays even though there is a shadow, because a card on another card
casts onto the same colour and only the rim tells them apart. The shadow is
--gb-elevation-1, which each theme ships.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id, class | string | The usual. Any children. |
Styling
The CSS type is card: --gb-surface-raised, a 1px --gb-border-strong,
radius 8, padding 12, gap 8. The variant class interactive adds a hover
elevation: card.interactive:hover takes the accent edge and
--gb-elevation-2, with the blur, offset and alpha moving together. It is
opt-in, because a card that lit up would promise it does something.
group-box
A titled frame for a cluster of settings. The frame goes round both the title and the content.

A title and two rows.
group-box title="The Company" {
row { text "Ring-bearer"; spacer; text class="caption" "Frodo Baggins" }
row { text "Guide"; spacer; text class="caption" "Gandalf the Grey" }
}
new GroupBox("The Company",
new Row(new Text("Ring-bearer"), new Spacer(), new Text("Frodo Baggins").styled("caption")),
new Row(new Text("Guide"), new Spacer(), new Text("Gandalf the Grey").styled("caption")));
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
title | string | none | The header row. Without it there is no header and no gap where one would be. |
id, class | string | The usual. Any children. |
The title is a property and not the argument, because the argument position is
where a container’s children start and group-box "Appearance" { … } would
read as content.
Styling
The CSS type is group-box. Its parts are group-box-title, a tinted header
ruled off from the body with --gb-surface-2 and --gb-font-heading, and
group-box-body. The title part is absent when there is no title. A legend
cut through the border is not available.
collapse
A header and a body that folds away. The body is unmounted while closed, not hidden, so a shut section holds no subscriptions for content nobody can see.

Open, with its chevron turned.
collapse title="The Council's terms" open=#true {
row { text "Bearers"; spacer; text class="caption" "1" }
row { text "Companions"; spacer; text class="caption" "8" }
}
new Collapse("The Council's terms",
new Row(new Text("Bearers"), new Spacer(), new Text("1").styled("caption")),
new Row(new Text("Companions"), new Spacer(), new Text("8").styled("caption")));
A collapse keeps whether it is open. Name a toggle action and it stops
keeping it: the header then raises "true" or "false" and the section is as
open as open says. The Java form is
new Collapse(title, open, onToggle, children...).
An accordion is a column. column accordion=#true inflates to an
Accordion that re-issues each collapse child so only one is open at a time.
A section the application already controls is left alone, and from markup an
accordion starts with every section shut.
column accordion=#true {
collapse title="The Shire" { text "Second breakfast kept." }
collapse title="Rivendell" { text "Council held." }
collapse title="Moria" { text "Doors: Mellon." }
}
new Accordion(
new Collapse("The Shire", new Text("Second breakfast kept.")),
new Collapse("Rivendell", new Text("Council held.")),
new Collapse("Moria", new Text("Doors: Mellon."))
);
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
title | string | "" | The header’s text. |
open | boolean | #false | The initial state, or the state itself once toggle is named. |
toggle | action name | none | Called with "true" or "false" when the header is pressed. Naming it makes the section controlled. |
id, class | string | The usual. The children are the body. |
Styling
The CSS type is collapse, with the class open while it is. Its parts are
collapse-header, which matches :hover, :focus-visible and :checked
while open, collapse-chevron, which rotates 90° through .open, and
collapse-body. The header is 40px, 36 at compact density. The body does not
animate, because height is not on the motion whitelist and the body is not
there while closed.
Keyboard
The header is the one Tab stop.
| Key | Does |
|---|---|
Enter, Space | toggles |
Right | opens |
Left | closes |
carousel
One slide visible out of a list, with previous and next and a dot per slide. Only the current slide exists; the others are dropped when you leave them.

The first of three slides.
carousel loop=#true interval=5000 {
panel class="slide" { text "Stage 1 of 3: Bag End" }
panel class="slide" { text "Stage 2 of 3: Rivendell" }
panel class="slide" { text "Stage 3 of 3: Moria" }
}
var slides = List.of(
new Panel(new Text("Stage 1 of 3: Bag End")).styled("slide"),
new Panel(new Text("Stage 2 of 3: Rivendell")).styled("slide"),
new Panel(new Text("Stage 3 of 3: Moria")).styled("slide")
);
new Carousel(0, null, true, Duration.ofSeconds(5), slides, Attributes.NONE);
new Carousel(Widget... slides) is the short form: no loop, no rotation. Name
a change action and the carousel becomes controlled, showing the slide
index names and raising the index it would like next.
Nothing advances on its own unless interval is set. When it is, rotation
has three brakes: it pauses while the pointer is over the strip, while the
keyboard is anywhere inside it, and entirely under reduced motion. Without
loop it also stops at the last slide.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
index | number | 0 | The slide shown, clamped into range. |
loop | boolean | #false | Whether next on the last slide goes to the first. |
interval | number, ms | 0 | How often to advance on its own. 0 is never. |
change | action name | none | Called with the wanted index. Naming it makes the carousel controlled. |
id, class | string | The usual. Each child is one slide. |
Styling
The CSS type is carousel, with the class rotating while an interval runs.
Its parts are carousel-viewport, carousel-controls holding two
carousel-step buttons with the classes previous and next, and
carousel-dots of carousel-dot, shown only with more than one slide. A step
matches :hover, :active, :focus-visible and :disabled at an end of a
non-looping strip. The current dot matches :checked. The steps are
button.ghost.circle’s shape, the dots 8px.
Keyboard
The strip is one Tab stop when it has two or more slides.
| Key | Does |
|---|---|
Left, Right | previous and next slide |
Home, End | the first and last slide |
Enter, Space | on a focused step button, presses it |
skeleton
The placeholder a widget shows while its data loads, sized from the typography token it stands in for so the layout does not jump when the content arrives.

Circle, title and two lines of text.
row {
skeleton shape="circle"
column {
skeleton shape="title"
skeleton shape="text" lines=2
}
}
new Row(
new Skeleton(Skeleton.Shape.CIRCLE),
new Column(
new Skeleton(Skeleton.Shape.TITLE),
new Skeleton(Skeleton.Shape.TEXT, 2, Attributes.NONE)
)
);
A shimmer is a loop, and the design system allows one decoration to loop. It is an opacity pulse between 0.45 and 1.0 over a second, held at its dimmest under reduced motion.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
shape | "text", "title", "circle", "rect" | "text" | What it stands in for. Any other word is refused. |
lines | number | 3 | How many bars a text skeleton draws. Fewer than one is refused. |
id, class | string | The usual. Children are ignored. |
new Skeleton() is three lines of text.
Styling
The CSS type is skeleton, and both it and each skeleton-bar carry the class
shape-text, shape-title, shape-circle or shape-rect. The last bar of a
multi-line text skeleton also carries last and is 60% wide. Radius 4, or full
for a circle.
statistic
A labelled number: a value in the display size, a caption over it, and an optional unit, delta and sparkline.

A label, a value, a unit and a delta.
row {
statistic label="Leagues walked" value="1,795" delta="+42" direction="up"
statistic label="Days from Rivendell" value="93" unit="d" delta="-2" direction="down"
statistic label="Companions lost" value="1" delta="Gandalf"
}
new Row(
new Statistic("Leagues walked", "1,795").delta("+42", Statistic.Direction.UP),
new Statistic("Days from Rivendell", "93").unit("d").delta("-2", Statistic.Direction.DOWN),
new Statistic("Companions lost", "1").delta("Gandalf", Statistic.Direction.NONE)
);
The value is a string. Formatting is the application’s, because a number formatted inside the toolkit would depend on the machine’s locale.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
label | string | required | The caption. |
value | string | required | The number, as text. |
unit | string | none | Drawn after the value, smaller. |
delta | string | none | A change, drawn under the value. |
direction | "up", "down", "none" | "none" | Colours the delta --gb-success or --gb-danger. |
id, class | string | The usual. Children are ignored. |
A sparkline is Java only: .sparkline(Sparkline) takes the
sparkline widget and draws it 64×24 under the number.
Styling
The CSS type is statistic. Its parts are statistic-label,
statistic-value holding statistic-unit, and statistic-delta, which
carries the class up or down.
tabs
A strip of headers over one panel: pick a tab and its content is built, leave it and the content is dropped, unless the strip is told to keep it.

Three tabs, one closable, one coloured.
tabs value="map" change="app.pick-tab" close="app.close-tab" new="app.new-tab" {
tab value="map" "The map" {
text "Where the road goes."
}
tab value="road" icon="footprints" closable=#true "The road" {
text "How far it is."
}
tab value="moria" colour="#bf616a" "Moria" {
text "Avoid."
}
}
new Tabs("map",
new Tab("map", "The map", new Text("Where the road goes.")),
new Tab("road", "The road", new Text("How far it is.")).icon(footprints).closable(true),
new Tab("moria", "Moria", new Text("Avoid.")).colour(0xFFBF616A))
.onChange(actions::pickTab)
.onClose(actions::closeTab)
.onNew(actions::newTab);
The strip is a model, a header and a panel. Which tab is selected is value,
or the bound value, and the strip reports what the user wants through
change, close and new. Adding and removing tabs needs no API: rebuild
with a different list. A header row too wide for the strip pages from its
ends. keep-alive hides a left tab’s content instead of dropping it, for an
editor whose state is costly to rebuild. Reordering by drag is Java only,
through onReorder(BiConsumer<String, Integer>).
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | none | The selected tab’s value, when nothing is bound. |
bind | path | none | A value to read the selection from instead. |
change | action name | none | Called with the value of the tab the user picked. |
close | action name | none | Called with the value of the tab whose × was pressed. |
new | action name | none | Adds a + button after the tabs and calls this when it is pressed. |
keep-alive | boolean | #false | Keeps a left tab’s content mounted and hidden. |
id, class | string | The usual. |
new Tabs(String value, Widget... tabs) is the Java form, with onChange,
onClose, onNew, keepAlive, onReorder and bound after it. Children
that are not tabs are placed in the header row.
Styling
The CSS type is tabs. The header is a tab-list holding a tab-rule, a
scroll.tab-viewport of tabs, and while they overflow a tab-pager at each
end with the class start or end. Each tab matches :hover, :checked
and :focus-visible, and holds a tab-indicator that matches :checked and
travels between tabs, a tab-close on a closable one, and the strip ends in
tab-new when new is wired. The content is tab-panel, and under
keep-alive each kept tab is a tab-page. A tab is 36px with a 2px accent
indicator.
Keyboard
The strip is one Tab stop.
| Key | Does |
|---|---|
Left, Right | move between the tab headers and the + button, without selecting |
Enter, Space | select the focused tab, or press + |
Delete | closes the focused tab, when it is closable |
Tab | leaves the strip for its content |
tab
One tab: the value its strip reports, a label, and the content shown while it is selected.

A closable tab with an icon and a colour.
tab value="road" icon="footprints" colour="#bf616a" closable=#true "The road" {
text "How far it is."
}
new Tab("road", "The road", new Text("How far it is."))
.icon(footprints)
.colour(0xFFBF616A)
.closable(true);
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | required | What the strip matches on and reports. Missing is refused. |
| argument | string | "" | The label. A tab with neither a label nor an icon is refused. |
icon | icon name | none | An icon before the label. |
colour, color | CSS colour | the theme’s | The indicator’s colour, written as a stylesheet writes one. |
closable | boolean | #false | Adds a × and lets Delete close it. |
id, class | string | The usual. The children are the content. |
Warning
Two tabs with the same
valueare one tab: the later replaces the earlier one’s content and nothing reports it.
timeline
An ordered list of entries along an axis, each with a marker, a label, an optional time and optional body.

A dot, a badge and an icon as markers, and a pending end.
timeline pending=#true {
entry time="Mon" "Drafted"
entry time="Thu" "Reviewed" {
marker { badge "3" }
}
entry time="Fri" icon="tag" "Released" {
text "Tagged and published."
}
}
new Timeline(
new Entry("Drafted").at("Mon"),
new Entry("Reviewed").at("Thu").withMarker(new Badge("3")),
new Entry("Released", new Text("Tagged and published.")).at("Fri").withIcon(tag)
).pending(true);
The line goes on: pending draws a trailing unfilled marker after the last
entry for what happens next, which is what tells a timeline from a list with
dots.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
direction | "vertical", "horizontal" | "vertical" | Which way the axis runs. |
align | "start", "alternate" | "start" | Every entry on one side, or alternating sides. |
pending | boolean | #false | A trailing empty marker. |
id, class | string | The usual. entry children sit on the axis, anything else passes through. |
An unknown direction or align falls back to the default without complaint.
Styling
The CSS type is timeline, with the classes horizontal and alternate. Each
entry carries end on the alternate side and pending on the trailing
marker. An entry is a timeline-rail, holding a timeline-marker-cell with
the timeline-marker and a timeline-line, beside a timeline-side holding
timeline-body, timeline-head, timeline-label, timeline-time and
timeline-content. The marker carries icon, widget or pending. Marker
12px, axis 2px in --gb-border, rail 20 wide.
entry
One event: a label, an optional time, and a marker that is a dot, an icon, or any widget.

An entry with an icon, a colour and a body.
entry time="Thu" icon="tag" colour="#a3be8c" "Reviewed" {
text "Two approvals."
}
new Entry("Reviewed", new Text("Two approvals."))
.at("Thu")
.withIcon(tag)
.colour(0xFFA3BE8C);
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | required | The label. |
time | string | none | The timestamp after the label, in caption. |
icon | icon name | none | Drawn in a 20px disc as the marker. |
colour, color | CSS colour | the theme’s | The marker’s colour. |
id, class | string | The usual. One marker child is the marker; every other child is the body. |
Two marker children are refused.
marker
The thing drawn on the axis instead of a dot: exactly one widget.
marker { badge "v2" }
new EntryMarker(new Badge("v2"));
It takes exactly one child and no attributes of its own. The child is drawn
under timeline-marker.widget. In Java, Entry.withMarker(Widget) is the
usual route.
Collections
A list, a table and a tree: three widgets over a model the application owns, that select by id, report what the user chose, and never edit the data.

The Collections screen of the showcase.
Each of the three takes the application’s own type and a few functions that describe it: how to identify an item, how to draw it, what to call it. The widget holds no copy of the data. Selection is a set of ids the application holds and hands back in, and every change arrives as the whole new set.
Important
A list, a table or a tree is built in Java. Markup can place one the model holds, with
bind=, but cannot describe one: an item factory is code. Thekdlsamples below show the placing. The Java beside them is the widget.
list
A vertical list of rows, one per item, with a selection model and a keyboard.

Six rows, one selected.
list bind="app.road" id="road" class="sidebar"
@Bind("app.road") private ListView<String> road =
ListView.of(Leagues.ROAD)
.virtualized()
.selection(Selection.MULTIPLE)
.selected(chosen, this::choose);
ListView.of(List<String>) is the short form: the string is the id, the label
and the type-ahead text. The general constructor takes the application’s type
and two functions:
new ListView<>(walkers, Walker::id, w -> new Text(w.name()))
.text(Walker::name)
.selected(picked, this::pick);
identity names an item, and that name is what selection carries. factory
builds the row’s content, and any widget will do. text is optional and
powers type-to-select.
Rows are virtualized by row height. virtualized() reads
--gb-list-row-height from the cascade, so a compact density gets the right
pitch. virtualized(double) names one. The list then builds only the rows a
viewport can see, plus four either side, with a spacer above and below sized
from the rest, so the showcase scrolls ten thousand rows. A list that is not virtualized builds every row.
The row the keyboard is on is built too, however far the list is scrolled from it, so the next arrow key carries on from where the focus was.
Rows that are not one height are virtualized by measuring them.
virtualized(RowHeights.estimating(64)) builds the same window, measures each
row as it is laid out, and counts every row it has not built at the estimate,
so a timeline of five thousand messages costs a window per frame. Heights are
remembered by each item’s identity, so rows prepended above keep theirs, and a
change of width forgets them. When a row above the line being read turns out
taller or shorter than it was counted, the enclosing scroll moves by the
difference and the line stays where it was. A scroll with anchor="end" or
preserve-on-prepend does that correcting itself. Home, End and
type-to-select scroll the row they reach to the top. The rows carry the class
measured and are as tall as their content, never shorter than
--gb-list-row-height. Space rows with padding, because a row’s height is its
border box and a margin or a gap between rows is not counted.
Warning
A virtualized list’s
list-rowheight must be the pitch it was told. When a stylesheet makes them differ by more than half a pixel the list logs it once and the scroll range is wrong.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
bind | path | none | The ListView a model holds. Nothing bound draws nothing. |
id, class | string | Laid over the widget’s own id and classes. |
Nothing else is read, and children are ignored.
Java
| Method | What it does |
|---|---|
ListView.of(List<String>) | A list of strings, each its own id and label. |
new ListView<>(items, identity, factory) | The general form. |
selection(Selection) | NONE, SINGLE or MULTIPLE. Single is the default. |
selected(Set<String>, Consumer<Set<String>>) | The current selection and where to report the next. |
selected(String, Consumer<String>) | The same for a single selection. |
text(Function<T, String>) | What type-to-select matches. |
virtualized(), virtualized(double) | Build only the visible window. |
virtualized(RowHeights) | Build only the visible window of rows that vary in height, measured as they are built. |
sections(Function<T, String>, Function<String, Widget>) | Headed runs of items, with the top one pinned. |
itemMenu(Function<T, String>) | A context-menu name per item. |
In MULTIPLE, a plain press replaces the selection, Ctrl toggles the row,
and Shift selects from the last plain press through to the row. What is
reported is the whole set, in the order it was chosen.
Styling
The CSS type is list. Each row is a list-row, and the virtual spacers are
list-spacer. A row matches :hover and :focus-visible, and carries the
class selected rather than a pseudo-class. The row height is
--gb-list-row-height, 32px, 26px at compact density.
Keyboard
| Key | Does |
|---|---|
Up, Down | move focus between rows, without selecting, and scroll the row into view. They wrap at the ends |
Enter | selects the focused row. Ctrl+Enter toggles, Shift+Enter ranges |
Home, End | the first and last item, scrolled into view |
| letters | type-to-select, when text is set. One second between letters, repeat a letter to cycle |
A right-click selects the row it is over before the context menu opens, unless it is already selected.
table
A list with columns: one row per item, one cell per column, and a header that sorts by asking.

Three columns, the last a fixed width.
table bind="app.company" id="company"
new Table<>(sorted, Walker::id, List.of(
Column.<Walker>of("name", "Name", Walker::name).sortable(true).resizable(true),
Column.<Walker>of("realm", "Realm", Walker::realm).sortable(true).weight(2),
Column.<Walker>of("leagues", "Leagues", w -> String.valueOf(w.leagues()))
.sortable(true)
.fixed(96)
))
.sorted(sort, this::sortBy)
.selection(Selection.MULTIPLE)
.selected(picked, this::pick)
.id("company");
A Column has a key, a header, a cell function and a width. Column.of
draws text, Column.widget draws any widget. weight(double) shares the
remaining width, fixed(double) takes pixels.
Sorting is reported, not performed. A press on a sortable header calls
onSort with the Sort the table would like next: the column, ascending, or
the same column flipped. The application sorts its items and rebuilds, and the
caret appears on the column sort names.
private void sortBy(Sort next) {
setState(() -> sort = next); // and sorted() orders the items by it
}
A resizable column has a grip after its header. Dragging it asks onResize
for a new width, and the application decides what the column becomes. The
header stays at the top while the rows scroll.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
bind | path | none | The Table a model holds. Nothing bound draws nothing. |
id, class | string | Laid over the widget’s own. |
A column child in markup is the layout widget, not a column definition, and
is discarded.
Java
| Method | What it does |
|---|---|
new Table<>(items, identity, columns) | The table. |
sorted(Sort, Consumer<Sort>) | The current sort and where to report the next. null is model order. |
resized(BiConsumer<String, Double>) | Where a grip reports a column key and a width. |
selection, selected | As list. |
virtualized(double) | Build only the visible rows, at this pitch. |
Sort.by(column) is ascending. Sort.next(current, column) is what the header
asks for.
Styling
The CSS type is table. The header is a table-head of table-header cells,
each holding a table-label and, on the sorted column, a sort-caret; a
table-rule runs under it, and a table-grip sits after a resizable header.
Rows are the list’s list-row, each a table-cells of table-cell. A header
carries the classes sortable, sorted and ascending or descending, and
matches :hover and :focus-visible. The header height is
--gb-table-header-height, 36px, 30px at compact density.
Keyboard
Rows take what list takes: Up, Down, Enter, Home, End. A sortable
header is a Tab stop, and Enter or Space on it asks for the next sort. A
table has no type-to-select.
tree
A list that remembers what is open: nodes with children, a chevron on those that have or may have some, and the list’s selection models.

Two roots with cascading checkboxes.
tree bind="app.lands" id="lands"
List<TreeNode> lands = List.of(
TreeNode.of("eriador", "Eriador",
TreeNode.leaf("shire", "The Shire"),
TreeNode.leaf("bree", "Bree")),
TreeNode.lazy("erebor", "Erebor",
() -> List.of(TreeNode.leaf("dale", "Dale")))
);
new Tree(lands, selected, this::select)
.checkable(Checkable.CASCADE)
.checked(checked, this::check)
.id("lands");
The model is a TreeNode. It has an id, a label and either a list of
children or a supplier of them. TreeNode.leaf has none, TreeNode.of has
them up front, and TreeNode.lazy fetches them the first time the node opens.
The tree keeps which ids are open and what a supplier returned, so a rebuild
with the same ids keeps the same shape.
Checking and selecting are two different things. Selection is the list’s,
a set of ids reported whole. checkable(Checkable) adds a checkbox per node:
LEAF on leaves only, ANY on every node, CASCADE where a parent’s box
shows its children’s state and checking it checks them all. The checked set
is reported through checked(Set, Consumer) and never touches selection.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
bind | path | none | The Tree a model holds. Nothing bound draws nothing. |
id, class | string | Laid over the widget’s own. |
There is no checkable= or node child in markup. Those are the model’s.
Java
| Method | What it does |
|---|---|
new Tree(roots, selected, onSelect) | Single selection of leaves only. |
anyNode(true) | Lets a parent be selected too. |
selection(Selection), selected(Set), onSelect(Consumer) | The list’s models. |
checkable(Checkable) | NONE, LEAF, ANY or CASCADE. |
checked(Set<String>, Consumer<Set<String>>) | The checked ids and where to report the next set. |
A tree is not virtualized: every visible row is built.
Styling
The CSS type is tree. Each row is a tree-row holding a tree-indent, a
tree-chevron, a tree-check when the tree is checkable, and a tree-label.
A row carries the classes expanded, selected and group, the last on a
row that cannot be selected, and matches :hover and :focus-visible. The
indent is 20px per level and the row height is --gb-list-row-height.
Keyboard
| Key | Does |
|---|---|
Up, Down | move focus between visible rows |
Right | opens a closed node, or moves to the first child of an open one |
Left | closes an open node, or moves to the parent |
Enter | selects, with Ctrl and Shift as the list has them |
Space | toggles the row’s checkbox |
Home, End | the first and last visible row |
* | opens every sibling of the focused row |
| letters | type-to-select over the visible rows |
A click on the chevron opens or closes without selecting. A click on a parent that cannot be selected opens it.
slot
A region of a document whose content the model decides: whatever widget a
bind= value holds.

The widget the model holds, drawn where the document put it.
slot bind="app.detail" id="detail" class="pane"
@Bind("app.detail") private Widget detail = new Text("Nothing selected");
void select(Person person) {
detail = new PersonForm(person); // the region redraws as the form
}
list, table and tree place a widget of their own kind. slot places any
widget: a detail pane that is a form for one selection and a message for none,
a toolbar that changes with the mode. The model holds the widget it builds and
replaces it when the region should change. The element subscribes to the
binding, so the region rebuilds and whatever is under it reconciles by key.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
bind | path | none | The widget a model holds. Nothing bound, or a value that is not a widget, draws nothing. |
id, class | string | Laid over the widget’s own id and classes, when it has any. |
Children are ignored. A slot has no CSS type of its own: what a stylesheet sees is the widget it draws.
Navigation
Three widgets that answer one question, where am I in a sequence: a trail of crumbs, a row of steps, and a wizard that puts steps over pages.
All three share one model. There is an ordered list, a current index, and a set of entries the application says are reachable. The widget draws the picture. The application moves the index. None of them decides on its own where the user may go next.

The Navigation screen of the showcase.
breadcrumbs
The path to here, as a row of crumbs with a chevron between each pair. The last crumb is where you are and does not press.

Three links and the current page.
breadcrumbs id="path" {
crumb icon="home" press="app.go-home" "Home"
crumb press="app.go-library" "Library"
crumb press="app.go-shelf" "Reference"
crumb "The Red Book"
}
new Breadcrumbs(
new Crumb("Home", actions::goHome).withIcon(homeIcon),
new Crumb("Library", actions::goLibrary),
new Crumb("Reference", actions::goShelf),
new Crumb("The Red Book")
).id("path");
The trail decides which crumb is current. It is always the last one written, so
a document cannot mark one and a Java caller cannot either. A trail longer
than collapse-after keeps its first crumb and its tail and folds the middle
into a … button. Pressing that button opens a menu of the hidden crumbs.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
collapse-after | number | 4 | How many crumbs show before the middle folds away. 0 or less never folds. 1 and 2 are raised to 3, which is the fewest a folded trail can show. |
id, class | string | The usual. |
The constructor new Breadcrumbs(Widget... children) folds at four.
collapseAfter(int) changes it.
Styling
The CSS type is breadcrumbs. Its parts are crumb, crumb-separator and
crumb-overflow. A crumb matches :hover and :focus-visible. The current
crumb matches :checked, and that rule removes the hover wash and the pointer
cursor. There are no variant classes.
Keyboard
| Key | On | Does |
|---|---|---|
Space, Enter | a crumb with a press | presses it |
Space, Enter, Down | the … | opens the menu of hidden crumbs |
Only a crumb that has a press and is not current is a Tab stop.
crumb
One entry in a trail: a label, an optional icon, and what pressing it does.

An icon and a label.
crumb icon="home" press="app.go-home" "Home"
new Crumb("Home", actions::goHome).withIcon(homeIcon);
new Crumb("The Red Book");
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | required | The label. A crumb with no label is refused at inflation. |
icon | icon name | none | An icon before the label, from the icon registry. |
press | action name | none | What pressing the crumb does. A crumb without one is not a link. |
id, class | string | The usual. |
A crumb’s children are ignored. Whether it is current is set by the trail, not by an attribute.
steps
A row of numbered discs that says how far along a process is. On its own it is
a picture. With clickable, a reachable step can be pressed.

Done, current and upcoming.
steps current=1 clickable=#true change="app.go-step" {
step reachable=#true "Account" description="Who you are"
step "Payment"
step "Review"
}
new Steps(1,
new Step("Account", "Who you are").reachable(true),
new Step("Payment"),
new Step("Review"))
.clickable(actions::goStep);
Every step before current is done. The step at current is current. The
rest are upcoming, unless a step says error. The widget writes those four
words as classes and never decides where the user may go: clickable raises a
change with the index of a step the application marked reachable, and
refuses the rest.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
current | number | 0 | The index of the current step. |
bind | path | none | A value to read the current index from instead. A bound number wins over current. |
direction | "horizontal", "vertical" | "horizontal" | Which way the row runs. |
clickable | boolean | #false | Lets a reachable step be pressed. |
change | action name | none | Called with the index of the pressed step, as a string. |
id, class | string | The usual. |
new Steps(int current, Widget... children) is horizontal and read-only.
direction(Direction), clickable(IntConsumer) and bound(Observable) set
the rest.
Styling
The CSS type is steps, with the class vertical when the direction is. A
step carries one of the classes done, current, upcoming, incomplete
or error, and the current one also matches :checked. Its parts are step-marker,
step-body, step-label and step-description. Between steps sits a
step-connector holding a step-connector-fill, which scales from the step
before it when that step is done. The marker is a 24px disc with a 2px ring: the accent when current, --gb-success
with a tick when done, --gb-danger with a cross on error, the ring alone
when upcoming. An incomplete step, one the list has passed that says it is not
done, keeps the ring and its number in full ink, so it reads as visited and
not ticked.
Keyboard
| Key | On | Does |
|---|---|---|
Space, Enter | a reachable step in a clickable list | raises change with its index |
A step is a Tab stop only when the list handed it a press. The list itself takes no arrow keys.
step
One step: a label, an optional description, and two flags the list reads.

A reachable step with a description.
step reachable=#true "Account" description="Who you are"
new Step("Account", "Who you are").reachable(true);
new Step("Verify").error(true);
new Step("Grafana", "Not signed in").complete(false);
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | required | The label. A step with no label is refused at inflation. |
description | string | none | A caption under the label. |
error | boolean | #false | Draws the step in --gb-danger with a cross, whatever its index. |
reachable | boolean | #false | Lets a clickable list press this step. |
complete | boolean | none | Whether the step is done. Unset, a step before the current one is done. #false there draws it incomplete, and #true after the current one draws it done. |
id, class | string | The usual. |
A step’s state is not an attribute. step current=#true is ignored, because
the list derives it from current. complete is the one exception to the
position: only the application knows that a step the user went past was left
undone.
wizard
A steps indicator over one page at a time, with Back, Next and Finish under
it. It owns no validation, no policy and no data.

The second of three pages, chosen by the bound step.
wizard id="signup" bind="signup.step" back="signup.back" next="signup.next" finish="signup.finish" {
page "Account" description="Who you are" {
text-input placeholder="Name"
}
page "Payment" {
text "Nothing to pay."
}
page "Review" {
text "All set."
}
}
new Wizard(current,
new WizardPage("Account", new TextInput().placeholder("Name")).describe("Who you are"),
new WizardPage("Payment", new Text("Nothing to pay.")),
new WizardPage("Review", new Text("All set.")))
.onBack(() -> goTo(current - 1))
.onNext(() -> goTo(current + 1))
.onFinish(() -> goTo(0))
.id("signup");
Back, Next and Finish only call their handlers. The application moves
current, by rebuilding with a new index or by setting the bound value, and a
wizard that will not advance is an application that did not move it. A page
the index has passed is done, unless it says complete=#false: then it is
drawn incomplete, visited and not done. A page marked error is drawn so
in the indicator. Only the current page’s children are built, and when the page
changes the keyboard moves into the new content.
Note
A button that has no handler is not shown. A wizard with no
back=has no Back. Next shows on every page but the last, where Finish takes its place.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
current | number | 0 | The index of the page shown. Out of range is clamped. |
bind | path | none | A value to read the index from. A bound number wins over current. |
back, next, finish | action name | none | What each button does. The button exists only when its action is named. |
go-to | action name | none | Makes the indicator clickable. Called with the index of a reachable page, as a string. |
back-label, next-label, finish-label | string | "Back", "Next", "Finish" | The button labels. |
id, class | string | The usual. |
new Wizard(int current, Widget... pages) has no buttons. onBack, onNext,
onFinish and goTo add them, labels(Labels) renames them, and
bound(Observable) reads the index from a value. Children that are not a
page are ignored.
Styling
The CSS type is wizard. Its parts are the steps indicator, wizard-content
and wizard-actions. The buttons are ordinary buttons, the affirmative one
with the class primary, and Back matches :disabled on the first page. A
theme that wants Windows order writes wizard-actions { flex-direction: row-reverse }. When the wizard has an id, the buttons take <id>-back,
<id>-next and <id>-finish, and the content <id>-content. The current
page’s classes land on wizard-content.
Keyboard
The wizard takes no keys of its own. The buttons take Space and Enter, and
the indicator takes what steps takes when go-to is wired.
page
One page of a wizard: a label for the indicator, and the content shown while it is current.

One page on its own.
page "Payment" description="How you pay" reachable=#true {
text "Nothing to pay."
}
new WizardPage("Payment", new Text("Nothing to pay."))
.describe("How you pay")
.reachable(true);
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | required | The label the indicator calls it by. |
description | string | none | The caption under that label. |
error | boolean | #false | Marks the page’s step as an error. |
reachable | boolean | #false | Lets a go-to indicator press this page’s step. |
complete | boolean | none | Whether the page is done, for a wizard whose pages may be passed undone. Unset, the position decides. |
id, class | string | The classes land on wizard-content while the page is shown. |
Any children are the page’s content. A page has no CSS type of its own.
Menus and the tray
A menu bar in the window, menus that open as platform windows of their own, context menus named on any widget, and a tray icon the desktop draws from the same menu value.
A menu is a widget: a menu holds items and separators, and an item
holding items is a submenu. Opening one is not a widget’s job. A menubar
opens its own headings, and anything else goes through Menus.open(host, …),
because opening needs a Host and a widget must not have one.
menubar
A horizontal bar of headings, each an item whose children are its menu.

The bar at rest. A menu opens on press.
menubar id="app-menu" {
item "File" {
item press="app.new" accelerator="Ctrl+N" "New"
item press="app.open" accelerator="Ctrl+O" "Open…"
separator
item press="app.quit" accelerator="Ctrl+Q" "Quit"
}
item "View" {
item press="app.toggle-hud" accelerator="Ctrl+F" checked=#false "Frame rate"
item "Theme" {
item press="app.light" "Light"
item press="app.dark" "Dark"
}
}
item "Help" {
item "Nothing here yet" disabled=#true
}
}
new MenuBar(
new Item("File").submenu(
new Item("New", actions::create).accelerator("Ctrl+N"),
new Item("Open…", actions::open).accelerator("Ctrl+O"),
new Separator(),
new Item("Quit", window::quit).accelerator("Ctrl+Q")
),
new Item("View").submenu(
new Item("Frame rate", window::toggleHud).accelerator("Ctrl+F").checked(hudShown),
new Item("Theme").submenu(
new Item("Light", () -> actions.pick("light")),
new Item("Dark", () -> actions.pick("dark"))
)
),
new Item("Help").submenu(
new Item("Nothing here yet").disabled(true)
)
).id("app-menu");
The bar owns its menus. It opens a heading’s menu as a popup against the heading, swaps to the neighbour when the pointer runs along the bar with a menu down, and binds every accelerator its rows name while it is mounted. A menu bar is a widget and not a property of the window, so a screen may have a second one.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id, class | string | The usual. |
The children are items. One that has children is a heading. A child that is
not an item is placed in the row unchanged.
Styling
The CSS type is menubar. Each heading is a menu-title, which matches
:hover, :focus-visible, :active and :disabled, and carries the class
open while its menu is down. The menus themselves are menu.
Keyboard
| Key | Does |
|---|---|
F10, or a tap on Alt | opens the first heading, or closes the bar when a menu is open |
Left, Right | walk the headings, and swap menus while one is open |
Enter, Space, Down | open the focused heading |
Escape | closes one menu, then the bar |
A bare Alt is a gesture rather than a shortcut, which is why it has a
registration of its own. There are no mnemonics.
menu
A column of rows: the value a context menu, a tray and a heading all hold.

Three items and a separator.
menu id="row-menu" {
item press="app.rename" "Rename"
item press="app.duplicate" "Duplicate"
separator
item press="app.delete" "Delete"
}
var rowMenu = new Menu(
new Item("Rename", actions::rename),
new Item("Duplicate", actions::duplicate),
new Separator(),
new Item("Delete", actions::delete)
);
Menus.open(host, "more-button", rowMenu).ifPresent(open -> this.menu = open);
A document declares a menu. Menus.open(host, anchorId, menu) measures it,
places it under the node with that id, flips it above when it would run off the
bottom of the screen, and opens it in a window of its own, so it may hang past
the window’s edge. The answer is empty when nothing with that id has been
painted or the platform has no popup windows. Choosing a command closes the
whole stack. A menu too tall for the screen scrolls.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id, class | string | The usual. |
The children are items and separators.
Styling
The CSS type is menu. A row that has an open submenu carries the class
open. When any row has an icon or is checkable, every row reserves an
item-lead column so the labels line up. A row that leads to a submenu ends in
an item-chevron. The row height is --gb-menu-item-height.
Keyboard
| Key | Does |
|---|---|
Up, Down | move between rows |
Enter, Space | run the row, or open its submenu at once |
Right | opens the submenu, or on a plain row moves to the next heading of a bar |
Left | closes a submenu, or moves to the previous heading of a bar |
Escape | closes this menu and no more |
The pointer opens a submenu after 150 ms of resting on its row, so a pointer crossing three rows on the way somewhere does not drop one out.
item
One row: a label, an optional icon, an accelerator to show, a tick, and either a command or a submenu.

An icon, a label, a check and an accelerator.
item icon="palette" press="app.toggle-theme" accelerator="Ctrl+T" checked=#true "Switch the light"
new Item("Switch the light", actions::toggleTheme)
.icon(paletteIcon)
.accelerator("Ctrl+T")
.checked(true);
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | The label. A row with neither a label nor an icon is refused. |
press | action name | none | The command. |
icon | icon name | none | An icon in the lead column. |
accelerator | string | none | Text shown right-aligned, and bound while a menubar holds the row. |
checked | boolean | absent | #true shows a tick, #false is a checkable row that is off, and no attribute is a row that is not checkable. |
disabled | boolean | #false | Greys the row and refuses it. |
id, class | string | The usual. |
A nested item is a submenu. That is the only thing an item can contain, and
there is no submenu node. A row cannot be both a command and a heading.
In Java, new Item(label, onPress) is a command, new Item(label) has
nothing behind it, and submenu(Widget...), icon, accelerator,
checked(boolean), checkable() and disabled(boolean) set the rest.
Styling
The CSS type is item. It matches :hover, :focus-visible, :active and
:disabled, and carries the class open while its submenu is. Its parts are
item-lead and item-chevron. The accelerator text has no part of its own.
separator
A rule between groups of rows.

A rule between items.
separator
new Separator();
It takes only id and class. The CSS type is separator, a 1px line in
--gb-border.
Accelerators
An accelerator is written as text, Ctrl+S, Shift+Ctrl+Z, Primary+Q. The
row shows the text as written. A menubar parses every accelerator under it
with Shortcut.of and binds it on the window while the bar is mounted, so the
key works with every menu shut. When the bar unmounts it gives back the keys
it took and no others.
Primary names the desktop’s own modifier, Cmd on macOS and Ctrl
elsewhere, so one document fits both. Ctrl, Control, Alt, Option,
Meta, Cmd, Super and Win are the other spellings.
Warning
Only a
menubarbinds. A menu that is only ever opened, a context menu or aMenus.opencall, shows its accelerators and registers none of them. Bind those withhost.shortcut(…)yourself. A row that is disabled, has a submenu, or has nopressis skipped.
The macOS menu bar
On macOS a menubar is the application’s menu bar, at the top of the screen,
and draws nothing in the window. Its headings follow the application menu,
which AppKit provides: About, Hide, Hide Others, Show All and Quit, under the
application’s title. The same document is a bar in the window on Linux and
Windows.
The platform fires the accelerators itself there, so the bar binds none in the
window, and F10 and a bare Alt do nothing. In the menu bar, and only there,
Ctrl with no Cmd beside it is read as Cmd. A menu written once as
Ctrl+O shows ⌘O on a Mac. Primary+O needs no reading at all.
In the menubar | In the macOS menu bar |
|---|---|
item with items | A menu, or a submenu inside one |
item with press | A command, with its accelerator as a key equivalent |
checked= | A tick |
disabled=#true | A greyed row |
separator | A dividing line |
| Anything else | Left out |
An application without a menubar can set the bar from Java with
host.applicationMenu(List<AppMenuItem>), which answers whether the platform
shows it. An empty list puts back what was there. There is no Window menu of
AppKit’s own. An application that wants Minimize and Zoom writes one.
Context menus
Any widget names its context menu, and the application says what the name means.
panel context-menu="content" {
text "Right-click anywhere in here."
}
@Override public void start(Host host) {
Menus.contextMenus(host, Map.of("content", contentMenu()));
}
A right-click walks up from the widget under the pointer to the first
ancestor with a context-menu and opens that menu at the pointer. The Menu
key, and Shift+F10, open the same menu at the focused widget instead. A name
the application never registered is logged and ignored. A right-click on a
list row selects it first.
In Java the attribute is .contextMenu("content") on any widget, or
.itemMenu(item -> "row-menu") on a list.
The tray icon
A tray icon is a menu somebody else draws. The application hands the desktop a
tooltip, a picture and an ordinary Menu, and the desktop’s shell themes it,
spaces it and clicks it. There is no markup node for it.
private Optional<ShownTray> tray = Optional.empty();
@Override public void start(Host host) {
var menu = new Menu(
new Item("Switch the light", actions::toggleTheme),
new Separator(),
new Item("Screens").submenu(
new Item("Basic", () -> actions.pickScreen("basic")),
new Item("Panels", () -> actions.pickScreen("panels"))
),
new Separator(),
new Item("Quit", () -> host.window().close())
);
tray = Trays.show(host, TrayIcon.of("Goldberry — showcase", menu).icons(onLightShell, onDarkShell));
}
@Override public void stop() {
tray.ifPresent(ShownTray::close);
}
| Call | What it does |
|---|---|
TrayIcon.of(tooltip, menu) | A tray with the platform’s default picture. |
.icon(PixelBuffer) | One picture, in physical pixels, 32×32 or 64×64. |
.icons(forLightShell, forDarkShell) | Two pictures, named for the panel each sits on. The tray follows the desktop’s theme while it is up, and shows the light-shell one where the desktop says nothing. |
.tooltip(String) | The hover text. |
Trays.show(host, tray) | Puts it up. Empty when this session has no notification area. |
ShownTray.menu(Menu) | Gives the menu new rows while the icon is up. The same shape changes in place; another shape replaces the rows under the same icon. |
ShownTray.close() | Takes it down and gives its accelerators back. The tray outlives the process if you forget, so close it in stop(). |
Rows map as a desktop expects: a checkable item is a checkbox row, a nested
item is a submenu, a disabled one is disabled. Icons and accelerators on rows
are dropped with a warning, because the shell draws the rows and takes neither.
The menu cannot be changed in place. Close the tray and show a new one.
Note
The tray is the desktop’s. Nothing in it is painted by Goldberry: the desktop shell draws the menu on Linux, an
NSMenuon macOS and a Win32 popup on Windows.
Overlays
What opens over the window: a modal dialog, a floating panel, a banner in the layout, a frame-rate readout, toasts, a guided tour, and tooltips on any widget.

The Overlays screen of the showcase.
There are two places something can go over a window, and every overlay uses one of them.
The overlay layer is part of the window’s own tree. Every window is rooted
at a WindowRoot, and an overlay is one of its children beside the
application’s, so it is painted by the same frame and clipped to the window.
host.overlay(widget, corner) puts a widget in a corner and host.fill(widget)
covers the window. Both return an Overlay whose remove() takes it away at
once and whose dismiss() lets its widget leave the way it leaves first.
A dialog, a HUD, a toast stack and a tour live here.
A platform popup is a second window the platform draws, parented to this
one and free of its bounds. host.popup(content, anchorId, placement) measures
the content, places it against the node with that id, flips it when it would
leave the screen, and opens it. The answer is an Optional<Popup>, and empty
is an ordinary answer: the video driver may have no popup windows, or nothing
with that id has been painted. A menu, a select’s list and a tooltip live here.
host.popup(new Popover(new Text("Saved.")), "save-button", Placement.BELOW)
.ifPresent(open -> this.hint = open);
Placement.BELOW, ABOVE and AFTER are the three sides, .align(Align)
chooses START, CENTER or END along the anchor, and .gap(float) the
distance. A popup is light-dismissed by default: a press in the owner window
or Escape closes it, and popup.close() does from Java.
A popup’s contents are the root of a tree of their own, so nothing inherits
into them. Selectors still reach in from where the popup was opened: a
descendant or child combinator in an application’s stylesheet steps out of the
popup’s root into the widget that opened it, and on up the window. A popup
opened against an id is opened from the widget with that id, a context menu
from the widget that was right-clicked, a tooltip from the widget it describes,
a submenu from its row, and a select’s list or a picker’s panel from the
control itself.
.toolbar > popover { padding: 4px }
.sidebar menu item { min-height: 32px }
A popup opened against a rectangle names no widget. OpenedFrom.call(context, () -> host.popup(...)) names one. The rules follow the opener while the popup
is open, so a class added to the toolbar restyles a popover already showing.
The toolkit’s own stylesheet does not reach in.
dialog
A modal: a veil over the window, a panel with a title and buttons, and a focus trap that keeps the keyboard inside until it is answered.

Three roles: neutral, dismissive and affirmative.
dialog id="unsaved" title="Unsaved changes" {
text "Your draft has not been saved. Discarding it cannot be undone."
action role="neutral" press="app.dont-save" "Don't save"
action role="dismissive" press="app.stay" "Keep editing"
action role="affirmative" press="app.discard" "Discard"
}
private Overlay open;
private void askToDiscard() {
open = Dialogs.show(host, new Dialog("Unsaved changes",
new Text("Your draft has not been saved. Discarding it cannot be undone."),
new DialogAction("Don't save", DialogAction.Role.NEUTRAL, this::dontSave),
new DialogAction("Keep editing", DialogAction.Role.DISMISSIVE, this::stay),
new DialogAction("Discard", DialogAction.Role.AFFIRMATIVE, this::discard))
.id("unsaved"));
}
private void discard() {
// The dialog has already faded and taken itself off the window.
draft.discard();
}
A dialog is a widget, and showing one is not: Dialogs.show(host, dialog)
fills the window with it and hands back the Overlay. Every route out, a
button, Escape, a press on the veil or the ×, fades the panel first, calls
the handler when the fade is over, and then removes the overlay. A handler does
not have to call remove(), and one that does is harmless. When the
application decides the dialog is finished without the user, open.dismiss()
runs the same fade, presses nothing, and removes it at the end.
open.remove() takes it away at once, with no fade.
Showing a dialog in the same turn another is removed is safe: each overlay is its own node, so the new dialog never inherits the old one’s state.
Height. A dialog is never taller than the window less 24 at the top and bottom. When its content would make it taller, the title and the button bar keep their size and the body scrolls. The body’s viewport is a Tab stop only while it has something to scroll, so a short dialog’s Tab order is its fields and its buttons.
The focus trap. While a modal is mounted the focused node is inside it.
Focus lands on the first focusable thing in the panel, Tab cycles within it,
and a press on the veil counts as the dismissive action. When the overlay is
removed the keyboard goes back to the one node that had it before, with the
same keyboard-or-pointer flag it had then. The veil is the whole of the
pointer’s modality, and modality is one flag on the panel.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
title | string | none | The title bar. Blank is the same as absent. |
dismiss | action name | none | Puts a × at the end of the title bar. The × closes the dialog and then runs the action, and Escape and the veil do the same. In Java, dialog.dismissible(handler). |
id, class | string | The usual. Dialogs.show gives an unnamed one the id dialog, and keeps a key set with keyed(…). |
action children become the button bar, in role order. Every other child is
the body. A dialog with two affirmative or two dismissive actions is refused,
because Enter and Escape each press exactly one button.
The × is for a dialog whose content has a button bar of its own, a wizard
for one, where a dismissive action would be a second Cancel. It is opt-in: a
dialog that must be answered stays one by default.
Styling
The CSS type is dialog, the panel, inside a dialog-scrim. Its parts are
dialog-title, dialog-body and dialog-actions. A dialog with a × puts the
title and a dialog-dismiss in a dialog-header row. The body sits in a
scroll with the class dialog-scroll. The buttons are ordinary
buttons: the affirmative one carries primary, a neutral one ghost, the
dismissive one neither. The bar puts the affirmative on the right. A theme
that wants Windows order writes dialog-actions { flex-direction: row-reverse }.
Padding 24, minimum width 320, maximum 80% of the window, and no taller than
the window less its margins.
Keyboard
| Key | Does |
|---|---|
Enter | presses the affirmative action |
Escape | presses the dismissive action, as a press on the veil does. In a dialog with a ×, it does what the × does |
Tab | moves within the dialog and never leaves it |
A dialog with no dismissive action and no × cannot be dismissed by Escape or
the veil. The × is not a Tab stop, because Escape is the same way out.
action
One button in a dialog’s bar, with the role that decides which key presses it.
action role="affirmative" press="app.discard" "Discard"
new DialogAction("Discard", DialogAction.Role.AFFIRMATIVE, this::discard);
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | The label. |
role | "affirmative", "dismissive", "neutral" | "neutral" | Enter presses the affirmative, Escape the dismissive, nothing presses a neutral. Any other word is refused. |
press | action name | none | What the button does. |
id, class | string | The usual. Children are ignored. |
popover
An anchored floating panel: the surface a popup shows, with the opening left
to Host.popup.

A card with text and a ghost button.
popover {
text "Saved a moment ago."
button class="ghost" press="app.undo" "Undo"
}
var popover = new Popover(
new Text("Saved a moment ago."),
new Button("Undo", actions::undo).styled("ghost")
);
host.popup(popover, "save-button", Placement.BELOW)
.ifPresent(open -> this.hint = open);
The two halves are deliberately not one widget. popover is the panel and
nothing else. Where it goes, when it flips and when it goes away belong to the
popup, which serves a tooltip and a select equally.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id, class | string | The usual. Any children. |
Styling
The CSS type is popover. A popover button rule sizes buttons inside it.
There are no parts, pseudo-classes or variants.
Keyboard
None of its own. The popup it is shown in closes on Escape while light
dismiss is on.
message
An inline banner about the region it sits in: a kind, an icon, text, optional action links and an optional dismiss.

Warning, danger with a dismiss, and success.
column {
message kind="warning" "Your session ends in five minutes." {
button class="ghost" press="app.extend" "Stay signed in"
}
message kind="danger" dismiss="app.clear" "Could not save: the port is in use."
message kind="success" "Saved."
}
new Column(
new Message(Message.Kind.WARNING, "Your session ends in five minutes.")
.actions(new Button("Stay signed in", actions::extend).styled("ghost")),
new Message(Message.Kind.DANGER, "Could not save: the port is in use.")
.dismiss(actions::clear),
new Message(Message.Kind.SUCCESS, "Saved.")
);
A message is not a toast. A toast is transient and floats over the window. A message is part of the layout and stays until the condition does. Its text can be bound, and a null or blank value renders as nothing, which is how a form’s error summary appears and goes:
message kind="danger" bind="form.error"
Message.summary(List<String>) builds one from a list of errors, or empty when
there are none.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | The text. |
kind | "info", "success", "warning", "danger" | "info" | The icon and tint. Any other word is refused. |
bind | path | none | A value to take the text from. Blank draws nothing. |
dismiss | action name | none | Adds a × that calls this. Without it there is no ×. |
id, class | string | The usual. The children are the action links. |
Styling
The CSS type is message, with the class success, warning or danger.
The base rule is the info look. Its parts are message-icon, message-body
holding the text and message-actions, and message-dismiss, which matches
:hover, :active and :focus-visible. Padding 12/16, radius 8, a 1px border
and a 4% tint of the kind’s colour.
Keyboard
The × is a Tab stop. Enter or Space on it dismisses.
hud
The frame loop, on top of the window it is running: frames per second and paint time by default, the whole breakdown on request.

At rest, before a frame has been measured.
hud readings="fps paint"
private Overlay hud;
private void toggleHud() {
if (hud != null) {
hud.remove();
hud = null;
} else {
hud = host.overlay(Hud.stages(), Corner.BOTTOM_END);
}
}
A HUD never asks for a frame. A readout that requested one so it could show a fresh number would be measuring itself. It reads the window’s statistics down the render context and updates when something else paints.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
readings | words | "fps paint" | Space-separated readings, or the preset stages or present. |
id, class | string | The usual. Children are ignored. |
The readings are fps, refresh, late, paint, build, style, layout,
raster, upload, acquire, submit, layers and pacing. layers is the GPU
layers’ own rendering time, judged against a quarter of a frame. pacing shows the present mode and effective frame cap.
Styling
The CSS type is hud. Each reading is a hud-reading carrying its name as a
class, hud-reading.paint, plus near or over when a time approaches or
passes the frame budget, and a hud-caption follows.
Toasts
A toast is a queue, and the stack is the widget. There is no toast node: a
Toast is a record, text with an optional action and a timeout, raised
through a controller from wherever it happens.
A stack of three. The newest is nearest the corner.
private final ToastController toasts = new ToastController();
@Override public void start(Host host) {
Toasts.at(host, toasts, Corner.BOTTOM_END);
}
private void sent() {
toasts.show(new Toast("Message sent.").action("Undo", actions::recall));
}
Toasts.at is called once. It puts one stack in the window’s corner and
returns the Overlay. After that the application holds the controller and
never mentions the stack again.
| Call | What it does |
|---|---|
new Toast(text) | A toast that stays five seconds. |
.action(label, runnable) | A button after the words. Pressing it runs the handler and starts the exit. |
.timeout(Duration) | How long it stays. Duration.ZERO never goes on its own. |
controller.show(toast), show(text) | Raises it, or queues it when three are showing. |
controller.clear() | Removes every toast. |
Toasts.of(context) | The controller from inside a widget’s build. |
Three show at once by default. A fourth waits its turn and comes forward while the oldest fades out. The timer pauses while the pointer is on a toast and resumes from where it was. A click on the plate dismisses it. When one leaves, the older ones slide to close the hole, and at a top corner the newest is nearest the top.
Styling
The stack is a toaster, with its corner as a class, toaster.bottom-end.
Each toast is a toast holding toast-text and, with an action, a
button.ghost. Width 360, padding 12/16, radius 8.
Tours
A guided sequence of stops over real widgets. The window dims except for the target, and a card beside it says what it is.
Tours.start(host, List.of(
new Stop("demo-tabs", "A strip of your own", "Chapters that can be closed."),
new Stop("jump-bar", "Jump to a chapter", "These bring a section into view."),
new Stop("gallery", "The gallery strip", "Every screen, and a Ctrl+digit for the first ten.")
));
A Stop names a target by id, with a title and a body. Tours.start(host, stops) fills the window with the tour and returns the Overlay, or null
for an empty list. Tours.start(host, stops, onEnd) is told when it ends.
Each stop reads the target’s painted rectangle on every build, scrolls it into
view first, and waits for the frame before placing the card. A stop whose
target is not on screen is logged and skipped. Stop.within(ScrollController)
names the scroll to use when the enclosing one is not the right one.
Styling
The CSS type is tour. Its parts are tour-veil, four tour-bands around
the cut-out, tour-ring and tour-card, which holds texts classed
tour-title, tour-body and tour-count, and buttons classed tour-skip,
tour-back and tour-next. The card is radius 12, padding 16, at most 320
wide, and the cut-out is inset 4 with radius 8. The veil’s cut-out travels
between stops.
Keyboard
| Key | Does |
|---|---|
Right | next stop |
Left | previous stop |
Escape | skips the whole tour |
Tooltips
A tooltip is an attribute, not a widget. Any node takes tooltip="…",
including one from an application’s own module, and the text rides on its
Attributes.
button press="app.open-menu" tooltip="A platform popup, free of this window's bounds" "Menu"
new Button("Menu", window::openMenu).tooltip("A platform popup, free of this window's bounds");
It shows after 500 ms of hover, or when keyboard focus arrives, placed above
the node and centred, and moves between neighbours after 100 ms. The tokens
--gb-tooltip-delay and --gb-tooltip-delay-move change the two delays. It is
never focusable and never light-dismissed: it closes when the pointer leaves or
focus moves, and not on a press. Plain text only.
Styling
The plate is the CSS type tooltip: padding 8/12, radius 4, caption, at most
320 wide, on --gb-hud-bg.
Charts
Five dashboard charts drawn on the canvas primitive: a line, grouped bars, a stacked area, a donut and a sparkline, in a palette the theme owns.
By the end of this chapter you can put a chart in a window from markup or Java,
give it series, a time axis, a limit and a fill, and read it from the keyboard.
The five widgets live in goldberry’s own catalogue. There is no chart engine
behind them, so a chart takes the theme, the text stack and hit testing like
any other widget.

The showcase's Charts screen. Every card is one of the five widgets below.
What the five share
The palette is the theme’s. A series takes a colour by its position, slot 1
to slot 8, read from --gb-chart-1 to --gb-chart-8. The order keeps adjacent
series apart under colour-vision deficiency, and a ninth series is drawn in
slot 8 again rather than in a generated hue. There is no colour argument. An
application that wants one series in one colour writes a rule, and the plot
and its legend swatch both follow it:
#revenue { --gb-chart-1: #b48ead; }
Data is a Series. Series.of("Downloads", 12, 19, 15) is a name and
values in order. A hole is Double.NaN, and a null in a list is read as one.
What the values are plotted against is the chart’s: the point index by default,
labelled by categories, or one Instant per point.
Markup holds small static data. A series node with point children is
for a sample or a fixture. Data from a model is Java, through the record.
A legend appears for two or more series. Clicking an entry shows that series alone, and clicking it again puts them all back.
Hovering draws a crosshair at the nearest point, a marker on each series and
a readout of what they read. The same crosshair can be shared across several
charts through a CrosshairGroup.
Long series are reduced to about one point per pixel before drawing, with the largest-triangle-three-buckets algorithm, so a spike survives where drawing every point would lose it.
A chart with no data says so. It keeps its box and shows a message, so a wall of loading cards does not reflow when the data lands.
line-chart
A trend with axes: one line per series, a legend, a crosshair and a readout.

Two series, an axis the chart chose, and a legend.
line-chart id="downloads" {
series name="Downloads" {
point "0.1" 1200
point "0.2" 3400
point "0.3" 2900
}
series name="Installs" {
point "0.1" 800
point "0.2" 2100
point "0.3" 2400
}
}
import dev.goldberry.widgets.data.Series;
import dev.goldberry.widgets.data.linechart.LineChart;
new LineChart(
List.of(Series.of("Downloads", 1200, 3400, 2900), Series.of("Installs", 800, 2100, 2400)),
List.of("0.1", "0.2", "0.3"),
Attributes.NONE.id("downloads")
);
The knobs are withers, and each returns a LineChart:
chart.fill(Fill.GRADIENT) // a fade under the line
.curve(Curve.SMOOTH) // monotone, cannot overshoot
.times(instants, ZoneOffset.UTC) // the x is when, not which
.threshold(Threshold.above(145, Threshold.Level.WARNING).labelled("Too long"))
.nulls(NullPolicy.ZERO) // GAP is the default
.softAxis(99, 100) // or .axis(0, 100) for a hard range
.logY() // a non-positive reading becomes a hole
.markers(Markers.ALWAYS) // AUTO by default
.crosshair(group) // a CrosshairGroup the application holds
.loading(); // or .failed("The query timed out")
Fill is NONE, SOLID or GRADIENT. Curve is LINEAR, SMOOTH or
STEP. NullPolicy is GAP, CONNECT or ZERO. Markers is AUTO,
ALWAYS or NEVER. A Threshold is at, above, below or band, in one
of four semantic levels, INFO, SUCCESS, WARNING or DANGER, and never a
series colour.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The chart’s id, for a rule that recolours one chart |
class | string | none | Classes on the chart’s box |
series children | nodes | none | One series per line. The categories come from the first series’ point labels |
Everything else is Java. A line-chart node takes no fill, curve, time axis or
threshold in markup.
Styling
The CSS type is line-chart, a column of the plot and the legend. Its parts are
chart-plot, chart-legend, chart-legend-entry, chart-legend-swatch and
chart-message. An entry carries .interactive when a click isolates its
series and .muted while its series is hidden. The message carries .failed
for a failure. chart-plot:focus-visible draws the focus ring. The series
colours are --gb-chart-1 to --gb-chart-8. The plot has no background of its
own, so a chart sits on whatever surface it was given.
Keyboard
Tab reaches the plot. Left and Right walk the crosshair, Home and End
jump to the ends, and Escape lets go.
series
One line of data, written inline: a name and its point children.

One series, two points.
line-chart {
series name="Uptime" {
point "Mon" 99.95
point "Tue" 99.91
}
}
new ChartSeries("Uptime", List.of(99.95, 99.91), List.of("Mon", "Tue")).toSeries(0);
A series node is a widget that draws nothing, so that the inflater can hand it
to its chart. Its parent reads it and never lays it out.
| Attribute | Type | Default | What it does |
|---|---|---|---|
name | string | series N | What the legend calls it, N being its position from one |
point children | nodes | none | The values, in order |
The CSS type is series, sized to zero.
point
One reading of a series: a label, then a number.

A point with a label and one without.
bar-chart {
series name="Riders" {
point "Mon" 3
point 2
}
}
The number is required, and a point with none is skipped. The label is
optional. A series whose labels are all blank gives the chart no x labels.
| Argument | Type | Default | What it does |
|---|---|---|---|
| label | string | "" | The x label, read from the first series only |
| value | number | required | The reading |
bar-chart
Magnitude by category: one group of bars per point, grouped and never stacked.

Two series side by side at each label.
bar-chart id="sightings" {
series name="Crebain" {
point "Mon" 18
point "Tue" 24
point "Wed" 14
}
series name="Riders" {
point "Mon" 3
point "Tue" 2
point "Wed" 5
}
}
new BarChart(
List.of(Series.of("Crebain", 18, 24, 14), Series.of("Riders", 3, 2, 5)),
List.of("Mon", "Tue", "Wed"),
Attributes.NONE.id("sightings")
);
The y axis includes zero and cannot be told otherwise, because a bar encodes its
value as a length. A negative value hangs below the zero line. markers,
logY, curve and times compile and draw the same pixels, and there is no
fill: a bar is a solid rectangle. softAxis, axis, threshold, nulls,
crosshair, loading and failed work as on a line chart.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The chart’s id |
class | string | none | Classes on the chart’s box |
series children | nodes | none | One series per bar in a group |
Styling
The CSS type is bar-chart, with the same parts, pseudo-classes and tokens as
line-chart. Hovering highlights the band under the pointer.
Keyboard
As line-chart: Left, Right, Home, End and Escape on the focused plot.
area-chart
A total and what it is made of: the series stacked into bands that add up.

Two series stacked, the second on top of the first.
area-chart id="provisions" {
series name="Lembas" {
point "Mon" 40
point "Tue" 52
point "Wed" 44
}
series name="Dried meat" {
point "Mon" 12
point "Tue" 9
point "Wed" 15
}
}
new AreaChart(
List.of(Series.of("Lembas", 40, 52, 44), Series.of("Dried meat", 12, 9, 15)),
List.of("Mon", "Tue", "Wed"),
Attributes.NONE.id("provisions")
).curve(Curve.SMOOTH)
.fill(Fill.GRADIENT);
Use a line-chart when the series are separate quantities and an area-chart
when they are parts of one. The y axis includes zero. A curve is applied to
both edges of a band, so the fill stays the difference its numbers say. fill
is SOLID by default. GRADIENT fades each band within its own extent, and
NONE is read as SOLID, because a band with no fill is not a band. markers
and logY are ignored.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The chart’s id |
class | string | none | Classes on the chart’s box |
series children | nodes | none | One series per band, bottom first |
Styling
The CSS type is area-chart, with the same parts, pseudo-classes and tokens as
line-chart.
Keyboard
As line-chart.
donut-chart
Part to whole: three to eight slices of one ring, with a legend that is always shown.

One point per series, each a segment.
donut-chart id="packs" {
series name="Lembas" {
point 62
}
series name="Dried meat" {
point 24
}
series name="Nothing" {
point 14
}
}
new DonutChart(
List.of(Series.of("Lembas", 62), Series.of("Dried meat", 24), Series.of("Nothing", 14)),
Attributes.NONE.id("packs")
);
One number per slice: the first value of each series. A donut of two slices is
refused when it is built, because two parts are a ratio and progress reads
better. A donut of nine is refused too, because the palette has eight
distinguishable hues and the arcs are too narrow to compare. A donut has no
axes, no crosshair and no isolation. Hovering shows a slice’s share in the hole.
loading() and failed(message) are its only knobs.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The chart’s id |
class | string | none | Classes on the chart’s box |
series children | nodes | none | One series per slice, three to eight of them |
Styling
The CSS type is donut-chart, a column of donut-plot and chart-legend. The
legend’s entries are a key, not controls, so they carry no .interactive.
donut-plot:focus-visible draws the focus ring.
Keyboard
Left and Right walk the ring, wrapping at the ends, Home and End jump
to the first and last slice, and Escape lets go.
sparkline
A trend with no axes, no legend and no readout: the shape of a change beside a number.

Filled, with a marker at the end.
sparkline id="safe" fill=#true marker=#true 61 68 74 79 83 86 89 91 93
new Sparkline(List.of(61.0, 68.0, 74.0, 79.0, 83.0, 86.0, 89.0, 91.0, 93.0)).fill(true).marker(true);
new Statistic("Days without loss", "93", "d", "+7", Statistic.Direction.UP,
new Sparkline(SAFE, true, true, Attributes.NONE), Attributes.NONE);
The values are the node’s arguments, which is the one chart shape small enough
to write inline. The line is scaled to the data’s own minimum and maximum, not
to zero, because its job is the shape. A flat series is centred. Fewer than two
values draws nothing. A sparkline is one series, so it has no palette slot: it
is drawn in the color it inherits, which is how one inside a statistic takes
the delta’s hue. A statistic takes its sparkline in Java only: its markup node
reads no child.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| arguments | numbers | none | The values, in order. Anything that is not a number is skipped |
fill | boolean | #false | A faint fill beneath the line |
marker | boolean | #false | A dot on the last point |
id | string | none | The sparkline’s id |
class | string | none | Classes on its box |
Styling
The CSS type is sparkline. It takes color for the line, the fill and the
marker, and width and height from the stylesheet. The stroke is 1.5 px and
is not a CSS property.
Keyboard
None. A sparkline is not focusable.
What is not a chart here
The scope is dashboard-grade and five widgets. That rules out the following.
- No dual y-axis. Two measures at different scales are two charts, or one indexed to a common base.
- No colour per series. The palette is assigned by position. A rule on the chart’s id is the override.
- No query layer, no auto-refresh, no time-range picker. A chart takes a
Seriesand redraws because the model changed. - No histogram, heatmap, scatter, candlestick, pan or zoom. Those are science-grade, and there is no module for them.
- No sixth widget. When a request fits none of the five, the answer is a
canvas, atable, or a different module.
Canvas, images and QR codes
A canvas is the surface an application draws on itself, an image shows a decoded picture, a QR code is a payload drawn as modules of whole device pixels, and an icon is one outline at whatever size its box is.
By the end of this chapter you can draw with paths, strokes, gradients and
images on a canvas, hear the pointer and the keyboard on it, place a picture
with one of four fit modes, put a scannable code in a dialog, and size an icon
from the stylesheet.
The showcase's Drawing screen. The drawings are a canvas each, the four photographs are image widgets, and each card links back to its section here.
canvas
An immediate-mode drawing surface: a box whose painter is handed the frame, translated to the box’s content corner and clipped to it.
canvas id="plot" class="chart"
import dev.goldberry.widgets.core.canvas.Canvas;
new Canvas((frame, size) -> {
frame.fillRect(0, 0, size.width(), size.height() / 2, 0xFF88C0D0);
}, Attributes.NONE.id("plot").classes("chart"));
The painter is Java.“ with:
The painter is Java, so markup names one rather than writing it. painter= and
input= name objects the application bound in its Named registry, as
canvas3d renderer= does:
var named = Named.strict().bind("app.revenue", (Painter) chart::paint);
A canvas that names neither is a styled, sized surface that draws nothing.
The painter
A Painter is paint(Frame frame, LogicalSize size). The frame’s origin is the
canvas’s top-left and the clip is its content box, so a painter cannot escape
its bounds. The toolkit brackets the call in save and restore, so a painter
may set a clip or a transform and leave it set. It runs on the UI thread inside
the frame, so it must not block and must not keep the frame.
var hill = Path.builder()
.moveTo(0, height)
.lineTo(0, height * 0.55)
.cubicTo(width * 0.25, height * 0.2, width * 0.45, height * 0.9, width * 0.6, height * 0.5)
.lineTo(width, height)
.close()
.build();
frame.fillPath(hill, Gradient.fade(0, height * 0.2, 0, height, CssColor.fade(ink, 0.55)));
frame.strokePath(Path.circle(cx, cy, 14), Stroke.round(2), accent);
frame.strokePath(Path.line(0, y, width, y), Stroke.of(1).dashed(4, 4), muted);
frame.drawImage(logo, 16, 16);
Frame fills and strokes a Path, with a colour or a Gradient, draws an
Image at its natural size or scaled and faded, clips with clipTo, and
transforms with transform, concat and resetTransform. Path has a builder
with moveTo, lineTo, quadTo, cubicTo, arcTo, close and append,
and factories line, polyline, rect, roundRect, ellipse, circle and
arc. A path is a value, so path.rotated(radians, cx, cy),
translated, scaled and transformed(affine) make a turned copy, and
frame.concat composes a transform onto the one the canvas already has.
A Stroke is of(width) or round(width), with cap, join, dashed(on, off)
and dash(Dash). The toolkit computes a dash itself and does not ask the
rasterizer for one.
A three-parameter painter is a StyledPainter and is handed a CanvasStyle:
the node’s resolved font and ink, this frame’s nowMillis, and
reducedMotion. So canvas { color: var(--gb-text) } reaches the drawing.
new Canvas((frame, size, style) -> {
Paragraph.of(style.font(), "Revenue").paint(frame, 0, 0, size.width(), style.ink());
});
A canvas is painted once and left there. animating asks for the next frame
for as long as a predicate over the same CanvasStyle says so:
new Canvas(floor::paint).animating(style -> style.nowMillis() - mounted < SETTLE_MILLIS);
A picture cut in nine is drawn with drawNineSlice: its corners whole, its
edges and middle stretched or tiled between them, the way a stylesheet’s
border-image draws a box’s edge. The cut is a NinePatch, made once:
private static final NinePatch PLATE = NinePatch.of(22, 64, 22, 64); // top, right, bottom, left
frame.drawNineSlice(namePlate, PLATE, 0, 0, size.width(), 40);
frame.drawNineSlice(namePlate, PLATE.withWidths(8, 24, 8, 24).withRepeat(Repeat.ROUND, Repeat.STRETCH),
0, 48, size.width(), 40);
The slice lines are in the picture’s pixels, and atDensity(2) reads them in
a @2x picture’s. Each side is drawn at its slice’s size unless withWidths
says otherwise. When two opposite sides do not fit, all four shrink by the
same factor, so a corner keeps its shape. withFill(false) leaves the middle
out, and withRepeat tiles the edges and the middle, at their own scale
(REPEAT) or a whole number of times (ROUND). Every seam is on a whole
device pixel, so nothing behind shows between a corner and its edge.
Input
An Input beside the painter makes the canvas hear the pointer and the keyboard.
The events are the toolkit’s own PointerEvent and KeyEvent, and
event.content() is measured from the corner the painter draws at.
new Canvas(board::paint, new Input() {
@Override
public void onPointer(PointerEvent event) {
var at = event.content();
switch (event.kind()) {
case PRESSED -> board.beginDrag(at.x(), at.y());
case MOVED -> board.dragTo(at.x(), at.y());
case WHEEL -> board.zoom(event.deltaY(), at.x(), at.y());
default -> { }
}
}
});
A drag that leaves the canvas keeps reporting, because the router captures the
pointer on press. event.consume() keeps a wheel from scrolling the pane the
canvas sits in. onKey, onText and onPreedit arrive when the canvas has
focus, and wantsText() turns the platform’s input method on for a canvas that
holds an Editor. accessibleName() names the figure for a reader.
path.contains(x, y) says whether a point is inside a path’s fill, by the
nonzero rule a fill uses, or path.contains(x, y, true) for evenodd. A
board hit-tests what it drew with it: a click lands in a note’s rounded
outline, not its bounding box, and not in the hole of a ring. A box with a
clip-path: path(…) is hit by the pointer the same way.
Widgets over the drawing
A painted rectangle has no focus ring, no name a reader can announce and no
place in the Tab order. Where something drawn has to have all three, such as
the events on a week grid, overlay places a real widget over it:
new Canvas(week::paint, week).overlay(size -> week.layout(size).blocks().stream()
.map(block -> new Positioned(
new Pressable(block.title(), () -> open(block.event())).keyed(block.event().id()),
block.rect()
))
.toList());
The function is handed the size of the content box, the rectangle the painter
is told about, and answers with Positioned widgets, each at a rectangle in
the painter’s own coordinates. Each widget fills its rectangle. They are
ordinary widgets inside the canvas’s box:
- drawn over the painting and clipped to the content box, and scrolled with
the canvas when a
scrollmoves it; - hit-tested before the painting, so a press on one goes to it and not to the
canvas’s
Input, and a press beside it reachesInputas before; - focusable in the order of the list, so a list in visual order is a Tab order in visual order;
- listed in the semantics tree under the canvas, with their own roles and names.
The list is asked for again whenever the content box changes size and whenever the canvas is rebuilt. A widget whose key comes back keeps its element, and with it its focus and its state, so key each one by what it shows. The widgets arrive one frame after the canvas is first laid out, because the size they are placed by is the one that frame measured.
A positioned widget can be draggable like any other, and the canvas can be
a drop target: an event dragged to another day lands on the canvas with the
point in the painter’s coordinates. See
Dragging between widgets.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
id | string | none | The canvas’s id |
class | string | none | Classes on its box |
painter | name | none | A Painter or StyledPainter the application bound |
input | name | none | An Input the application bound |
Styling
The CSS type is canvas. It is a box first: background, border,
border-radius, padding, width, height and every layout property are the
stylesheet’s, and the painter draws inside the padding. A canvas has no size of
its own, so one in a row with nothing to size it is zero wide. cursor works
as on any box. Its role is figure.
isolation: isolate keeps what the painter drew: the canvas becomes a group with
a raster of its own, and while nothing about it changes later frames copy the
raster instead of calling the painter. An animating canvas is drawn on every
frame either way.
The widgets of an overlay sit in a canvas-layer covering the content box,
each in a canvas-item at its rectangle.
Keyboard
A canvas is focusable exactly when it has an Input whose focusable() is
true. Keys reach onKey. A canvas with no input is not a Tab stop.
The widgets of an overlay are Tab stops of their own, after the canvas and in the order of the list.
image
A picture, loaded off the frame on a virtual thread and drawn at its natural size until a stylesheet says otherwise.

With no image source bound, each image is its alt text.
column {
image src="photos/harbour.jpg" alt="The harbour at dusk" fit="cover"
image srcset="classpath:logo.png 1x, classpath:logo@2x.png 2x" alt="Goldberry"
image src="classpath:divider.png" decorative=#true
}
import dev.goldberry.widgets.core.image.ImageView;
import dev.goldberry.widgets.core.image.ImageSource;
import dev.goldberry.widgets.core.image.Fit;
new ImageView(ImageSource.file(path), "The harbour at dusk").fit(Fit.COVER);
new ImageView(ImageSource.resource(App.class, "logo.png"), "Goldberry").variant(2, ImageSource.resource(App.class, "logo@2x.png"));
ImageView.decorative(ImageSource.resource(App.class, "divider.png"));
An ImageSource is a file(path), a resource(anchor, name), bytes(data),
an Image already decoded with of(image), or supplied(key, supplier) for a
thumbnail generator or an HTTP fetch run on a virtual thread. The shared loader
decodes each source once per process, so ten thumbnails of one file decode
once. While the pixels are on their way the box carries .loading. When they
cannot be decoded it carries .error and shows a broken-image icon with
the alt text.
The record is ImageView. The Java name differs from the markup name because
Image is the decoded value in dev.goldberry.image, which an application
holds, pastes and encodes without a widget. The format comes from the bytes:
PNG, JPEG, QOI, WebP and GIF decode, and an animated GIF decodes to its first
frame. SVG decodes with goldberry-vector on the module path and its native
library for the platform. The image has the document’s natural dimensions.
A larger box or a higher display scale requests a raster at the new device
size. This also applies to CSS url() images and to images in HTML and
Markdown. In these contexts currentColor defaults to black.
Important
An image needs
alttext ordecorative=#true, and is refused when it has neither. A picture a reader is told is a figure and nothing more is worse than one they are not told about.
Fit modes
fit | What is drawn |
|---|---|
contain | The whole image, as large as fits, letterboxed. The default |
cover | The box filled, the image cropped to the box’s shape |
fill | The box filled, the image stretched to its shape |
none | The image at its natural size, centred, cropped if larger |
The image is always centred. cover crops rather than clips, so it needs no
overflow: hidden and cannot paint over a neighbour.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
src | string | none | One path. classpath: names a resource on the application’s class loader. Exactly one of src and srcset is required |
srcset | string | none | Several paths with scales: logo.png 1x, logo@2x.png 2x |
alt | string | "" | What the picture shows, for a reader. Required unless decorative |
decorative | boolean | #false | The picture shows nothing a reader needs, and leaves the semantics |
fit | contain, cover, fill, none | contain | How the picture fills a box of another shape. A misspelt value is refused |
id | string | none | The image’s id |
class | string | none | Classes on its box |
Styling
The CSS type is image. With no width and height the box is the picture’s
natural size, one image pixel per device pixel, and max-width shrinks it in
proportion. With one of them the other follows the picture’s shape. With both,
fit decides. The classes loading and error are added while a load stands
there, and image-alt is the part that shows the alt text on failure.
Keyboard
None. An image is not focusable.
Vector animations
A Lottie document, the format of a Telegram tgs sticker, is a description
rather than a picture: shapes, colours and easing curves. VectorAnimation
reads one, gzipped or plain JSON, and draws it at whatever size it is asked
for. AnimationView plays one on the frame loop, the way image shows a
picture.
import dev.goldberry.image.anim.VectorAnimation;
import dev.goldberry.widgets.core.image.AnimationView;
var sticker = VectorAnimation.of(Files.readAllBytes(path)); // .tgs or .json
new AnimationView(sticker, "🎉");
AnimationView.decorative(sticker.loops(1)).autoplay(false);
Image still = sticker.imageAt(500, 128, 128); // half a second in
new Canvas((frame, size) -> sticker.paint(frame, elapsed, 0, 0, size.width(), size.height()));
The view starts from the first frame when it is first drawn, and asks for
frames only while the animation moves. With autoplay(false), or when the
platform says its user wants less movement, it shows the first frame and the
loop stays idle. An animation plays for ever unless loops(n) says otherwise,
and then holds its last frame. Its CSS type is image, it is sized like an
image (the animation’s canvas in logical pixels until a stylesheet says
otherwise), and it takes the same Fit and the same alt-text rule.
What is drawn is the subset Telegram allows in a sticker, and somewhat more:
shape, null, solid and precomp layers with parents; groups and their
transforms; rectangles, ellipses, stars, polygons and paths; flat and gradient
fills and strokes, dashed or not; trims, mattes and masks; held, eased and
curved keyframes, and paths that change shape. A document with an expression or
an image layer in it is refused with an ImageDecodeException, as bytes that
are not a Lottie document are. Anything else unknown, such as a text layer or a
layer effect, is passed over, and the rest is drawn.
There is no markup node for an animation yet: the document is bytes the application has, not a path a page names.
After the paragraph that introduces AnimationView:
AnimationView plays any MovingPicture, the interface VectorAnimation
implements. goldberry-media’s VideoAnimation is the other one: a WebM
sticker, drawn with its transparency (see the media chapter).
svg-view
Use svg-view for a diagram or icon whose ink follows the surrounding text.
This leaf takes its fill from the view’s CSS color. Changing the theme or
a :hover rule updates the drawing. Colours written directly in the SVG
keep their values.

An inline SVG whose fill follows the view's text colour.
svg-view alt="Leaf" "<svg viewBox='0 0 48 48'><path fill='currentColor' d='M6 41Q5 9 41 6Q42 40 11 37Z'/></svg>"
A src can name a file or a classpath resource. Supply either the inline
document or the source. Give each figure alt text describing its content.
Use decorative=#true when the surrounding text already conveys it.
svg-view src="classpath:/art/hills.svg" alt="Sun over two hills" fit="contain"
import dev.goldberry.vector.view.SvgSource;
import dev.goldberry.vector.view.SvgView;
var hills = new SvgView(SvgSource.resource(App.class, "/art/hills.svg"), "Sun over two hills");
If the resource belongs to a package in a named module, open that package
to dev.goldberry.vector for the Java anchor. The classpath: form uses
the class loader, which needs that package to be open unconditionally.
Add dev.goldberry:goldberry-vector and its matching natives-<target>
classifier to the application. For example, on Linux x64 the classifier is
natives-linux-x64. A modular application requires dev.goldberry.vector
and grants it native access with --enable-native-access=dev.goldberry.vector.
Add VectorStyles.stylesheet() beside the controls’ stylesheets to style
the loading placeholder and the error icon and alt text.
A Gradle build using the Goldberry BOM can declare the Linux x64 dependencies together.
implementation 'dev.goldberry:goldberry-vector'
runtimeOnly 'dev.goldberry:goldberry-vector::natives-linux-x64'
CSS width or height sets one dimension and the other follows the
document’s proportions. With both set, contain fits the whole drawing,
cover crops to the box, none keeps the natural size and fill gives
the document that viewport, respecting its own preserveAspectRatio.
Paths, gradients, clips, masks, references within the document and embedded PNG or JPEG data URIs are supported. Convert lettering to paths when it must appear in the artwork. SVG text, external references, scripts and animation are unsupported. Documents are limited to 16 MiB and a raster to 8192 pixels per side and 64 million pixels overall.
qr-code
A QR code for a payload, drawn in modules of whole device pixels so a phone camera reads it at any scale.

A code at error-correction level M.
qr-code value="https://goldberry.dev" level="M" quiet-zone=4 name="Scan to open goldberry.dev"
import dev.goldberry.widgets.core.qrcode.QrCode;
import dev.goldberry.image.qr.Level;
new QrCode("https://goldberry.dev").level(Level.H).withAttributes(Attributes.NONE.name("Scan to open goldberry.dev"));
new QrCode(link, Level.L, 4, Attributes.NONE.id("qr-low"));
The encoder is the toolkit’s own, in dev.goldberry.image.qr beside the image
codecs, and QrEncoder.encode(payload, level) returns the same QrMatrix with
no widget. The widget divides its box into a whole number of device pixels per
module and turns the remainder into margin, so what changes between 100 % and
200 % is how many pixels a module is, never whether its edge lands on one. A box
too small for one pixel per module draws nothing. A payload no version holds is
refused when the widget is built. Rebuilding with the same payload does not
re-encode.
The payload is not part of the accessible name, because a sign-in token is a
credential. Give the widget a name that says what the code is for.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
value | string | "" | The payload, encoded as UTF-8 |
level | L, M, Q, H | M | How much of the code may be destroyed and still read. Anything else falls back to M |
quiet-zone | number | 4 | The light margin around the code, in modules. Four is the standard’s |
name | string | none | What a reader is told the code is |
id | string | none | The code’s id |
class | string | none | Classes on its box |
Styling
The CSS type is qr-code. The default sheet makes it 160 by 160 with
flex-shrink: 0, and an application sets width and height like anything
else. The ink is --gb-qr-ink and the paper is --gb-qr-paper, and both are
the same near-black on white in the dark theme as in the light one, because many
scanners will not read an inverted code. The quiet zone is painted in the paper
colour.
Keyboard
None. A code is a figure.
icon
One icon on its own, as big as the stylesheet makes its box and in the box’s colour.
One icon at three sizes the stylesheet chose, and one coloured.
row class="icon-sizes" {
icon "cloud-upload" class="small"
icon "cloud-upload"
icon "cloud-upload" class="large"
icon "circle-alert" class="warn" name="Not signed in"
}
import dev.goldberry.widgets.core.icon.IconView;
new IconView("cloud-upload").styled("small");
new IconView(Icon.bundled("circle-alert", 24)).withAttributes(Attributes.NONE.classes("warn").name("Not signed in"));
icon.small { width: 11px; height: 11px; }
icon.large { width: 24px; height: 24px; }
icon.warn { color: var(--gb-warning); }
Inside a button an icon is drawn at the size it was built at. Here the box
decides: width and height, 16 by default, and the outline is scaled to the
smaller of the two and centred along the other. The bundled set is drawn on a
24-unit grid with a 2-unit stroke, and the stroke scales with it, so an 11 px
icon is the same drawing as a 24 px one, thinner. width: 1em; height: 1em sizes an
icon to the text beside it. Nothing native is held, so a document reloaded on
every keystroke builds nothing that has to be closed.
The argument is looked up in the application’s Icons registry first, so
icon "home" draws whatever the application registered as home, and then in
the bundled set. A name that neither has is an empty box of the same size with
the class missing, rather than an error. A stylesheet may draw a fallback on
it:
icon.missing { background: currentColor; border-radius: 9999px; width: 6px; height: 6px; }
In Java, Icon.find(name, size) is the same lookup for a name that comes from
outside the program. It returns an Optional<Icon>, where Icon.bundled
throws.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | none | The icon’s name: a registered one, or one from the bundled set |
name | string | none | What a reader is told. Without one the icon is decorative |
id, class | string | The usual |
Styling
The CSS type is icon, with the class missing when the name found nothing.
The default sheet makes it 16 by 16 with flex-shrink: 0. The stroke is the
box’s color, which it inherits like text.
Keyboard
None. A named icon is a figure, and an unnamed one is decoration.
Markdown, HTML and the web
A Markdown note and an HTML page render as ordinary widgets under the ordinary cascade, and a web page is a window the desktop's own engine draws where the window system allows one.
By the end of this chapter you can show a document that follows a property, answer its links and task boxes, let a reader select and copy from it, and decide whether a real web page can be offered on the machine you are on.
The two views are in the goldberry-html module. Add it beside the toolkit and
add its stylesheets beside the controls’ own, or a document renders as unstyled
words:
var sheets = new ArrayList<>(Controls.stylesheets(theme));
sheets.add(MarkdownStyles.stylesheet());
sheets.add(HtmlStyles.stylesheet());
Nothing in the core knows the module exists. Its catalogue announces the two node names, and the inflater finds them when the module is on the module path.

The showcase's Markdown screen. The editor writes one property and the view reads it.
markdown-view
A rendered Markdown document: GitHub’s dialect by default, folded into column, row and text.

The source and the document it renders, side by side.
split-pane position=0.5 first-min=240 second-min=240 {
text-area class="mono" bind="note.source" change="note.set-source" fill=#true
scroll {
markdown-view bind="note.source" link="app.open" wikilink="app.open-page" images="app.assets" task="note.toggle-task"
}
}
import dev.goldberry.markdown.Markdown;
import dev.goldberry.markdown.view.MarkdownView;
var view = MarkdownView.following(model.source())
.onLink(app::open)
.onWikiLink(app::openPage)
.images(assets)
.onTask(index -> model.setSource(Markdown.toggleTask(model.source(), index)));
A live preview is a binding. The editor writes note.source through its action
and the view reads the same property with bind=. Nothing watches the editor
or schedules a render: a keystroke marks the view for rebuild and the next frame
is the parsed document. A block whose source did not change keeps the widget it
had, so a keystroke on a 50 kB note costs about 2 ms of build.
Markup may also carry the document as the node’s argument. syntax picks the
dialect, and a view with a document and a binding shows the document until the
property answers.
markdown-view "A *little* document." syntax="commonmark"
In Java a Document is a value: Markdown.parse(text) or
Markdown.parse(text, MarkdownSyntax.commonMark()) returns a sealed tree an
application can walk for an outline before handing it to
MarkdownView.of(document). MarkdownView.of(text) parses for the caller who
wants a preview and nothing else. MarkdownHtml.of(document) writes the same
tree out as an HTML fragment, so a preview and the bytes a server hands out
cannot drift.
Links, images and tasks
A rendered document is read, and the application answers.
A link is a button.link, a Tab stop that hands its href to link= and does
nothing else: no browser opens and no path resolves. A [[wiki link]] hands its
target to wikilink=, and a view with no handler draws it inert. An image is
its alt text until an ImageSource the application supplies turns the src
into pixels. A task box reports its ordinal to task=, and
Markdown.toggleTask(source, index) flips that one character of the source.
The ordinal crosses as the string a document would have written.
Selection
Drag across the document, double-click a word, triple-click a block, Ctrl+A
and Ctrl+C. What lands on the clipboard has the space between words and the
newline between blocks that the document implies.
Nothing to switch on. A drag repaints rather than rebuilds.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | The Markdown source, shown until bind answers |
bind | binding | none | A property whose text is parsed on every build |
syntax | github, commonmark | github | The dialect. Anything else is refused |
link | valued action | none | Handed a link’s href |
wikilink | valued action | none | Handed a wiki link’s target |
images | named ImageSource | none | Where an image’s src becomes pixels |
task | valued action | none | Handed a task box’s ordinal, from zero |
id | string | none | The view’s id, on the column it builds |
class | string | none | Classes on that column |
Children are refused, and there is no src= to read a file with.
Styling
markdown-view composes and has no box of its own. It builds a column with
the class markdown, and markdown.css hangs every rule off a class: md-h1
to md-h6, md-prose, md-line, md-lines, md-word, md-em,
md-strong, md-struck, md-underline, md-code, md-code-block,
md-code-line, md-code-language, md-link, md-wikilink, md-list,
md-item, md-item-body, md-marker, md-quote, md-quote-body, md-table,
md-row, md-cell, md-rule and md-raw. A link is a button with the class
link. The sheet is in the toolkit’s base layer, so an application’s rule wins
without !important.
Keyboard
Tab reaches each link, and Space or Enter presses it. Ctrl+A selects the
document and Ctrl+C copies the selection.
What it does not do
Emphasis uses the italic face. Wrap the view in scroll
when the application needs a scrollable viewport.

The HTML screen of the showcase: the source and the page it renders.
html-view
A rendered HTML document: parsed in Java into a model of records and folded into the same widgets the Markdown view uses.

A heading, emphasis and a link.
scroll {
html-view bind="doc.source" link="doc.open" images="app.assets"
}
import dev.goldberry.html.Html;
import dev.goldberry.html.view.HtmlView;
var document = Html.parse(help.body());
var view = HtmlView.of(document).onLink(app::navigate).images(assets);
var links = document.find("a");
HtmlView.following(model.source()) is the Java spelling of bind=, and
HtmlView.of(text) parses for a caller who wants a page and nothing else. The
document may also be the node’s argument:
html-view "<p>A <em>little</em> page with <a href=\"/help\">a link</a>.</p>" link="doc.open"
An anchor becomes a button.link that hands its href to link=. It is a Tab
stop, it hovers and it takes Space and Enter, so a help page is navigable
from the keyboard. Whether the link may be followed is the application’s: no
browser opens, no relative path resolves and nothing is fetched. Selection and
copy work as in the Markdown view.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
| argument | string | "" | The HTML source, shown until bind answers |
bind | binding | none | A property whose text is parsed on every build |
link | valued action | none | Handed an anchor’s href |
images | named ImageSource | none | Where an <img src> becomes pixels. Without one an image is its alt text |
author-styles | ignored, theme-colours, adapted or as-written | adapted | What is done with the page’s own <style> and style=; see A page’s own styles |
id | string | none | The view’s id, on the column it builds |
class | string | none | Classes on that column |
Children are refused, and there is no src=.
Styling
html-view builds a column with the class html. Every element contributes
the class html-<tag>, so html.css reads like a browser’s default sheet and a
tag nobody anticipated is already styleable. A page’s own class="callout"
arrives as html-callout. The structural classes are html-block, html-prose,
html-line, html-lines, html-word, html-list, html-item,
html-item-body, html-marker, html-table, html-row, html-cell,
html-caption, html-quote, html-quote-body, html-pre, html-code-line,
html-rule and html-term. Headings are html-h1 to html-h6.
A page’s own styles
A page’s <style> blocks and style= attributes are applied to that page and
to nothing else in the window, and so are the bgcolor and <font color> of
mail written before CSS. A rule a mail writes cannot reach the application
round it or the mail beside it.
html-view bind="mail.body" link="mail.open" author-styles="adapted"
HtmlView.following(mail.body()).authorStyles(AuthorStyles.THEME_COLOURS);
What is read is the part that is safe and that the toolkit’s CSS has: colour,
the text’s size, weight, style, spacing, alignment, decoration and case, a
box’s padding, margin, border, corners and max-width, opacity,
visibility, and display: none, which is how a mail hides its preview line.
Nothing that fetches is read (url() included), nothing that moves a box out
of the page (position, transform, a negative margin), nothing that reads
or sets the theme (custom properties and var()), and no font-family, so a
mail reads in the application’s own face. @media and every other at-rule are
skipped.
Selectors are matched against the page as written, so ul > li, td a and
p:first-child mean what they say. :hover, :active and :focus apply as
the pointer and the keyboard move. A page’s rules win over the application’s
own sheets for the page’s elements; an application that has to insist writes
!important.
author-styles= decides what happens to the colours:
| Value | What the page looks like |
|---|---|
adapted | The default. A background the page paints is kept, and text on it reads: the page’s own colour when it reaches 4.5:1 against that background, dark or light ink when it does not. A text colour with no background of the page’s under it is the theme’s, because it would sit on the theme’s surface |
theme-colours | Sizes, spacing, boxes and borders as written, every colour the theme’s |
as-written | Exactly as written, for a surface the application knows to be white |
ignored | The application’s stylesheets alone, as a help page should be |
Inline styles follow the text run. Its background covers the glyph range on each line. Paragraph boxes support padding.
Keyboard
As markdown-view: Tab to each link, Space or Enter to press it,
Ctrl+A and Ctrl+C for the selection.
What it does not do
The document view renders a subset of HTML. It delegates links and images to the application. For a page that needs scripts, forms or navigation, use the web view.
Wrapping and hyphenation
Markdown and HTML shape adjacent text of the same style as a run, and lay
those runs out in a paragraph. The md-word and html-word classes style
the runs. Inline images sit on the baseline. A link can wrap over several
lines and stays one Tab stop.
.md-prose, .html-prose { text-align: justify }
Justification expands gaps between words on wrapped lines. The last line and the line before a hard break keep their natural spacing.
For automatic hyphenation, set the language and enable hyphens: auto.
<p lang="en" style="hyphens: auto">An introduction to internationalization.</p>
In Markdown, give markdown-view or an ancestor lang="en" and use
.md-prose { hyphens: auto } in the stylesheet. Automatic breaks use
bundled American English patterns for English locales with Latin script.
A displayed hyphen at a wrap does not change the text copied to the
clipboard. A link label with mixed explicit languages uses ordinary
wrapping and honours authored soft hyphens.
The default hyphens: manual uses explicit soft hyphens (U+00AD or
­ in HTML) in any language. Use hyphens: none to suppress them.
The web view
A real web page inside the window, drawn by the desktop’s own engine into a child window placed over the widget’s box. Java only: there is no markup name, because a page is a platform handle a document cannot describe.
import dev.goldberry.widgets.core.web.WebView;
import dev.goldberry.widgets.shell.web.WebPage;
new WebView(WebPage.of("https://goldberry.dev")).withAttributes(Attributes.NONE.id("page"));
A WebPage is a value: WebPage.of(url), WebPage.ofHtml(html) or
WebPage.blank(), with title, sized, debug for the engine’s inspector,
and on(name, callback) for a function the page’s own script can call. The
widget follows the page it is handed, so navigating is rebuilding with another
page. A callback’s return value resolves the page’s promise and an exception
rejects it.
var page = WebPage.ofHtml(DEMO)
.on("goldberrySays", arguments -> "\"Java heard you\"");
WebViews.open(host, page) opens a page in a window of its own instead, and
returns empty where no page can be opened.
Ask before offering one
The engine is the platform’s own, driven through a separate optional library, so the toolkit loads without it. Most machines cannot open a page, so an application asks first:
if (Goldberry.capabilities().contains(Capability.WEB_VIEW)) {
return new WebView(WebPage.of(HANDBOOK));
}
return new Button("Open the handbook", () -> Desktop.browse(HANDBOOK));
WebViews.isAvailable() is the same question.
| Platform | What the page is |
|---|---|
| X11, and XWayland | The engine’s window, reparented into this one |
| macOS | The engine’s view, a subview of the window’s content view |
| Windows | The engine’s child window |
| Wayland | Nothing. The widget refuses and says why |
Wayland refuses it
Embedding means putting the engine’s window inside the application’s. Wayland
does not allow a client to reparent a foreign surface, and no protocol proposes
it. On a Wayland session the widget opens nothing and paints a message saying
why, rather than dropping a loose window on the desktop.
An application that wants a page there can ask for the X11 driver with
-Dgoldberry.backend.videoDriver=x11, which runs the window under XWayland.
What a page cannot share the screen with
The page is a window above the frame, not a raster in it. Nothing painted can
cover it: a popover, a tooltip or a toast that overlaps the page is
invisible where they meet. A scroll does not clip it. opacity, transform
and the frost material do not reach it. A dialog
is the exception: while a modal is up the widget parks its page off the side of
the window and brings it back when the dialog closes. A page is also opened
parked and shown only once it reports itself loaded, with a spinner in its box
until then.
Input is the page’s. The window system delivers clicks and keys to the engine directly, and on macOS the backend drops key events while a page holds the keyboard. Under X11 a window keeps presenting through the GPU with a page in it. A page is taken down on the engine’s thread, and its context outlives the application’s exit.
Signing in through a page
Two things a sign-in needs from a page cannot come from the page’s own script. The engine hands them over instead:
- Where it is going.
onNavigate(Predicate<URI>)is asked before every navigation, a server’s redirect included. False cancels it, and the page stays on the document it had. An OAuth redirect to a custom scheme comes back this way, with no loopback server. - Its cookies, HttpOnly ones included.
cookies(URI)reads the engine’s jar for a URL. The answer is aCompletionStage<List<HttpCookie>>that completes on the UI thread.
private final WebViewController signIn = new WebViewController();
new WebView(WebPage.of(GRAFANA + "/login"))
.onNavigate(uri -> {
if ("myapp".equals(uri.getScheme())) {
finish(uri.getQuery());
return false;
}
if (uri.getPath().equals("/")) {
signIn.cookies(URI.create(GRAFANA)).thenAccept(this::keepSession);
}
return true;
})
.controller(signIn)
.withAttributes(Attributes.NONE.id("sign-in"));
A page opened with WebViews.open takes WebPage.onNavigate the same way and
answers cookies(URI) itself. The predicate runs inside the engine’s decision,
so it must answer at once, and one that throws lets the navigation go ahead.
The widget asks the predicate of the page value it has now, so a rebuild
with a new lambda needs no reload. A WebViewController is inert until its page
has opened, and asking it then gives a stage that has already failed.
| Platform | Cookies from | Navigations asked about |
|---|---|---|
| Linux | The engine’s cookie manager | Every frame’s: the engine does not say which frame |
| macOS | The engine’s cookie store, matched to the URL by the toolkit | The main frame’s |
| Windows | The engine’s cookie manager | The main frame’s |
On Linux and macOS every page in the process shares one cookie jar, so a session signed in to in one page can be read from any other.
A page can be given scripts that run before its own, on every navigation, which is where an embedding application defines the API its pages call. And the application can talk to the open page through the controller:
var page = WebPage.of(app.url()).initScript("window.Host = { version: 2 };").on("hostSend", this::received);
controller.postMessage("{\"type\":\"theme\",\"dark\":true}");
A page hears a posted message as a message event on its window, with the
JSON as event.data.
A sign-out deletes what the page signed in with: deleteCookies(url, name)
deletes the cookies the engine would send to url (all of them when name
is null), and clearCookies() empties the jar. Both complete on the UI thread.
On Linux and macOS every page shares one jar. WebViewSpec.userAgent(agent)
sets the user agent the page sends from its first request, and the
controller’s userAgent(agent) changes it later.
Styling
The widget builds a column with the class web-view, a stack with the
class web-stage, and a canvas with the class web-surface that carries the
id and sizes the page. All three default to flex-grow: 1, so a page fills the
box it is given. The page’s own document is not in the toolkit’s tree, so no
stylesheet or theme reaches it. An application that wants a page to follow the
desktop’s light or dark setting reads Host.systemTheme() and writes the CSS.
Keyboard
The page’s own. The toolkit forwards nothing.
Audio and video
Four widgets over one MediaPlayer: the picture, the controls, both together, and a compact player for sound.
By the end of this chapter you can open a file or a URL in a player, show it with its controls from markup or Java, switch tracks and subtitles, and know which codecs a build decodes.
The module
The widgets are in goldberry-media. Java demuxers read Matroska and WebM,
MP4, Ogg, FLAC, WAV and MP3 through MediaIO. The bundled decoders and pixel conversion
ship in libgoldberry-media, one library for each target. Add the
natives-<target> classifier for each platform your application supports.
Add the stylesheet beside the controls’ own:
var sheets = new ArrayList<>(Controls.stylesheets(theme));
sheets.add(MediaStyles.stylesheet());
The published natives decode royalty-free codecs only: VP8, VP9, AV1 and Theora for
video, and Opus, Vorbis, FLAC, MP3 and PCM for audio. MediaCapabilities.current()
answers what a build decodes and demuxes, read from the loaded libraries.
A player
A MediaPlayer is the application’s. The widgets show and drive it, and never
own it.
import dev.goldberry.media.MediaPlayer;
import dev.goldberry.media.io.Source;
var player = MediaPlayer.builder().build();
player.open(Source.of(Path.of("clip.webm")));
player.play();
open takes a Source.of(path) or a Source.of(uri). Every call returns at
once: the engine runs on its own threads and reports back as a PlayerStatus,
one immutable value with the state, the position, the duration, the tracks, the
volume, the rate and the buffered ranges. player.status() reads the latest and
player.onStatus(listener) hears each change. The transport is play, pause,
seek(position) or seek(position, SeekMode.KEYFRAME), setVolume,
setMuted, setRate from 0.25 to 4 with the pitch following, step(count)
for a picture at a time, and close. A seek on a source that cannot seek, or
a live one, is dropped and the stream plays on. PlayerStatus.seekable() says
which.
setLooping(true), or MediaPlayer.builder().looping(true), plays the source
over and over. The player never reaches ENDED, and there is no pause where the
source joins back onto its start. The engine reads the start again before the
end is heard. The sound and the pictures run on in time across the seam, and the
position is the time within the pass that is playing. A pass is as long as its
last picture. The sound is fitted to that length: trimmed where it runs over,
and padded with silence where it falls short. A source with no picture loops at
the end of its sound’s last packet, so an Opus track’s encoder padding, a few
milliseconds, is heard at the seam. A source that cannot seek, or a live one,
ends anyway.
MediaProbe.probe(source) says what a source holds without playing it. A video
track’s TrackParams.Video has its frameRate(), a FrameRate such as 60/1
or 30000/1001, and the Track has its frameCount() where the container
records one. MP4 does. Matroska and WebM do not, so for them the count is
frameRate.framesIn(duration).
A source’s chapters are on its MediaInfo: chapters() lists them in order,
each a Chapter with its start, its end and its title, and
chapterAt(position) is the one playing. They are read from Matroska’s
chapters, an MP4’s chapter track or chpl list, an MP3’s ID3 CHAP frames,
and the CHAPTER001= comments of Ogg and FLAC. nextChapter() seeks to the
next one’s start; previousChapter() seeks to the start of the one playing
once it has played three seconds, and to the one before it until then. Both
return false when there is nowhere to go.
In markup a player is a named object. The application registers it and a node
names it with player=:
var named = Named.strict().bind("video.player", player);
var inflater = Widgets.inflater(named, icons, model);
A node with no player to resolve against does not inflate, so the samples below
are fragments and the showcase’s video.kdl and audio.kdl are the complete
documents.
HDR and wide gamut. A picture in HDR (PQ, as HDR10 is, or HLG) or in BT.2020’s or P3’s primaries is tone-mapped to the window’s SDR as it is drawn, on the GPU and on the CPU alike: its light from the stream’s own transfer function, its colours into BT.709’s, its highlights rolled off from the brightness it was mastered to (1000 nits when it does not say) down to SDR’s white, with hue kept. What a stream says of its colour comes from the codec and the container both;
VideoPlanes.colour()hands it to a view that converts planes itself, andColorDescriptionis what a decoder an application brings reports.
Tracks, subtitles and the network
A source with two voices or two angles offers a track menu, and
player.selectTrack(track) switches over the same frame queue, so the old
picture stays up until the new track’s picture covers the position.
Text subtitles are read in Java from a SubRip, WebVTT, ASS or MP4 text track, or
from a SubRip or WebVTT file through player.loadSubtitles(source).
hideSubtitles() turns them off and currentSubtitles() is what shows at the
clock. The player does not read bitmap subtitles.
A URL is read through a cache and buffered to a high-water mark, which the
seek bar shades. Once the source is open, the cache reads up to half a minute
ahead at its bitrate when it has room. A live stream’s ICY title appears in
the player’s nowPlaying line. With no audio device, media plays silently.
Bringing a codec
H.264, HEVC, AAC, AC-3 and E-AC-3 are not in the published natives. They play
through the operating system’s own decoders, which are DecoderProviders
found by ServiceLoader and consulted before the built-in ones:
| Provider | Codecs | System |
|---|---|---|
videotoolbox, audiotoolbox | H.264, HEVC; AAC, AC-3, E-AC-3 | macOS |
gstreamer-video, gstreamer-audio | The same, with the decoders installed | Linux |
mediafoundation-video, mediafoundation-audio | The same | Windows. Set -Dgoldberry.media.mediaFoundation=false to disable |
vulkan-video | H.264, HEVC, VP9 and AV1 as supported by the driver | Supported Vulkan devices |
An application brings its own codec the same way: implement DecoderProvider
with name, supports(request) and open(request), and declare
provides dev.goldberry.media.codec.DecoderProvider with … in its module. A
provider for a patented codec holds the licence for it.
MediaPlayer.builder().decoderProviders(list) lists providers by hand, and
PlatformDecoders.providers() is the system’s set.
The probe names such a track’s pixel format even so: the published natives
neither decode nor parse H.264 or HEVC, so the name is read from the parameter
sets in the track’s avcC or hvcC record.
The bundled decoders run in software. setHardwareDecoding(HardwareDecoding.OFF)
asks system providers to use software and bypasses providers requiring hardware.
The setting applies from the next source opened and is passed to custom providers
in each DecoderRequest. To use an external decoder as a last resort, set
-Dgoldberry.media.ffmpeg=/absolute/path/to/ffmpeg to an executable installed on
the machine.
Nothing larger than 8K is decoded: no side longer than 8192 and no more pixels than 8192 × 4352, the largest picture AV1 and VP9 define. A source whose video states more, or whose decoder hands over more, fails with
InvalidDatanaming the size.PictureLimitholds the two numbers, and a provider an application brings can hold its decoder to them too.
A video sticker
A WebM sticker is a short VP9 video with an alpha channel: each picture’s alpha
travels beside it as a second VP9 stream, and the track says so with
AlphaMode. The built-in decoder decodes both, so the pictures are transparent
where the sticker is, and half transparent where it fades.
VideoAnimation plays one as a picture rather than as a player. It reads the
bytes from memory, decodes no sound, holds no thread, and is drawn by the same
AnimationView that plays a Lottie sticker:
var sticker = VideoAnimation.of(bytes);
return new AnimationView(sticker, "🎉");
The view plays it on the frame loop, loops it until loops(n) says otherwise,
stands on its first picture with autoplay(false) or when the user asks for
less movement, and draws it over whatever is beneath it. Each picture is
decoded when the frame asks for it, on the UI thread, which costs about a
millisecond and a half for a 512×512 sticker. close() frees the decoders, and
an animation nothing refers to frees them by itself.
A MediaPlayer plays the same file with its alpha too. video-view draws a
picture with alpha on the CPU, over its own background, which media.css makes
black: a stylesheet that wants the page to show through sets
background-color: transparent on it. The GPU’s video layer draws opaque
pictures only, and leaves these to the CPU.
media-player
A video-view with media-controls laid over its foot: the picture, the
transport, the error, the stream’s title and the subtitles in one box.

A media-player paused, with a subtitle track chosen.
media-player id="video-player" player="video.player" fit="contain"
import dev.goldberry.media.view.MediaPlayerView;
new MediaPlayerView(player);
new MediaPlayerView(player, Fit.COVER, Attributes.NONE.id("video-player"));
The controls hide while the player plays and the pointer rests, 2.5 seconds
after it last moved, and come back when it moves. A click on the picture plays
or pauses. A failure is shown over the picture in .media-error, and an H.264
file says which codecs it could not play. Subtitles are lines over the foot of
the picture, above the controls while they show and lower while they hide. F
asks the window to fill its display, and a copy of the player covers the window
with the class is-fullscreen.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
player | named MediaPlayer | required | The player to show and drive |
fit | contain, cover, fill, none | contain | How a picture fills a box of another shape, as on image |
id | string | none | The player’s id |
class | string | none | Classes on its box |
Children are refused.
Styling
The CSS type is media-player, a column with min-height and the backdrop
--gb-media-backdrop. Inside it are the video-view, the .media-overlay
column pinned to the bottom, media-controls in that, .media-error,
.media-now-playing, .media-subtitles and .media-subtitle. The state is on
the root as .is-idle, .is-opening, .is-buffering, .is-playing,
.is-paused, .is-ended or .is-error, with .is-scrubbing while the seek
bar is held, .is-pointer-idle while the controls hide, and .is-fullscreen on
the full-window copy. The tokens are --gb-media-*, and media.css fades the
overlay on .is-pointer-idle.
A source with chapters notches the seek bar where each starts, and
.media-chapter is the title of the one playing, after the elapsed time.
Keyboard
Once the player has focus: Space or K plays and pauses, Left and Right
seek five seconds, Up and Down change the volume by five percent, M mutes,
L loops the source and stops looping it, Home goes to the start, , and .
step a picture back and on, < and > slow down and speed up through 0.25 to
2, and F and Escape enter and leave fullscreen.
Page Up goes to the previous chapter and Page Down to the next.
video-view
A player’s pictures and nothing else: the surface for an application that draws its own controls or none.
video-view player="trailer" fit="cover"
import dev.goldberry.media.view.VideoView;
new VideoView(player);
new VideoView(player, Fit.COVER);
The view follows the player’s status. A picture a paused seek lands on is shown
when it is ready, and while the player plays it draws a new picture every frame.
With goldberry-gpu on the module path the pictures go through a GPU layer, and
a shader converts them from their planes with the stream’s matrix and range.
Without it, or where the layer cannot be placed, the view draws converted
pictures on the CPU.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
player | named MediaPlayer | required | The player to show |
fit | contain, cover, fill, none | contain | How the picture fills the box. The picture is centred |
id | string | none | The view’s id |
class | string | none | Classes on its box |
Children are refused.
Styling
The CSS type is video-view. It has no size of its own and grows into what it
is given, with flex-grow: 1 and --gb-media-backdrop where the picture does
not reach.
On the GPU, a picture’s planes are copied once: the video thread writes them straight into the view’s upload memory, and the window’s thread uploads them as they are, so a 4K picture costs the UI thread half a millisecond. This happens by itself for
video-view. An application that draws a player’s pictures withPictureRenderergets the same by offering the renderer’s memory:player.attachView(PictureForm.PLANES)and thensetPlaneStore(renderer.planeStore())on what it returns.
Keyboard
None of its own. Put a media-controls beside it.
A picture that does not come from a player, such as a call’s video decoded
by the application, is shown by PictureView over a PictureSource. A
PushedPictures takes pictures from any thread, and the view draws the newest
once a frame, as a video-view with the same styling.
var tile = new PushedPictures();
row.add(new PictureView(tile, Fit.COVER));
tile.push(new VideoPlanes(...)); // from the thread that decoded it
A pushed picture’s bytes must stay as they are until two more have been
pushed after it. A VideoPicture is drawn as it is. VideoPlanes are shown
by the GPU where the window has one, and converted to BGRA on the CPU where it
has not, which takes the module’s natives; a picture is converted once however
many frames draw it.
audio-player
Compact controls over a player: play and pause, the times, a seek bar, mute and volume, with the stream’s title above and an error below.

An audio-player over the same player.
audio-player id="audio-player" player="audio.player"
import dev.goldberry.media.view.AudioPlayer;
new AudioPlayer(player);
The seek bar is left out for a source that cannot seek, and a LIVE label
stands in its place for a stream. While playing, the widget reads the position
four times a second.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
player | named MediaPlayer | required | The player to show and drive |
id | string | none | The player’s id |
class | string | none | Classes on its box |
Children are refused.
Styling
The root carries the class audio-player, and its pieces media-play,
media-time, media-seek, media-live, media-rate, media-mute,
media-volume, media-now-playing and media-error. The state is on the root
as is-playing, is-paused, is-buffering, is-ended or is-error.
media-chapter shows the current chapter title when available.
Keyboard
As media-controls, without the picture keys.
Page Up goes to the previous chapter and Page Down to the next.
media-controls
The transport bar on its own, for an application that lays it out itself under a
video-view or drives a player it shows elsewhere.
column {
video-view player="trailer"
media-controls player="trailer"
}
import dev.goldberry.media.view.MediaControls;
new Column(List.of(new VideoView(player), new MediaControls(player)), Attributes.NONE);
Play and pause, the elapsed and remaining times, a seek bar that scrubs to keyframes while dragged and lands exactly on release, mute, volume, the rate when it is not 1, and the audio, video and subtitle menus where the source has a choice. All of it is built from the ordinary controls, so it takes the theme and the focus like any other.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
player | named MediaPlayer | required | The player to drive |
id | string | none | The bar’s id |
class | string | none | Classes on its box |
Children are refused.
Styling
The CSS type is media-controls, a row with --gb-media-gap. Its pieces carry
media-play, media-time, media-seek, media-live, media-rate,
media-loop, media-mute, media-volume, media-audio-track,
media-video-track, media-subtitles-menu and media-fullscreen. The
media-loop button shows only while the player loops, and pressing it stops
the loop. The state is on the bar as
is-playing, is-paused, is-buffering, is-ended or is-error, and
is-scrubbing while the seek bar is held.
media-chapter shows the current chapter title when available.
Keyboard
The bar is a focus stop. Space or K, Left and Right, Up and Down,
M, L, Home, , and ., and < and >, as on media-player. A key bubbles
to the bar from a control inside it that does not want it.
Page Up goes to the previous chapter and Page Down to the next.
Microphone
goldberry-mic records from the microphones there are, and works out what the
sound says: how loud it is, what its spectrum is, what its outline looks like.
It is an optional module with no native library of its own:
dependencies {
implementation("dev.goldberry:goldberry-mic")
}
Recording
try (var microphones = Microphones.open();
var recording = microphones.record(RecordingSpec.voice())) {
var meter = new LevelTracker();
recording.onSamples(meter);
...
}
Microphones.list() asks the system for the recording devices plugged in now,
and systemDefault() is the system’s choice: a recording from it follows the
user’s setting when it changes. A recording from one device of the list stays
on that device, and is Lost when it is unplugged.
RecordingSpec.voice() asks for 48 kHz mono in 10 ms blocks. The samples are
32-bit float, interleaved, whatever the device runs at; the conversion is done
before they arrive.
A recording hands each block to its onSamples listeners on a thread of its
own, in order. The block is borrowed: its samples are valid during the call,
and a listener that keeps them copies them. The same frames go into a buffer
read(FloatBuffer) takes from, for code with a thread of its own; what it does
not take within RecordingSpec.buffer() (two seconds by default) is dropped,
and droppedFrames() counts it.
| Status | Means |
|---|---|
Active | Recording |
Paused | Stopped by pause(); resume() starts it again |
Lost | The device went away or the system took it; final |
Closed | Closed; final |
onStatus tells a listener each change. onChange on Microphones tells one
about devices plugged in and taken away; both are heard while the
application’s window loop runs, on its thread. A program with no window lists
the devices again instead.
On macOS
macOS records for an application only once the user has allowed it, and asks
the first time a recording opens. The question quotes a sentence from the
application’s Info.plist:
<key>NSMicrophoneUsageDescription</key>
<string>Records your voice for voice messages.</string>
Without the key the system does not ask: it ends the process the first time
it records. The bundle is the application’s own. The toolkit’s Gradle plugin
writes none, so the key goes into whatever Info.plist the packaging writes;
jpackage takes a whole one from its --resource-dir. A program started
from a terminal has no bundle of its own, so macOS asks on the terminal’s
behalf and remembers the answer for the terminal.
A user who refused allows it again in System Settings, under Privacy & Security, then Microphone.
Levels, spectra and outlines
The analysis reads any SampleSource, a recording or a SyntheticSource, and
each tracker is itself a listener, fed on the source’s thread and read from
any other:
| Tracker | Reports |
|---|---|
LevelTracker | The last block’s Levels (peak and RMS) and a peak that holds for 1.5 s and then falls at 20 dB a second |
SpectrumAnalyzer | The Spectrum of the last size frames through a Hann window, in dBFS per bin, and bands(count, low, high) spaced in log frequency |
EnvelopeTracker | The Envelope of the last stretch heard: each bucket’s lowest and highest sample, oldest first |
A full-scale sine reads 0 dBFS at its peak, and its bin of the spectrum reads 0 dB too. Silence reads −120 dB rather than minus infinity.
The widgets
The three widgets read any SampleSource and draw what they hear. Each feeds
a tracker of its own while it is mounted and draws again at most once a frame,
however many blocks arrive; a widget shown again starts from silence. Their
sizes and colours are in mic.css, added beside the controls’ sheets:
var sheets = new ArrayList<>(Controls.stylesheets(Theme.NORD_DARK));
sheets.add(MicStyles.stylesheet());
In markup, source= names a source the application registered with the
document. A name nothing is bound to draws silence, so a preview of the
document shows the widget at rest.
| Token | Draws |
|---|---|
--gb-mic-track | A level meter’s track |
--gb-mic-level, --gb-mic-hot, --gb-mic-clip | A level bar below −6 dBFS, to −1 dBFS, and past it |
--gb-mic-hold | The held peak’s mark, until it clips |
--gb-mic-wave, --gb-mic-wave-ahead | A waveform’s played part, and a clip’s part not played yet |
--gb-mic-spectrum | A spectrum’s bars or line |
level-meter
How loud a source is, as a bar.
level-meter source="mic"
level-meter source="mic" orientation="vertical"
new LevelMeter(recording)
The last block’s RMS is the solid bar and its peak a fainter one past it. The loudest peak of the last moment is a mark that holds for 1.5 s and then falls at 20 dB a second. The scale runs 60 dB, from −60 dBFS to full scale; the bar turns to the hot colour at −6 dBFS and the clip colour at −1, and a held peak that reached −1 marks in the clip colour too.
| Attribute | Means |
|---|---|
source | What to measure |
orientation | horizontal (the default) fills left to right; vertical fills bottom to top, and adds the class vertical |
A meter is 8 pixels thick and at least 96 long; a vertical one is 96 tall.
waveform-view
The outline of the last few seconds a source said, scrolling in from the right.
waveform-view source="mic" seconds=5
new WaveformView(recording, Duration.ofSeconds(5))
| Attribute | Means |
|---|---|
source | What to draw |
seconds | How much of the past the view spans, 3 by default |
The window is cut into 256 buckets, each drawn from its lowest sample to its highest at full scale. What has not been heard yet is a flat line.
A recorded clip is drawn whole by the plot the view itself draws with, from the clip’s own envelope. A voice message, two fifths played, filling the height with its loudest moment:
var outline = Envelope.of(samples, channels, 48);
new WaveformPlot(outline, 0.4, true, Attributes.NONE)
An outline with a third as many buckets as the box is wide, or fewer, is drawn a bar a bucket with gaps between; a longer one is one continuous shape.
spectrum-view
What frequencies a source is made of, now.
spectrum-view source="mic"
spectrum-view source="mic" bands=48 shape="line"
new SpectrumView(recording, 48, SpectrumShape.LINE, Attributes.NONE)
| Attribute | Means |
|---|---|
source | What to analyse |
bands | How many bands, 32 by default, up to 1024 |
shape | bars (the default), or line: a line through the bands with the area beneath it shaded |
The spectrum is of the last 40 ms or so, through a Hann window, cut into bands spaced evenly in log frequency from 50 Hz to 16 kHz (or just under half the sample rate, where that is lower). Each band is as loud as its loudest bin, and the view is 90 dB tall: a full-scale sine reaches the top in its band.
Testing without a microphone
A SyntheticSource makes its samples from a Signal (silence, a tone, noise,
a clip, or a mix of them) and delivers them only when it is advanced, on the
thread that advances it:
var source = SyntheticSource.of(Signal.tone(440, 0.5));
var meter = new LevelTracker();
source.onSamples(meter);
source.advance(Duration.ofMillis(500));
assertEquals(-6.0, meter.reading().levels().peakDecibels(), 0.1);
Every signal is a function of the frame number, so the same frames come out however the time is cut up, and a picture of a meter is the same every run.
Camera
goldberry-camera lists the cameras there are and takes pictures from them.
A camera is a picture source, so it is drawn as any other is, and
camera-view adds what a camera needs on top: what to say while there is no
picture, and a mirror. It is an optional module with no native library of its
own, and it brings goldberry-media with it:
dependencies {
implementation("dev.goldberry:goldberry-camera")
}
Opening a camera
try (var cameras = Cameras.open();
var camera = cameras.open(CameraSpec.CALL)) {
window.show(new CameraView(camera));
...
}
Cameras.list() asks the system for the cameras plugged in now, each with
its name, where it faces, and the modes it offers. preferred() is the one to
open when the application has not chosen: the first facing the user, else the
first. onChange hears cameras plugged in and taken away while the
application’s window loop runs.
A camera opens in the mode nearest to what was asked. A rate slower than the one asked counts twice as much as a size away from it. Of two modes as near, an uncompressed one wins, then the larger, then the rate nearer the one asked.
Most USB cameras send their largest sizes and fastest rates only compressed,
as Motion JPEG. A camera opened in such a mode decodes each frame on its own
thread, which costs a few milliseconds a frame: about 5 at 1280×720 and 12 at
1920×1080. So a camera that sends 1280×720 at 30 only compressed, and
uncompressed only at 10, opens the compressed mode for CameraSpec.CALL, and
640×480 at 30 uncompressed for CameraSpec.PREVIEW. CameraInfo.formats()
lists every mode, and CameraFormat.compressed() says which need decoding.
A settings screen that lists the modes for a person to pick opens exactly the one picked:
var mode = camera.formats().get(picked);
var opened = cameras.open(camera, mode);
A mode the camera does not offer is refused with an
IllegalArgumentException.
Pictures are taken newest first, on a thread of the camera’s own: NV12 planes
from an uncompressed mode, BGRA pictures from a compressed one. A picture
stays as it is until two more have been shown after it, so a view that draws
slowly never holds the camera up. A compressed frame that arrives cut short or
corrupt is dropped while the camera goes on, and droppedFrames() counts it.
Frames that leave out their Huffman tables, as many USB cameras’ do, are given
JPEG’s standard ones.
On Linux the cameras are listed through PipeWire where it runs, which also
drives the laptop cameras only it can serve and lets two applications share a
camera, and through V4L2 otherwise. Setting SDL_CAMERA_DRIVER in the
environment (v4l2 or pipewire) picks one.
Cameras.driver() names the driver in use: pipewire or v4l2 on Linux,
mediafoundation on Windows, coremedia on macOS. Through PipeWire a camera
is named after PipeWire’s node, so a USB camera is listed as
C922 Pro Stream Webcam (V4L2). The suffix names the PipeWire plugin that
serves the camera, not the driver the application reaches it through.
| Status | Means |
|---|---|
Asking | The system is asking the user; no pictures yet |
Active | Taking pictures |
Denied | The user refused; final |
Lost | The camera was unplugged or stopped; final |
Closed | Closed; final |
On macOS
macOS lets an application use a camera only once the user has allowed it, and
asks the first time one opens. Until the user answers, the camera is
Asking and a camera-view says so; an answer makes it Active or Denied.
The question quotes a sentence from the application’s Info.plist:
<key>NSCameraUsageDescription</key>
<string>Shows your camera in calls.</string>
Without the key the system does not ask: it ends the process when the camera
opens. As with the microphone, the bundle is the application’s own: the
toolkit’s Gradle plugin writes none, and jpackage takes a whole
Info.plist from its --resource-dir. A program started from a terminal is
asked about on the terminal’s behalf. An application that records its calls’
sound as well needs both keys.
A user who refused allows it again in System Settings, under Privacy & Security, then Camera.
camera-view
A camera’s pictures, or a line saying why there are none.

The fallback while a camera source is unavailable.
camera-view camera="front" fit="cover"
camera-view camera="front" mirror="off"
new CameraView(camera, Fit.CONTAIN, Mirror.OFF, Attributes.NONE)
| Attribute | Means |
|---|---|
camera | The camera to show, a named object; a name nothing is bound to shows “No camera” |
fit | cover (the default), contain, fill or none, as video-view takes it |
mirror | auto (the default) mirrors unless the camera faces away; on; off |
While the camera is active its pictures are drawn as video-view draws a
player’s: on the GPU where the window has one, and converted on the CPU where
it has not. Otherwise the view says, in the middle, that it is waiting for
permission, that the camera is not allowed, that it stopped, that it is off,
or that there is no camera.
The mirror is the view’s. A person expects to see themselves as in a
mirror, and a desktop camera, which does not say where it faces, almost always
faces the user, so auto mirrors it. The camera’s own pictures, which a call
sends, stay as they were taken.
The view carries its camera’s state as a class, asking, active,
denied, lost, off or none, and mirrored when it mirrors, so a
stylesheet can dress each. camera.css sizes it at least 160 by 120, rounds
its corners and puts it on black:
| Token | Sets |
|---|---|
--gb-camera-backdrop | Behind the picture, and around a letterboxed one |
--gb-camera-message-color | The line shown instead of a picture |
--gb-camera-min-width, --gb-camera-min-height | The smallest the view is |
--gb-camera-radius | Its corners |
Testing without a camera
A SyntheticCamera paints a test card (colour bars over a grey ramp, with a
square crossing them) and takes a picture only when it is advanced, so a
picture of a camera-view is the same every run:
var camera = SyntheticCamera.of(640, 480);
camera.advance(Duration.ofMillis(500)); // fifteen pictures at 30 fps
SyntheticCamera.asking(…) starts it waiting, and approve(), deny() and
lose(reason) move it as a person or a cable would.
The GPU canvas
A canvas3d is a box the GPU draws into with an application's own renderer, and goldberry-gpu on the module path is what makes a window present through the GPU at all.
By the end of this chapter you can put a 3D view in a window, write the renderer
it draws with, decide whether it is drawn every frame or on demand, and read
from the log and from Window.presentation() whether a window went through the
GPU.
The showcase's GPU screen. The left cube spins on every frame, the right one turns when the slider moves.
What the module does to a window
The UI is painted on the CPU whatever the window presents through.
goldberry-gpu changes the last step. Put it on the module path and every
window presents its frame through the GPU: the frame’s damage is uploaded to a
texture and drawn onto the window’s swapchain, on Metal, Vulkan or Direct3D 12.
Where that cannot be done, with no device, a refused claim or a popup, the
window presents on the CPU exactly as it does without the module. The window
says which, once per change:
[GPU] "Goldberry — showcase on Linux / amd64" presents through the GPU (vulkan)
Window.presentation() answers the same thing in code, as a Presentation.Gpu
with the driver’s name or a Presentation.Cpu with the reason, and
Window.onPresentationChange(handler) hears each change.
On macOS an embedded WKWebView sits above the window’s Metal view, so the window
keeps presenting through Metal while the page is open.
Two system properties set the policy:
| Property | Values | What it does |
|---|---|---|
goldberry.gpu | auto, off | off never touches the GPU. Every window stays on the CPU and a canvas3d shows a notice instead of a picture |
goldberry.gpu.composite | always, auto, never | always composites every window from its first frame. auto composites a window only while it shows GPU layers. never composites none and reads every layer back |
What the GPU path adds is GPU layers: opaque rectangles in the frame’s paint
order that the GPU fills and the UI is composited over. A window that cannot
composite reads a layer back into its frame instead, so the same tree draws
the same picture both ways. canvas3d is one layer. A video-view is the
other, when goldberry-media and goldberry-gpu are both present.
canvas3d
A 3D view: a leaf sized by its stylesheet, whose picture an application’s
Canvas3dRenderer draws on the window’s device.
canvas3d renderer="cube" continuous=#true depth="d16"
import dev.goldberry.gpu.view.Canvas3d;
new Canvas3d(Cube.spinning()).continuous(true).depth(Canvas3d.Depth.D16);
new Canvas3d(viewer).revision(revision).withAttributes(Attributes.NONE.id("model"));
In markup the renderer is a named object the application registered, resolved
by renderer=. A node with no renderer to resolve against does not inflate, so
the sample above is a fragment.
When it is drawn. A continuous canvas is drawn on every frame and keeps the
window drawing frames while it is shown: a spinning model, a game. Otherwise it
is drawn once, then again when its size changes and when its revision does. A
model viewer that redraws when its camera moves rebuilds the widget with the
next revision, and between those the last picture is shown again and nothing is
rendered.
Where there is no GPU. With goldberry.gpu=off, with no device, or inside
an opacity group, the box is filled with --gb-canvas3d-unavailable and a
notice says why.
The renderer
public interface Canvas3dRenderer {
void init(GpuDevice device);
default void resize(PhysicalSize size) {}
void render(GpuFrame frame, Canvas3dTarget target);
void dispose();
}
init is called once, before the first render, with the window’s device.
resize follows it and runs again whenever the canvas’s size in physical pixels
changes. render runs for each frame the canvas is drawn. dispose runs when
the canvas leaves the tree, or before init on a new device. Every call is on
the UI thread, which is the device’s. The canvas keeps the renderer while it is
mounted and makes a new layer when the widget is rebuilt with another renderer
or depth.
The showcase’s cube is a renderer written as an application writes one:
public final class Cube implements Canvas3dRenderer {
@Override
public void init(GpuDevice device) {
vertex = device.createShader(ShaderCode.load(ShaderStage.VERTEX, "cube.vert", 0, 1, Cube::resource));
fragment = device.createShader(ShaderCode.load(ShaderStage.FRAGMENT, "cube.frag", 0, 0, Cube::resource));
pipeline = device.createPipeline(PipelineSpec.builder(vertex, fragment, TextureFormat.B8G8R8A8_UNORM)
.vertexBuffer(...)
.build());
mesh = device.createBuffer(BufferUsage.VERTEX, STRIDE * VERTICES);
}
@Override
public void render(GpuFrame frame, Canvas3dTarget target) {
frame.renderPass(target.colour(), Load.clear(0, 0, 0, 1), target.clearDepth(), pass -> {
pass.bindPipeline(pipeline);
pass.bindVertexBuffer(0, mesh);
pass.pushVertexUniforms(0, transform(target.aspect(), target.seconds()));
pass.draw(VERTICES);
});
}
@Override
public void dispose() {
pipeline.close();
mesh.close();
}
}
GpuDevice makes textures, buffers, samplers, shaders and pipelines from
records, and beginFrame() starts a GpuFrame. A frame is a command buffer
recorded pass by pass: copyPass uploads into buffers and textures, and
renderPass draws into a target, with a Load for what happens first and an
optional DepthTarget. A pass is open only while its body runs. The toolkit
submits the canvas’s frame, and a frame closed without submit is discarded.
A RenderPass binds a pipeline, vertex and index buffers and fragment samplers,
pushes uniforms, and calls draw or drawIndexed. Misuse the API can see, a
closed resource or a draw with nothing bound, throws in Java before the driver
is reached. Everything is confined to the device’s thread.
The Canvas3dTarget is a colour texture at the canvas’s size in physical
pixels, a depth texture beside it when the canvas asked for one, and nanos,
the frame’s time since the canvas was first drawn. target.aspect() is what a
projection is made with, target.seconds() is what an animation is a function
of, and target.clearDepth() is the depth target cleared to the far plane. The
renderer covers every pixel of the colour texture, and its picture is opaque,
as every GPU layer is.
Shaders
Shaders are written in HLSL and compiled offline. The sources live in
src/main/shaders/*.hlsl, and ./gradlew :gpu:compileShaders compiles them to
SPIR-V, DXIL and MSL, then writes the bytecode as resources beside the code that
loads them.
It is a task run on purpose, not part of build, because its compilers come
with the Vulkan SDK, which is too much to ask of every build. The task also
compiles the showcase’s own cube.vert.hlsl and cube.frag.hlsl.
ShaderCode.load(stage, name, samplers, uniformBuffers, lookup) reads
name.spv, name.dxil and name.msl through the caller’s own resource lookup,
and device.createShader(code) picks the format the device takes.
Attributes
| Attribute | Type | Default | What it does |
|---|---|---|---|
renderer | named Canvas3dRenderer | required | What draws the picture |
render-scale | number | 1 | Fraction of the box at which the renderer draws |
upscale | linear or fsr1 | linear | Filter used to scale the result to the box |
sharpness | number, 0 to 1 | 0.87 | FSR 1 sharpening |
continuous | boolean | #false | Drawn on every frame, and keeps the window drawing them |
depth | none, d16, d32 | none | The depth target the renderer draws with. Anything else is refused |
revision | number | 0 | A value other than the last one drawn has an on-demand canvas drawn again |
id | string | none | The canvas’s id |
class | string | none | Classes on its box |
Children are refused.
Styling
The CSS type is canvas3d, sized like an image or a canvas by width and
height. It is a GPU layer, so it is opaque, what is painted after it is over
it, and a clip cuts it to a rectangle. Without a GPU the box is filled with
--gb-canvas3d-unavailable, and the notice is a message with the class
canvas3d-notice inside a stack with the class canvas3d-stage.
and a clip cuts it to a rectangle. Inside a box that clips to a
border-radius, the clip is that box’s bounding rectangle, and whatever is
painted over the corners rounds it.
Keyboard
None. A canvas3d is not focusable.
The texture model
A TextureSpec is a 2D texture of a format and a size, with three counts that
default to one: layers, mipLevels and samples. TextureSpec.sampled,
renderTarget, depth and sampledDepth make the common shapes;
TextureSpec.array(format, width, height, layers, usages) makes an array, and
withMipLevels, withMipChain, withLayers, withSamples and withUsages
vary any spec.
var faceUsages = EnumSet.of(TextureUsage.COLOR_TARGET, TextureUsage.SAMPLER);
var faces = device.createTexture(TextureSpec.array(TextureFormat.B8G8R8A8_UNORM, 256, 358, 64, faceUsages));
var board = device.createTexture(TextureSpec.renderTarget(TextureFormat.R8G8B8A8_UNORM, 2048, 2048).withMipChain());
var shadow = device.createTexture(TextureSpec.sampledDepth(TextureFormat.D32_FLOAT, 2048, 2048));
var scene = device.createTexture(TextureSpec.renderTarget(TextureFormat.R16G16B16A16_FLOAT, w, h));
Layers and levels are addressed, not made. A GpuTexture stands for its
level 0 of layer 0 wherever a RenderTarget is taken. texture.layer(i),
texture.level(n) and texture.view(level, layer) name one level of one
layer as a TextureView, which frame.renderPass draws into, copy.upload
fills, and frame.readback reads. A shader samples the array as one
Texture2DArray in HLSL and picks the layer by index, so a card-face cache
is one texture and every card one instance of one draw.
Mip levels are uploaded one at a time through a view, or generated:
frame.generateMipmaps(texture) fills every level below the first from the
one above it, outside any pass, for a texture made with
TextureSpec.renderTarget, because the drivers blit through a colour target. A
SamplerSpec reads level 0 alone unless it has a mip filter:
SamplerSpec.trilinear(), or withMipFilter(Filter.LINEAR), reads the level
the footprint calls for.
Float colour formats. R16G16B16A16_FLOAT, R32_FLOAT and
R11G11B10_UFLOAT are colour targets a Load.clear takes past 1 and below
0, and read back as their bytes: halves, which Float.float16ToFloat decodes,
or floats. The canvas’s own target stays B8G8R8A8_UNORM; a renderer draws
its scene in HDR and tonemaps into the canvas in its last pass. Whether a
device renders into R11G11B10_UFLOAT is a question for
device.supports(format, usages).
A depth texture can be sampled. TextureSpec.sampledDepth makes a depth
target a later pass reads: a shadow map. It is drawn in a render pass with no
colour target, frame.renderPass(DepthTarget.clear(shadow), body), with a
pipeline made by PipelineSpec.depthOnly(vertex, fragment, DepthTest.less(format))
whose fragment shader outputs nothing. The two kinds of pipeline and pass do
not cross: a colour pipeline in a depth-only pass, or the reverse, is refused
in Java. The scene then binds the shadow map like any texture, through a
sampler with a comparison, SamplerSpec.linear().withCompare(CompareOp.LESS_OR_EQUAL),
for HLSL’s SampleCmp. A sampled depth texture reads back as floats or shorts.
One made with TextureSpec.depth alone is never read back.
Samples. A spec with samples of 2, 4 or 8 is a multisampled render
target: one layer, one level, never sampled itself. A pipeline made with
.samples(4) draws into it, in a pass that names where the samples go:
frame.renderPass(msaa, load, resolved.level(0), body) resolves them into a
single-sampled texture of the same format and size when the pass ends, and
the multisampled texture’s own contents are then undefined. A depth target in
such a pass has the same sample count. The sampled picture is the resolved
one.
Which counts a device has for a format is asked before the target is made:
device.supportsSamples(format, samples) is true for 1 and the driver’s
answer for 2, 4 and 8, and device.maxSamples(format, limit) is the highest
supported count at most limit. A renderer with an anti-aliasing setting
asks for both of its targets’ formats and takes the smaller answer:
var samples = Math.min(
device.maxSamples(TextureFormat.B8G8R8A8_UNORM, settings.msaa()),
device.maxSamples(TextureFormat.D32_FLOAT, settings.msaa())
);
A sampler per slot. pass.bindFragmentSamplers(sampler, textures...)
reads every texture of a shader with one sampler. A shader that reads its
textures differently binds a SamplerBinding per slot, slot 0 first:
pass.bindFragmentSamplers(List.of(
new SamplerBinding(faces, trilinear),
new SamplerBinding(shadow, shadowCompare)
));
The shader declares the slots in the same order, each texture with its own
sampler: a SamplerState for the first and a SamplerComparisonState for
the second, read with Sample and SampleCmp. bindVertexSamplers takes
the same list for a vertex shader.
Uploads
Upload memory written elsewhere.
GpuDevice.createUploadBuffermakes memory a producer on another thread fills while it is mapped, andCopyPass.upload(texture, buffer, offset, rowBytes)records the upload from it with no copy. Mapping, unmapping and uploading are the device’s thread’s; only the bytes may be written elsewhere, and unmapping ends the mapping for every thread. Rows padded to 256 bytes upload in one copy whereGpuDevice.uploadsPaddedRows()is true, Vulkan and Direct3D 12; Metal reads an upload’s rows as packed, so there padded rows are recorded one at a time and packed rows are the ones to stage.
Compute and storage
A compute shader is <name>.comp.hlsl, compiled by the same task, and loaded
by ComputeCode.load with a builder that says its workgroup and what it
binds. device.createComputePipeline(code) makes the pipeline, and a frame
runs it in a compute pass that names what it writes:
var declared = ComputeCode.builder(64, 1, 1).readOnlyStorageBuffers(1).readWriteStorageBuffers(1).uniformBuffers(1);
var code = ComputeCode.load("particles.comp", declared, Vfx.class::getResourceAsStream);
var simulate = device.createComputePipeline(code);
var usages = EnumSet.of(BufferUsage.COMPUTE_STORAGE_WRITE, BufferUsage.GRAPHICS_STORAGE_READ);
var particles = device.createBuffer(usages, COUNT * STRIDE);
frame.computePass(particles, pass -> {
pass.bindPipeline(simulate);
pass.bindStorageBuffers(emitters);
pass.pushUniforms(0, dt, 0, 0, 0);
pass.dispatch(COUNT / 64);
});
frame.renderPass(target.colour(), Load.keep(), pass -> {
pass.bindPipeline(sprites);
pass.bindVertexStorageBuffers(particles);
pass.draw(6, COUNT, 0, 0);
});
What a pass writes is said when it begins, frame.computePass(written, body)
or the form with lists of buffers and texture views, so the driver orders the
writes against the draws around them. What it reads is bound after the
pipeline with bindStorageBuffers and bindStorageTextures. A buffer or
texture carries the usages of every stage that touches it: COMPUTE_STORAGE_WRITE
for the pass, GRAPHICS_STORAGE_READ for the draw that reads it through
bindVertexStorageBuffers, bindFragmentStorageBuffers or
bindFragmentStorageTextures, COMPUTE_STORAGE_READ for a later pass. A
graphics shader that reads storage says so when loaded,
ShaderCode.builder(stage).storageBuffers(n), and a vertex shader that
samples a texture, a height map, binds it with bindVertexSamplers.
the windowing backend’s HLSL bindings for compute: samplers, then read-only storage textures and
buffers, as t[n] in space 0; read-write storage textures and buffers as
u[n] in space 1; uniform blocks as b[n] in space 2. For a vertex shader,
storage comes after its samplers in space 0; for a fragment shader, in space
2 after its samplers.
BlendMode.ADDITIVE sums the output onto the target, colour and alpha alike:
particles, glows and light. The counts and the usages are checked in Java
before the backend sees a dispatch or a draw, as everything in this API is.
Indirect draws, stencil and copies
A draw can take its counts from a buffer rather than from its arguments, so
that a compute pass decides what is drawn: the instances that survived
culling, or the particles still alive, with nothing read back. The buffer is
made with BufferUsage.INDIRECT, and with COMPUTE_STORAGE_WRITE too when a
compute pass writes it. Its commands are the records in
dev.goldberry.gpu.indirect: a DrawCommand is four words (vertices,
instances, first vertex, first instance), an IndexedDrawCommand five, and a
DispatchCommand three.
var usages = EnumSet.of(BufferUsage.COMPUTE_STORAGE_WRITE, BufferUsage.INDIRECT);
var commands = device.createBuffer(usages, DrawCommand.BYTES);
frame.computePass(commands, pass -> {
pass.bindPipeline(cull);
pass.bindStorageBuffers(instances);
pass.dispatch(INSTANCES / 64);
});
frame.renderPass(target, Load.clear(0, 0, 0, 1), depth, pass -> {
pass.bindPipeline(lit);
pass.bindVertexBuffer(0, cube);
pass.drawIndirect(commands, 0, 1);
});
drawIndirect(buffer, offset, count) draws count commands that lie one
after another from offset, and drawIndexedIndirect does the same from the
bound index buffer. ComputePass.dispatchIndirect(buffer, offset) reads its
workgroups the same way. A command with zero vertices or zero workgroups does
nothing, which is what a culling pass writes when it culls everything. From
Java, IndirectCommand.pack(list) lays the commands out to upload. The offset
is a whole word, and a command that runs past the buffer’s end is refused.
A stencil test masks where a pipeline draws. It needs a depth format with a
stencil, D24_UNORM_S8_UINT or D32_FLOAT_S8_UINT. Apple’s GPUs have only
the second, so ask device.supports(format, usages) first. One pipeline
marks the pixels with the pass’s reference, and the next draws only where
the mark is:
var stencil = TextureFormat.D32_FLOAT_S8_UINT;
var depthStencil = device.createTexture(TextureSpec.depth(stencil, width, height));
var mark = device.createPipeline(PipelineSpec.builder(vertex, flat, format).depthTest(DepthTest.off(stencil)).stencilTest(StencilTest.replace()).build());
var through = device.createPipeline(PipelineSpec.builder(vertex, lit, format).depthTest(DepthTest.less(stencil)).stencilTest(StencilTest.equal()).build());
frame.renderPass(target, Load.clear(0, 0, 0, 1), DepthTarget.clear(depthStencil, 1, 0), pass -> {
pass.setStencilReference(1);
pass.bindPipeline(mark);
drawPortal(pass);
pass.bindPipeline(through);
drawFarRoom(pass);
});
StencilTest.notEqual() draws everywhere but the mark, as an outline around
a selection does. DepthTest.off(format) passes every fragment and writes no
depth, for a pipeline that tests stencil alone. A DepthTarget clears the
stencil with the depth, to the value its fourth component gives, and keeps it
at the end of the pass.
BlendMode.CONSTANT mixes the output into the target by the pass’s blend
constants, src × c + dst × (1 − c) channel by channel: a cross-fade, or a
tint, changed per draw with pass.setBlendConstants(r, g, b, a) and no
second pipeline.
A copy pass also copies on the GPU. copy.copy(source, destination) copies a
whole texture into one of its size and format, or a whole buffer into one of
its size. The longer forms copy a box of texels from one level and layer to
another, or a range of bytes, in whole words, between two buffers or two parts
of one that do not overlap. Last frame’s picture for a motion blur, a
history buffer, or the output of a compute pass moved into a buffer of
another usage are all copies.
A compute shader samples textures through pass.bindSamplers(sampler, textures...), as many as ComputeCode.builder(...).samplers(n) declares, in
t[n] and s[n] of space 0 before its read-only storage. A vertex shader
reads storage textures, texel by texel, through bindVertexStorageTextures:
a height field that a compute pass wrote, displacing a terrain. Such a
texture is made with GRAPHICS_STORAGE_READ and not SAMPLER. the backend takes a
texture as one or the other, and TextureSpec refuses both.
device.adapter() names the GPU and its driver in the system’s words, for a
settings screen or a log. device.waitForIdle() waits until everything
submitted has finished. texture.setDebugName(name) and
buffer.setDebugName(name) are what RenderDoc, PIX and Xcode show the
resource as.
What a device can do
device.features() answers the questions an options screen asks before it
offers a choice: the colour and depth sample counts (colorSampleCounts(),
ascending from 1 and not always every one, since some devices have 4 and 8 but
no 2), the depth formats with a stencil (stencilFormat() picks the smaller
one the device has), the block-compressed formats it samples, whether it
renders half-float targets, and the adapter’s name. It is asked once and kept.
var features = device.features();
var antiAliasing = features.colorSampleCounts();
var outlines = features.stencilFormat().isPresent();
Ray tracing is asked separately, with RayTracer.availability(), because it
runs on a device of its own that is only looked for when something asks.
Rendering offscreen
A test of a scene with a canvas3d in it opens an OffscreenGpu and hands
its surface to Offscreen:
try (var gpu = OffscreenGpu.open()) {
var picture = Offscreen.of(1600, 900).gpu(gpu.surface()).render(new Board(state));
GoldenImage.assertMatches("board", picture);
}
The surface is the read-back kind a window that presents on the CPU has: each
layer the frame places is rendered on the device, downloaded, and drawn into
the picture, so the picture holds the canvas’s pixels as a window would show
them, and a golden compares them. The device is made on the calling thread,
and the renderer’s init, render and dispose run on it as they would in a
window. Closing the OffscreenGpu closes the device and everything left on
it. Where no window has started the windowing backend’s video, the offscreen GPU does, under the
driver goldberry.gpu.videoDriver names, the windowing backend’s default, or offscreen when
the default cannot start on a machine with no display. It quits what it
started when closed. With no device at all, open throws with the driver’s
reason, rather than rendering the notice.
strip(...) and session(...) show GPU layers through the same surface,
in every frame they hand out, so a test that clicks the board and moves the
clock compares pictures with the canvas in them:
try (var gpu = OffscreenGpu.open();
var session = Offscreen.of(1600, 900).gpu(gpu.surface()).session(new Board(state))) {
session.click("pass");
session.advance(Duration.ofSeconds(1));
GoldenImage.assertMatches("board-after-pass", session.frame());
}
A running window’s picture is window.capture(): the last frame as the
screen shows it, GPU layers and all, composited again into a texture and read
back where the window is composited, and the window surface’s pixels where it
presents on the CPU. The launcher writes it for a run that paints a set number
of frames: --frames=N --capture=PATH writes the last frame as a PNG. The
flags are listed under Measuring.
OffscreenGpu.open(GpuPower.HIGH) prefers the discrete GPU on a machine with
two, and gpu.adapter().name() says which one the driver gave.
Ray tracing
dev.goldberry.gpu.raytrace traces rays through a scene of triangle meshes,
and hands back what each pixel’s ray hit and whether the light reaches it. It
traces in one of two tiers, behind one API that answers alike:
- In software, on the canvas’s own device, any GPU it has: the scene is a hierarchy of boxes built on the CPU, and compute shaders walk it.
- In hardware, on a GPU whose driver has ray tracing. The windowing layer’s GPU has none, so this tier runs on a Vulkan device of its own beside it, and its answers come back through memory for a renderer to upload into a texture or a buffer of the canvas’s device.
Asking first. RayTracer.open(device, mode) opens a tracer on the
canvas’s device, which a renderer has from init. RayTracingMode.SOFTWARE
traces in software; HARDWARE in hardware, or throws with a sentence that
says why there is none — no Vulkan, or each device and what it lacks; AUTO
in hardware where its device is a GPU, and in software otherwise; OFF opens
nothing. RayTracer.availability(device, mode) answers which without opening
anything: RayTracing.Software or RayTracing.Hardware, each naming its
device, or RayTracing.Unavailable with the sentence. A settings screen shows
that sentence beside its switch, and tracer.device() says which tier a
tracer got. RayTracer.availability() is the hardware tier’s answer alone,
for a screen with no device to hand. The system property
goldberry.raytracing=off, software or hardware overrides what an
application asks, for the process, and goldberry.raytracing.device=<part of a name> picks the hardware tier’s device where there are several.
The scene. A TriangleMesh is positions and indices. An Instance places
a mesh with a Transform and gives it an id, which is what a hit reports, and
a mask. SceneGeometry.of(instances…) is the scene, and tracer.build(scene)
builds it into a RayScene: one structure for each distinct mesh, shared by
every instance of it, and one over the instances. scene.update(geometry) places other instances of the same
meshes — moved, renumbered, more or fewer — and rebuilds that last structure
alone, which is what a frame of a moving scene costs. A mesh the scene was not
built with, or one whose triangles changed, is a new scene.
scene.structureBytes() is the GPU memory it holds.
try (var tracer = RayTracer.open(device, RayTracingMode.AUTO).orElseThrow()) {
var cube = TriangleMesh.of(positions, indices);
var ground = Instance.of(plane, Transform.IDENTITY, 1);
var box = Instance.of(cube, Transform.translation(new Vector3(0, 0.5f, 0)), 2);
try (var scene = tracer.build(SceneGeometry.of(ground, box))) {
var camera = Camera.lookingAt(new Vector3(0, 6, 8), Vector3.ZERO, 50);
var request = TraceRequest.of(camera, 640, 360).withShadowsToward(sun);
var shadows = tracer.traceShadows(scene, request);
frame.copyPass(pass -> pass.upload(shadowTexture, shadows.pixels()));
scene.update(SceneGeometry.of(ground, box.withTransform(next)));
}
}
The rays. A TraceRequest sends one ray through the centre of each pixel
of a Camera’s picture, rows from the top, and, with withShadowsToward, a
second ray from each hit toward a directional light. A camera a renderer
rasterizes with gives rays through the same pixel centres, so the traced
picture lines up with the drawn one.
The hits. Hits holds a 24-byte record a pixel: the instance’s id (or
Hits.MISS), the triangle’s index in its mesh, the distance along the ray,
the barycentrics of the triangle’s second and third vertex, and whether the
light reaches the point. hits.hit(x, y) reads one as a Hit.
hits.shadowMask() is a ShadowMask; hits.distances(miss) is an
R32_FLOAT picture; hits.records() is the records themselves, for a storage
buffer a shader reads.
The shadows alone. tracer.traceShadows(scene, request) traces the same
rays and answers with a ShadowMask, made on the GPU: a byte a pixel, 255 in
the light (or where the ray hit nothing) and 0 in shadow, rows with no
padding. mask.pixels() uploads into an R8_UNORM texture, which a shader
samples as 1 and 0; mask.isLit(x, y) reads one pixel. A request without a
light is refused.
The lighting. tracer.traceLighting(scene, LightingRequest.of(request))
traces, from each primary hit, the shadow ray, rays around the hit for ambient
occlusion and a ray off it for its reflection, and answers with a Lighting
of two planes laid out for two textures. lighting.shading() is
R8G8B8A8_UNORM: red 255 in the light and 0 in shadow, green how open the
hit is (the share of its occlusion rays that escaped), blue how lit the
surface its reflection sees is, alpha 255 where the primary ray hit anything.
lighting.reflectedIds() is R32_FLOAT: the id of the instance the
reflection saw, or -1, from which a shader looks up what that surface looks
like. withOcclusion(rays, radius) sets how many occlusion rays a hit takes,
up to 64, and how far they look; 0 turns occlusion off. withReflections(false)
leaves reflections out. The occlusion rays follow a fixed sequence for each
pixel, so a still scene lights the same on every trace.
var lighting = tracer.traceLighting(scene, LightingRequest.of(request).withOcclusion(12, 1.4f));
frame.copyPass(pass -> pass.upload(shadingTexture, lighting.shading()));
The lighting into textures. A renderer that only samples the lighting
can leave it on the GPU. LightingTargets.create(device, width, height) makes
the two textures, sampled and written by compute, and
tracer.traceLighting(frame, scene, request, targets) records the lighting
into them in the frame, before the passes that sample them. In software the
shaders write the textures where they are, and nothing crosses to the CPU; in
hardware the tracer traces at once and the frame uploads the planes. Either
way the textures hold what traceLighting(scene, request) returns.
targets = LightingTargets.create(device, size.width(), size.height());
tracer.traceLighting(frame, scene, LightingRequest.of(request), targets);
What it costs. A trace that returns its answers returns when the GPU is
done, with its output copied back: the rays, then the copy. traceShadows
copies a byte a pixel, traceLighting eight and trace 24, so a renderer
that wants the light alone asks for the mask, and one that samples it traces
into textures. The lighting traces up to four rays a pixel and its occlusion
rays besides. The software tier walks its boxes in compute shaders, which on
a GPU with ray-tracing hardware is slower than the hardware tier and on one
without is not far from it. Tracing a smaller picture than the canvas and
sampling it scaled is the usual way to keep either within a frame.
Where it runs. The software tier runs wherever a canvas3d has a GPU:
Metal, Direct3D 12 and Vulkan. The hardware tier runs on Linux and Windows, on
a GPU whose Vulkan driver has the ray-tracing pipeline extensions — NVIDIA
from the GTX 16 series, AMD from RDNA 2, Intel Arc — whichever API the window
draws with, and on the CPU through Mesa’s software Vulkan where it runs at
256-bit vectors, as x86 machines do. An arm64 machine’s software Vulkan runs at
128 bits, crashes building a scene there, and is refused, so availability()
says so. macOS has no hardware tier.
In the Showcase’s Ray tracing and settings card, choose Auto to use the available tracing backend or GPU compute to run on the canvas’s device. On Metal, both choices run the compute shaders. Hardware requests the Vulkan ray-tracing backend.
Render scale and upscaling
A canvas3d can be drawn at a scale of its box and brought up to it: the
setting a game’s options screen calls render scale. Fewer pixels drawn is
frame rate bought for sharpness.
canvas3d renderer="cube" continuous=#true depth="d16" render-scale=0.67 upscale="fsr1"
var canvas = new Canvas3d(cube).continuous(true).renderScale(RenderScale.of(0.67).withFilter(UpscaleFilter.FSR1));
The renderer draws into a colour texture at the scaled size, and is told that
size by resize. target.size() and target.aspect() are the scaled
texture’s, which keeps the box’s aspect. The canvas then brings the picture up
to the box with one of two filters:
linear, the default: each pixel interpolated from the four nearest. One pass, soft edges.fsr1: AMD FidelityFX Super Resolution 1. EASU upscales along the edges it finds and keeps them sharp, then RCAS sharpens bysharpness=, from 0 (not at all) to 1 (the most). The default, 0.87, is what AMD recommends. Its quality modes are render scales: ultra quality 0.77, quality 0.67, balanced 0.59, performance 0.5.
A scale above 1 draws more pixels than the box has and brings them down linearly, whichever filter is named. At exactly 1 the renderer draws straight into the box and nothing else runs. A new scale draws an on-demand canvas again; the renderer keeps what it made and is resized.
A renderer that draws into textures of its own can upscale one the same way,
with an Upscaler made on its device in init:
upscaler.upscale(frame, small, target, UpscaleFilter.FSR1, RenderScale.DEFAULT_SHARPNESS);
FSR 1 expects a picture whose values are what the display shows, as a
B8G8R8A8_UNORM target holds them, and it leaves alpha opaque.
| Attribute | Type | Default | What it does |
|---|---|---|---|
render-scale | number, 0.5 to 2 | 1 | The size drawn at over the box’s size, per axis. Anything outside is refused |
upscale | linear, fsr1 | linear | How the picture is brought to the box. Anything else is refused |
sharpness | number, 0 to 1 | 0.87 | How much fsr1 sharpens; linear ignores it |
Raster textures
A RasterTexture is a texture kept in step with a raster the toolkit’s
painter draws: a board’s tiles, a chart, a sheet of labels, drawn by a
Canvas3dRenderer like any other texture. It owns the texture, the raster
and what has been painted since the last upload.
tile = RasterTexture.create(device, new PhysicalSize(256, 256));
tile.paint(List.of(PhysicalRect.of(0, 0, 64, 64)), frame -> drawSquare(frame));
frame.copyPass(tile::upload);
frame.copyPass(copy -> copy.copy(tile.texture().view(0, 0), 0, 0, target.colour().view(0, 0), x, y, 256, 256));
What is painted is what goes up. paint(regions, painter) runs the
painter once per region, clipped to it, and remembers the regions;
upload(copy) copies exactly those into the texture and forgets them. A new
raster is transparent and damaged whole, so its first upload fills the
texture. paint(regions, scale, painter) draws at a scale, so a painter can
work in units of its own whatever the tile’s size in pixels. damage() says
what the next upload copies.
Where the raster lives. On a device whose upload memory reads like
ordinary memory, the raster is painted in that memory, and an upload is a copy
the GPU makes out of it, with nothing copied on the CPU. Elsewhere the raster
is ordinary memory and an upload stages its damage, as CopyPass.upload
does. inPlace() says which. The device decides once, at start-up, by timing
a paint in each; goldberry.gpu.inPlace=on or off decides instead, and
RasterTexture.staged(device, size) always stages.
A paint waits for the frame of the last upload. Painted in place, pixels
the GPU is still copying must not change, so paint waits for that frame to
have run, which it has, in all but a GPU-bound frame, by the time the next
paint comes. Before the frame is submitted, a paint does not wait; the frame
may then copy what was painted since, and the next upload copies it either
way. A frame discarded with an upload in it loses that damage.
One thread, the device’s. Close a raster texture once the frame of its last upload has been submitted or discarded; closing waits for that frame and releases the texture with it.
A composited window paints in place too
The same memory serves the window. Where the device’s check says so, a
composited window lends the frame loop a frame in upload memory to paint into,
and its present copies the damage straight out of it; the UI frame is no
longer copied on the CPU at all. The hud’s upload reading is that copy’s
recording. Nothing changes for an application, and goldberry.gpu.inPlace=off
puts every window back on the staged path.
What it costs
The figures are for Metal on an M1 Pro, except where another driver is named. Creating the device costs about 20 ms at the first frame there, and 190 to 320 ms on NVIDIA’s Vulkan driver on Linux. A whole 2560 by 1600 frame costs 1.1 ms of CPU to composite against 2.65 ms for the window-surface present of the same frame, and a minute of 4K60 VP9 through a GPU layer shows all 3600 pictures where CPU present drops 1581.
A device lost mid-render shows black and does not fall back.
What a frame costs
A native window is up in a tenth of a second, a settled frame costs microseconds, and this page says where the rest of the time goes.
Read this page to know which numbers to expect from a Goldberry window and what each one measures. The three chapters after it say how to start fast, how to keep a frame cheap, and how to measure your own application rather than trust these figures.
The table below says what each number measures, and how.
| Number | What it measures | Method |
|---|---|---|
| 519 ms, 116 ms | The showcase’s native image, from exec to the first frame, and the moment the window is open | median of 7 runs, timed from exec |
| 1980 ms, 1340 ms | The showcase on the JVM, cold and with an AOT cache | median of 5 runs |
| 3.13 ms, 4.28 ms | A 960×640 frame with text, paced to the display | median and 95th percentile |
| 2.3 ms | A 3840×2160 paint in PaintBenchmark | four paint workers, against 6.0 ms on one thread |
| 117 µs | One small box changed at 960×640, repainted inside its damage | against 367 µs for a full repaint |
| 9.1 µs | Layout and the walk on a showcase-shaped tree when nothing changed | the retained tree, against 190 µs rebuilt every frame |
The frame loop
One UI thread runs the loop. Paint workers rasterize the bands. This is the pipeline, in the order a frame runs it:
input events → dispatch (hit-test on render tree)
→ rebuild dirty widgets → diff → update elements/render objects
→ style resolution (invalidated nodes) → layout (incremental)
→ paint recording (dirty layers only) → raster (banded)
→ present(buffer, damage) / GPU composite
Three trees take part. Widgets are immutable records that describe. Elements persist and hold state. Render objects own the layout nodes and are kept between frames, so a frame diffs a new description against a retained tree rather than building one. The architecture overview has the full picture.
Where the time goes at 960×640
Everything before rasterization is a rounding error. Rasterization and present are the frame.
| Stage | Cost | Note |
|---|---|---|
| Everything but rasterization, nothing changed | 3.5 µs | against 354 µs with nothing retained or cached |
| Rasterization on one thread | about 320 µs | the whole frame, with the rasterizer pinned to one thread |
| Paint in a live window, four workers | 2.146 ms | against 2.856 ms synchronous |
| Present, unpaced | about 6.4 ms | 4.8 ms of it blocks on the swapchain and 43 µs is the toolkit’s own code |
| Present, paced to the display | 1.20 ms | paint falls to 1.61 ms beside it |
Read the paint row with care. The same scene paints in 0.34 ms in a benchmark
loop and in 2.15 ms in a running window, because present leaves the next
paint’s caches cold. Only a figure from a live window says what a frame costs.
Measuring explains the gap.
The three chapters
Starting fast
How long a user waits depends on how you launch, and this chapter says what each launch costs and what to keep off the path to the first frame.
By the end of this chapter you can read the start-up timeline your own application prints, choose a launch mode with its number in front of you, train an AOT cache for the JVM, and keep your own work out of the first frame.
From exec to the first frame
The user waits for the process, not for the toolkit. So the clock starts at
exec, before any Java runs. The showcase on Linux with an NVIDIA GPU,
opening an X11 window and painting three frames:
| Launch | First frame, median | Range |
|---|---|---|
| JVM, cold | 1980 ms | 1948–2187 ms, 5 runs |
| JVM, JDK 25 AOT cache | 1340 ms | 1220–1406 ms, 5 runs |
| Native image, GPU on | 519 ms | 491–557 ms, 7 runs |
| Native image, GPU off | 365 ms | 351–460 ms, 7 runs |
A native image is what a release of the showcase ships, and it is the fastest of the four. On the JVM, most of the two seconds cold is spent before the toolkit’s first line and in building the showcase’s first frame. The AOT cache takes a third off that.
What the toolkit does in its time
A native run, phase by phase. The first column is time since exec. A
duration in parentheses is how long that one phase took:
70.1ms runtime starting (about 50 ms of it an mDNS host lookup)
86.6ms SDL video subsystem up (14.1ms)
113.1ms libgoldberry ABI 17 verified (26 ms of loading the web engine before it)
116.2ms window "Goldberry — showcase" open
365.3ms GPU device created (190.1ms on NVIDIA's driver)
511.0ms first frame presented
The window is open at 116.2 ms. Creating the GPU device takes 190.1 ms of
what follows, and the first frame comes after it. Three things in that
listing are not the toolkit’s own work: a host-name lookup before main,
the platform’s web engine loaded to answer a capability question, and the driver’s device
creation.
The same timeline on the JVM, under gradle run:
start-up timeline (866.6ms to here):
533.8ms +533.8ms runtime starting
559.6ms +25.8ms libgoldberry mapped (1.9ms)
722.6ms +162.9ms SDL video subsystem up (99.2ms)
728.0ms +5.4ms backend ready (185.5ms)
742.9ms +12.9ms SDL window 4 created
749.5ms +6.6ms window "Goldberry — showcase" open
866.6ms +117.1ms first frame presented
The first row is the JVM and Gradle’s launcher. Everything after it is the toolkit, and the deltas sum to about 330 ms: the library is mapped in under 2 ms, the windowing layer’s video subsystem takes 99 ms, and the first frame 117 ms.
The TRACE timeline and how to read it
Goldberry records a mark at each phase whether or not anybody listens, and
prints the table once, after the first frame reaches the screen. The
showcase’s logback.xml reads one property for the level:
./gradlew run -Dgoldberry.log.level=TRACE
In your own application set the dev.goldberry logger to trace in whatever
SLF4J binding you ship. The logging chapter has the
configuration.
Read the table as deltas. The second column is what each phase cost since the
one before it, and that is the column to look at when a start is slow. The
first row is what the runtime spent before Goldberry’s first line, and it is
printed on purpose: leaving it out would flatter the number by the amount
nobody can change. Startup.logModules() prints which Goldberry modules the
JVM resolved, which is the first thing to check when a widget package seems
to be missing.
Four rules shape the timeline:
- Timed from process start. On Linux the zero comes from the kernel’s own
clock through
/proc, becauseProcessHandle’s instant is up to a second late there. - Recorded always, reported at trace. A mark costs a timestamp and a queue append.
- Summarised once, after the first frame. A second window is not a second start-up.
- Capped at 256 marks, so a mark left in a loop costs a counter and nothing else.
The JDK 25 AOT cache
On the JVM the single largest saving is a cache the application trains for itself. JEP 483, JEP 514 and JEP 515 together let the JDK load classes pre-linked and keep the profiles of hot methods.
Run the application once with the cache output flag, and walk through the screens a user opens first.
Launch it with the cache flag from then on. Classes arrive loaded and linked, and the hot methods are already profiled.
Rebuild the cache when the JDK build or the module path changes. A stale cache is a warning at every launch.
# Training run: open the screens a user sees first, then quit.
java -XX:AOTCacheOutput=app.aot --module-path lib -m my.app
# Every launch after it.
java -XX:AOTCache=app.aot --module-path lib -m my.app
The cache is 37 MB and belongs to the application. It is specific to the JDK build and the module path and it is trained on your screens, which is why the toolkit documents it and does not ship one. The Starting fast section of Applications says the same in fewer words.
The native image, and why it is fast
A GraalVM native image has no JVM to start and no classes to load, so the executable reaches its first frame after the toolkit’s own work. The first native application chapter walks the build. The command is one Gradle task:
./gradlew :example:nativeImage -Pgraalvm.home=/path/to/graalvm
./example/build/native/goldberry-showcase-linux-x64
One flag decides whether the image is fast once it is running. GraalVM’s FFM downcalls are not optimised, so Goldberry links every downcall handle while the image is built and holds it as a constant. Sixty frames of the showcase, headless:
| 60 frames | Per frame | |
|---|---|---|
Without the --initialize-at-build-time lines | 2.55 s | 42.5 ms |
| With them | 0.061 s | 1.0 ms |
The image builds and paints correctly either way, so only the frame time shows the difference. Native image explains the mechanism.
The GPU device at the first frame
With goldberry-gpu on the module path every window presents through the GPU
by default. The device is created at the first frame, and what it costs is
the driver’s to decide:
| Machine | Device creation | Driver |
|---|---|---|
| M1 Pro, macOS | 19.5–21.3 ms at the first frame | Metal |
| NVIDIA, Linux | 190.1 ms, a quarter of a native start | Vulkan |
The measured alternative is to keep every window on the CPU:
./example/build/native/goldberry-showcase-linux-x64 -Dgoldberry.gpu=off
With the NVIDIA GPU that takes the native first frame from 519 ms to 365 ms.
An application that shows no canvas3d and no video loses nothing by it, and
the GPU chapter says what the path adds.
What an application keeps out of start
The toolkit’s part of a start is fixed. Yours is not, and two habits keep it small.
Open what has to be closed in start, not in a build. A widget is a value
that is rebuilt and thrown away, so an Icon built inside build() is parsed
from the bundled set and scaled to its size on every rebuild.
Application.start runs once on the UI thread before the first frame and
before root(), and that is where an icon, a font source or an image
belongs. Fonts open lazily: a face
is parsed the first time something asks for it, so an application that never
draws code text never pays for JetBrains Mono.
public final class Notes implements Application {
private Icon save;
@Override
public void start(Host host) {
save = Icon.bundled("save", Icons.SLOT); // once, before the first frame
host.shortcut(Mod.CTRL.and(Key.S), model::save);
}
@Override
public Widget root() {
return new Button("Save", model::save).withIcon(save); // the same value every build
}
}
Do slow work with Goldberry.async. It runs the work off the UI thread and
delivers the result on it, so the callback may touch a window with no hand-off
to write. A file read, a network call or a database query in start holds
the first frame for exactly as long as it takes.
@Override
public void start(Host host) {
Goldberry.async(() -> Files.readString(path))
.thenAccept(text -> model.setNote(text)); // on the UI thread
}
Tip
Measure before guessing. The JVM timeline above shows the video subsystem at 99 ms and the four-megabyte native library at under 2 ms, which is the opposite of what most people would guess.
Keeping frames cheap
The toolkit retains, invalidates, culls and paces so that a settled frame costs microseconds, and ten habits keep an application from undoing it.
By the end of this chapter you know which costs the toolkit removes from a frame, and the handful of choices that are yours: how you rebuild, what you transition, when you restyle, how you show a long list, and what the GPU and the native image change.
What the toolkit does for you
Each row is one mechanism and the number it moves. Nothing here needs a call from an application.
| Mechanism | What it does | Scene | Measured |
|---|---|---|---|
| Retained render tree | Render objects keep their layout nodes between frames and are reconciled against each frame’s description. Every write to a layout node is guarded by a comparison, because the layout engine dirties a node when a style is set, not when it differs | Layout and walk at 960×640 | 9.1 µs retained and 7.2 µs with a fresh box tree every frame, against 190 µs rebuilt every frame |
| Cascade invalidation | A node’s resolved style is cached on its element and checked by identity against the resolver and the inherited style. Invalidation is a subtree | Frame CPU before rasterization | 3.5 µs, against 354 µs with nothing retained or cached |
| A rebuild is not a restyle | An identical widget stops the walk. A re-description that keeps type, id and classes keeps its subtree’s styles | A wheel notch on the icon sheet | 4 elements re-resolved against 1556, and 4.2 ms of cascade against 66.6 |
| Damage | A changed node damages where it was and where it is. The frame is painted only inside that union where the backend promises to keep last frame’s pixels | One small box changed | 117 µs inside the damage, against 367 µs for a full repaint |
| Layers | A translucent group is rasterized once at full strength, untransformed, and its alpha and matrix go on the blit. A group that only fades or moves keeps its raster | A frame of a fade | 199 µs with the raster reused, against 554 µs rebuilt |
| Culling | Each render object carries the ink its subtree draws. A subtree whose ink cannot touch the clip is neither drawn nor walked | The icon sheet, 1544 tiles with forty visible | a settled frame 9.0 ms against 22.2, the raster 4.4 ms against 18.0 |
| Banded raster | The rasterizer splits a frame into bands and up to four workers rasterize them on any surface over 400×300 | A live 960×640 frame, and a 3840×2160 paint | 2.146 ms with four workers against 2.856 ms synchronous, and 2.3 ms against 6.0 ms |
| Pacing to the display | The windowing layer is asked to hold each present until vertical blank. Where that is ignored, the loop paces itself to the rate read off the window’s display | Present and paint in a live window | present 1.20 ms against 5.51, paint 1.61 ms against 2.25, and 165 ms of each second in the frame path instead of 862 |
| Idle loop | The loop parks until an event or a frame request. A static window costs nothing and nothing polls | A repaint request | wakes the loop once, through a pushed event |
| Deep trees | A node copies the custom-property map only when it declares one | First-frame resolve at element depth 101 | 1168 µs, against 2651 µs with the map copied at every node |
Two numbers on that table are worth reading twice. The damage saving is 3.1× for a change covering 0.23% of the window, because the clip saves rasterization and the walk visits every box regardless. And the retained tree costs the same with a fresh box tree every frame as with nothing changed, which is the row a real application lives on.
What an application must do
Rebuild cheaply
A widget is a value. Return a new tree from build() as often as you like,
because reconciling a fresh description against the retained tree costs
7.2 µs on a showcase-shaped screen. What is not free is anything a build
creates that has to be parsed, shaped or decoded. An Icon is parsed from
the bundled set and scaled to its size when it is built, a Font is one face
opened and kept, and an Image is decoded once into pixels it owns. Build
each in Application.start and keep it in a field. The
start-up chapter
shows the shape.
A model write is cheap too. A field bound ahead of time costs 2.5 ns to write with no listeners and 12.9 ns with one, and each write asks for one frame. Set a field, and the toolkit rebuilds.
Transition the properties that can be transitioned
Transitions are over a closed list: opacity, background-color,
border-color, box-shadow, color and transform. A layout
property never transitions, and a declaration naming one is refused with a
warning rather than ignored:
card { transition: box-shadow 160ms ease-out } /* interpolates every component */
card { transition: width 160ms } /* refused, with a warning in the log */
Why: an animated value lives in an overlay applied at paint and is never
written back into computed style, so the cascade and the animation cannot
fight. Width would mean a layout pass per frame, which is the one cost the
retained tree exists to avoid. Animate a size with transform instead.
Restyle for a theme, rebuild for everything else
A change to a model field asks for a frame. A change to a field declared
@Bind(restyle = true) drops every resolved style first. Declare it on the two
values a rule depends on, a theme and a density, and on nothing else:
@Model
public final class Settings {
@Bind(value = "app.theme", restyle = true) String theme = "nord-dark";
@Bind("app.note") String note = "";
}
Why: a restyle re-resolves every element in the window, which is the 66.6 ms cascade in the table above. A rebuild without a restyle re-resolves only the nodes whose selectors can have changed.
Virtualize a long list
A list or a table with thousands of rows builds only the rows its viewport
can see once it knows how tall a row is. The height can come from the
stylesheet’s --gb-list-row-height, read when the list is built:
ListView.of(names).virtualized() // the stylesheet's row height
ListView.of(names).virtualized(32) // a stated one
Table takes its rowHeight as a component, and zero builds every row. A
list whose rows vary in height must not virtualize, because the arithmetic is
index times height. A masonry cannot virtualize, which is why the icon sheet
relies on culling instead. The
collections chapter has both widgets.
Edit a large note in a text-area
A text-area shapes a line at a time and draws the rows on screen, so a
keystroke costs the same in a 500 kB note as in a 2 kB one. Medians per
keystroke, with the whole note shaped and with one line:
| Note | Whole note shaped | A line at a time |
|---|---|---|
| 2 kB | 4.63 ms | 4.92 ms |
| 50 kB | 20.47 ms | 4.10 ms |
| 500 kB | 207.39 ms | 4.36 ms |
A keystroke into the 500 kB note shapes 2 021 characters against 1 941 for the
2 kB one. A text widget shapes its whole paragraph, which is right for a
label and wrong for a document. A markdown-view bound to the same note
keeps the blocks nobody typed in. A 50 kB preview costs 16.83 ms a keystroke,
against 24.14 ms with every block rebuilt, and a 500 kB preview costs more
than 100 ms.
Ask for a frame only while something moves
The frame loop is idle when no animation is active. WidgetRenderer.isAnimating()
answers whether anything in the last rendered tree is moving, and an
application that drives its own loop asks for the next frame only then:
window.onPaint(frame -> {
BoxPainter.paint(frame, renderer.render(tree));
if (renderer.isAnimating()) {
window.repaint();
}
});
Why: a request wakes the loop and paints a frame whether or not a pixel changes, and sixty of them a second is a fan running for nothing. An application on the launcher gets this for free: a model write asks for a frame and a settled tree asks for none.
Know that opacity on a group costs a layer
A node with opacity below one and children is rasterized into a layer of
its own and composited once. That is what makes
opacity mean what CSS means where two children overlap, and it costs an
allocation and a blit. A translucent leaf keeps the cheap path on purpose. So
fade a panel, and do not fade every label in it separately.
Move things with transform
A transform is applied to the blit, so a group that only moves keeps its raster at 199 µs a frame instead of 554. Scrolling is a transform on one box, and the thousand boxes under it are skipped at the first rectangle that held, so a scroll re-measures nothing. Prefer a transform to a changed position or size whenever the thing moving is the same thing.
Use the GPU path where it helps
With goldberry-gpu on the module path a window presents its CPU-painted
frame through the GPU, and falls back to the CPU wherever it cannot.
Painting itself does not change. What changes is present, and video:
| Through the GPU | Through the window surface | Scene | |
|---|---|---|---|
| Paint mean | 3.67 ms | 5.34 ms | the showcase on Metal, 240 frames |
| First frame on screen | 1016.9 ms | 1013.4 ms | the showcase on Metal |
| Pictures shown | 3600 of 3600 | 2018 of 3598 | one minute of 4K60 VP9 |
| UI thread per picture shown | 2.8 ms | 17.6 ms | the same minute of 4K60 VP9 |
It helps a window that shows video, a canvas3d, or a large surface. It costs
the device at the first frame, 20 ms on Metal and 190 ms on NVIDIA’s Vulkan
driver, and -Dgoldberry.gpu=off keeps every window on the CPU. The
GPU chapter covers the widgets built on it.
Keep a downcall handle a constant in a native image
This one is for anyone binding a native function of their own. In a native
image a MethodHandle to a foreign function is a direct call only when it is
a static final read by the method that invokes it. Twenty million calls:
| Handle | JVM | Native image |
|---|---|---|
| Bound to its address, built at run time | 10 ns | 4560 ns |
| Unbound, built at run time | 10 ns | 4500 ns |
| Unbound, built at image build time | 10 ns | 10 ns |
Passing the constant into a helper as an argument costs 810 ns a call against 8.9 ns when the helper names the field itself, and an instance field measures 4540 ns. For the toolkit’s own bindings the difference is a showcase frame at 42.5 ms or at 1.0 ms, and Native image says which flag makes the difference.
Warning
An image with the wrong handle shape builds, runs and paints correctly. It is only forty times slower. Measure the frame, because nothing else will tell you.
The Measuring chapter says how to take your own numbers.
Measuring
A trace line per frame, a resize run that reports what it cost, benchmarks that are never a gate, and the flags that change what you measure.
By the end of this chapter you can read where a slow frame went, run the showcase under load and get one line that says what it cost, run every benchmark in the repository, and tell a benchmark’s number from a frame’s.
Per-frame timings at TRACE
Every frame logs its stages at trace. The showcase reads the level from one
property, and an application of your own sets the dev.goldberry logger to
trace in its SLF4J binding. The logging chapter has
the configuration.
./gradlew run -Dgoldberry.log.level=TRACE
The window’s line splits the frame into the buffer, the paint and the present, and paint into three parts, because the split says where a frame’s time goes:
frame <size> in <total>us: buffer <n>, paint <n> (begin <n>, draw <n>, end <n>), present <n>
begin attaches the context, draw is the painter’s own work, and end
waits for the paint workers. During a resize this line is the difference
between “the toolkit is slow” and “the platform is”.
The launcher adds a second line per frame that did something, split by the
stages of the widget pipeline. It is a system property rather than a log
level, because a diagnostic that cost an isTraceEnabled() per element per
frame would be measuring itself:
./gradlew run -Dgoldberry.trace.frames=true # frames that did something
./gradlew run -Dgoldberry.trace.frames=all # and the quiet ones
A frame whose cascade is slow per element reads:
frame 268 | build 0.010 style 8.636 layout 1.115 raster 1.304 ms
| elements 125, built 0, resolved 3, invalidated 1
| cascade 5.133 identity 0.956 motion 0.176 boxes 1.467
| text 17 cached, 6 shaped | damage 3
The counts beside the timings are the point. resolved 3 beside
style 8.636 is a cascade that is slow per element rather than one running
too often. A frame that is slow for a reason the timings cannot show is
explained by a count and not a duration: a style cache missing on every
element, or a click invalidating the whole tree, shows in the counts first.
Tip
The showcase has a HUD on
Ctrl+Fthat shows the same stages over the last sixty frames. Switch it on during a drag or a resize, when there is something to watch.
The showcase under load
The launcher accepts these flags and leaves every other argument to the application:
| Flag | What it does |
|---|---|
--frames=N | Paints N frames and exits |
--size=WxH | Opens the window at that size |
--resize=WxH | Walks the window a pixel a frame on each axis from its opening size to WxH and back, for as long as the run lasts |
--late-budget=N | Past N missed refreshes the launcher exits non-zero after shutdown, with the summary in the message |
A drag is a resize event per pointer motion, and that is the load a frame loop has to be measured under. A jump from one size to another is one reallocation and says nothing. The walk steps between frames, because a resize asked for from inside a painter changes the size under the frame being painted on every driver where a window resize is synchronous.
./example/build/native/goldberry-showcase-linux-x64 --frames=300 --resize=1580x1100
After the window closes the launcher logs one line, in Locale.ROOT so a
script can grep it:
frames: 300 frame(s) painted, 2 late; paint mean 1.31 ms, worst 8.90 ms; display 60.0 Hz
A display that reports no refresh rate shows as display 0.0 Hz, and “late”
then counts missed ticks of the pacer’s own timer. --late-budget is for a run
against a real display, which is where it means something.
Under Gradle the same run is ./gradlew run -Pgoldberry.example.frames=300,
and -Pgoldberry.backend.videoDriver=dummy keeps it off the real compositor.
Use the Gradle property rather than an environment variable, because a JavaExec fork inherits the daemon’s environment and not the
shell’s.
./goldberry-showcase-macos-aarch64 -Dgoldberry.startup.log.level=TRACE --frames=1
The timeline measures from process start to the first successful presentation. The macOS Showcase workflow includes it in the job summary.
Every frame, and the hitch
host.window().onFrame(frame -> …) hears every frame the window presents,
with its interval, its paint and stages, the refreshes it was late by, and on
a composited window its upload, acquire, submit and GPU layers. The listener
is handed the same object every frame, so listening costs nothing; keep one
with frame.copy().
window.onFrame(frame -> {
if (frame.intervalNanos() > 25_000_000) {
hitches.add(frame.copy());
}
});
frames.percentile(FrameStage.INTERVAL, 99) is the hitch a mean smooths
away, over the last sixty frames; percentile(FrameStage.PAINT, 50) is the
median paint. frames.layers() is what the GPU layers took to render
again, a canvas3d’s renderer recording its passes, apart from the
compositor’s own work.
The benchmark lane
A benchmark is a JUnit class under a module’s src/benchmark/java, and a
probe is a main beside it. ./gradlew benchmark runs every module’s
benchmarks, ./gradlew :widgets:benchmark one module’s, and check only
compiles them, so a benchmark that stops building fails on the commit that
broke it. They print their measurements and assert almost nothing,
because a timing assertion on a shared machine fails for reasons that have
nothing to do with the code.
They run one module at a time, whatever org.gradle.parallel says: every
benchmark task holds a shared build service with one slot. Two benchmarks
measured together measure each other, and a table taken beside a compiler is a
table of the compiler.
The inventory:
| Benchmark | Module | What it prices |
|---|---|---|
PaintBenchmark | :core | Painting a frame, and what the paint workers do to it |
TextBenchmark | :core | The text path: shaping, the paragraph cache, wrapping |
EditorKeystrokeBenchmark | :core | One keystroke into a 2 kB, a 50 kB and a 500 kB editor document |
FrameBenchmark | :widgets | A frame of a real widget tree, split by stage |
DeepTreeStyleBenchmark | :widgets | A 50-, 100- and 200-deep tree’s first frame and a middle ancestor’s hover, against the catalog’s sheets |
TextAreaFrameBenchmark | :widgets | One keystroke into a 2 kB, a 50 kB and a 500 kB note |
AxisLabellingBenchmark | :widgets | One numeric and one time-axis labelling, against a third of a frame |
MarkdownFrameBenchmark | :html | The same keystroke through a markdown-view, with the Markdown parser timed alone as a control row |
PlaneCopyBenchmark | :media | Copying and converting a 4K picture’s planes, against a picture’s time at 60 fps |
ReadPacketBenchmark | :media | One read_packet through the upcall stub against a direct call |
BindingSchemeBenchmark | :weaver | The two ways of binding a model, against each other |
BindingCodegenBenchmark | :weaver | Whether a jar should generate its binding rather than reflect |
DowncallBenchmark | :natives | One foreign call, held both ways |
ModifierPollBenchmark | :natives | The per-event modifier poll |
BindingBenchmark | :example | A Property per value against plain bound fields, and the showcase’s own names |
FrameBudgetBenchmark | :example | A frame of the real application, stage by stage and resolution by resolution |
And the probes, each run by a task of its own and read by a person, because they open a real window or device and the numbers are the machine’s:
| Probe | Task | What it measures |
|---|---|---|
GpuPresentProbe | :natives:gpuPresentProbe | Window-surface and composited present, and the swapchain switch |
GpuVideoProbe | :gpu:gpuVideoProbe | A composited frame with a 4K video layer under the UI |
VideoLayerProbe | :gpu:videoLayerProbe | The video layer’s upload of a new 4K picture each frame |
VideoPresentProbe | :media:videoPresentProbe | A minute of 4K60 video in a window: dropped pictures and CPU time |
Run one by name:
./gradlew :widgets:benchmark --tests '*TextAreaFrameBenchmark*'
./gradlew :example:benchmark --tests '*FrameBudgetBenchmark*' -i
./gradlew benchmark --tests '*Text*'
The last names benchmarks in two modules, and every other module’s task is given the same filter and finds nothing, which is not a failure.
MarkdownFrameBenchmark carries a control row, the Markdown parser timed on its own. Two
runs whose parse times disagree are two runs on two differently loaded
machines, and their other rows should not be compared.
JMH on :core
The hot seams that are pure logic have JMH, as a src/jmh source set with
forks, warm-up and a blackhole, so a number is not the JIT specialising a loop
away. CascadeBenchmark resolves one element against a six-rule sheet at
0.476 ± 0.067 µs/op.
./gradlew :core:jmh
That is what JMH adds over the benchmark task, and the only reason to run
both.
A cost is guarded by a count, never by a clock
A test under check that asserts a millisecond fails for what else the
machine was doing. FrameBudgetBenchmark’s style row reads 3.6 ms on an idle
machine and 20 ms under a parallel Gradle, on the same commit, which is why it
is a benchmark and its table is read rather than asserted.
What check is owed instead is a count. A keystroke into a 500 kB note shapes
and draws about what a keystroke into a 2 kB note does, 2 021 characters
against 1 941, and a test under check asserts that count rather than a
time. A markdown-view is held the same way, in blocks built, blocks kept
and paragraphs shaped. A count says the same thing under a parallel build and
a millisecond does not.
Important
A benchmark’s scaffolding is under
check. The two namesBindingBenchmarkresolves are also resolved by a test on every build.
The flags
Each is a system property on the Java command line, so -D on a plain
launch, and on ./gradlew run the showcase forwards the ones below.
| Property | Values | What it changes | Default |
|---|---|---|---|
goldberry.paint.threads | 0 for synchronous painting, N to pin the worker count | The paint workers | up to four on any surface over 400×300 |
goldberry.frame.rate | N overrides the display’s rate, 0 measures the unthrottled loop | The pacer, which 0 switches off | the rate read off the window’s display |
goldberry.backend.vsync | false | Stops asking the windowing layer to hold each present until vertical blank | true |
goldberry.gpu | off | Keeps every window on the CPU | on, when goldberry-gpu is on the module path |
goldberry.gpu.composite | always, auto, never | Whether a window is composited always, only while it shows GPU content, or not at all | always |
goldberry.backend.videoDriver | dummy | The windowing layer’s video driver, for a headless run that touches no compositor | the windowing layer’s own choice, X11 first on Linux |
goldberry.trace.frames | true, all | The launcher’s per-frame stage line, with its counts | off |
goldberry.log.native | false | Gives the native libraries their stderr back, past the SLF4J bridge | true, the bridge installed |
goldberry.log.level | TRACE | The showcase’s logback.xml level for dev.goldberry. Your application names its own | DEBUG |
A tuning flag that is not understood is taken as the default. A typo should not stop a window opening.
| Showcase argument | Effect |
|---|---|
--capture=PATH | Writes the last frame of a bounded run as a PNG |
--capture-at=N | writes frame N to the --capture= file and keeps running |
--verify-native-libraries | Exercises the packaged native libraries and exits |
A benchmark is not a frame
The same 960×640 scene paints in 0.34 ms in PaintBenchmark and in 2.15 ms
in the running showcase, both with four workers. The difference is present.
The benchmark’s own loop, run inside the live application between two real
frames, is four times faster than the frames on either side, and with
present skipped and nothing else changed the paint falls from 2.193 ms to
0.574 ms.
present moves megabytes and crosses into the kernel, and by the time the
next frame begins the pipelines, the destination pixels, the glyph caches and
the page tables that reach them have all been displaced. So:
- A benchmark compares options against each other. Worker counts, surface sizes and algorithms, with everything else held constant.
- A claim about what a frame costs comes from a frame. Read it off the trace line or the launcher’s summary, in a window that presents.
The summary page quotes both numbers for that reason, and labels each.
Building an application
How a Goldberry application is put together: what the classes are, what each one is allowed to know, and where a thing goes when you are not sure.
The rule underneath all of it is one sentence: data flows down, events flow up. Everything below is that sentence turned into files.
The four kinds of class

Views read values and report events. Actions assign values, and a changed value notifies the views.
| What it is | What it may know | |
|---|---|---|
| Values | a @Model class of plain fields | nothing. No widget, no window, no toolkit type beyond @Bind |
| Actions | an @Actions record nested in the values | the values. Not widgets, not the window |
| Views | Widget records — or a .kdl document | the values it reads and the actions it calls |
| Application | one implements Application, and no annotation | all three, plus the Host. The only class that knows a window exists |
Nothing points backwards. Values do not know actions exist; actions do not know
views exist; a view cannot write a value, because what it is handed is an
Observable with no set on it.
Values
A class of fields. Not a record — a record’s components are final and a bound field has to be assignable.
@Model
public final class Settings {
@Bind("app.gain") private Number gain = 40;
@Bind(value = "app.theme", restyle = true) private String theme = "dark";
@Bind(value = "app.bytesRead", repaint = false) private long bytesRead;
// Projections are fine: a question about the fields with one answer.
public Theme theme() {
return "light".equals(theme) ? Theme.NORD_LIGHT : Theme.NORD_DARK;
}
}
Each field declares what changing it costs:
- the binding — always. Anything bound to
app.gainis told. - a frame — by default;
repaint = falsefor a value nothing on screen shows. - a restyle —
restyle = truewhen a rule depends on it, not a widget. A theme and a density, and almost nothing else.
Assignment is what is observed, so hold a List and replace it rather than
editing one in place. The build refuses to bind an array for exactly this reason.
Actions
A record wrapping the values, nested inside them. One method per thing a control can ask for.
@Model
public final class Settings {
@Bind("app.gain") private Number gain = 40;
@Actions
public record Commands(Settings values) {
@Action("app.louder") public void louder() { values.gain = values.gain.doubleValue() + 1; }
@Action("app.pick") public void pick(String name) { values.theme = name; }
}
}
@Actions, not @Model. A class of methods holds no values and publishes no
paths, so it is not a model. A class carrying both
markers, or an @Actions class with a @Bind field, is a build failure saying
which one it should be.
Name it for its domain — Commands, Editing, Playback — and not
Actions. A nested type called Actions shadows the annotation, so @Actions
would resolve to your own record and you would have to write the annotation out in
full. The showcase does exactly that and pays for it, on purpose, so there is one
worked example of the wart.
values.gain = … notifies, even though the assignment is in a different class:
the build rewrites a write to a @Bind field wherever it appears.
A record, because it holds one thing and holds it immutably: no state of its
own, equals that means what it says, a constructor nobody writes. Wanting a
mutable field here is the signal that the thing is state — put it with the
values, where the rest of the state is.
Nested, because a nestmate reaches a private field. That is the whole reason,
and it is worth the one file: a sibling top-level class works too, but forces
every value open to the package. Nesting is scoping, not
coupling — the values class holds no reference to Actions and compiles with it
deleted.
Three shapes, in order of preference:
| Shape | Fields | When |
|---|---|---|
values with a nested @Actions record | private | the default |
| one class, values and methods together | private | a model with three fields |
values and a sibling @Actions class | package-private | you want two files and will pay for them |
An @Action method takes no argument, or one the toolkit can parse from a string
(String, double, int, boolean). A button reports that something
happened; a slider reports what it should become.
Views
Two forms, and they resolve names identically.
Markup, for structure:
column class="settings" {
slider bind="app.gain" min=0 max=100 change="app.set-gain"
button "Louder" press="app.louder"
}
Java, for anything a document should not carry — a loop, a conditional, a widget built from a list:
public record Panel(Settings settings, Settings.Commands actions) implements Widget.Stateless {
@Override public Widget build(BuildContext context) {
return new Column(
new Slider(0, 100, Models.observable(settings, "app.gain"), actions::setGain),
new Button("Louder", actions::louder)
);
}
}
bind="app.gain" and Models.observable(settings, "app.gain") are the same
lookup against the same registry. There is one name for a value, not two.
What a view may not do
Write. A widget is handed the Observable half of a value and there is no set
to call — so a control built from markup cannot reach the model even by accident,
and “who changed this?” always has an answer.
Widget state versus application state
Two different things, and putting one where the other goes is the commonest mistake.
| Lives in | Dies when | |
|---|---|---|
| a scroll offset, a caret, which tab is open, a hover | State on the widget | the widget is unmounted |
| the gain, the theme, the document being edited | the values class | the application exits |
Ask: would a second screen showing this need the same answer? If yes, it is application state.
The application
One class. The only one that knows a window exists.
public final class Hello implements Application {
private final Settings settings = new Settings();
private final Settings.Commands actions = new Settings.Commands(settings);
private Icons icons;
/// Everything markup may name, and everything the window follows.
@Override public List<Object> models() {
return List.of(settings, actions);
}
@Override public void start(Host host) {
// Anything the window owns for its whole life is made here and released
// in stop(): a widget is a value that gets rebuilt and thrown away, so
// nothing that costs money to build belongs in a build method. An icon
// is parsed from the bundled set and scaled to one size, which is work
// to do once rather than per frame.
icons = Icons.strict().bind("plus", Icon.bundled("plus", 16));
host.shortcut("Ctrl+T", actions::toggleTheme);
}
@Override public Widget root() {
return new Panel(settings, actions);
}
@Override public List<Stylesheet> stylesheets() {
return Controls.stylesheets(settings.theme());
}
@Override public void stop() {
icons.close();
}
public static void main(String[] args) {
Goldberry.run(new Hello());
}
}
models() is the whole of the wiring. From that one list the toolkit gets:
- what a document’s
bind=andpress=resolve against; - when to repaint — any value that asks;
- when to restyle — any value declared
restyle = true.
There is no repaint() call anywhere in an application, and there should not be
one.
More than one model
The list is a list because a window has actions of its own — “open the menu”,
“toggle the HUD” — that need a Host and therefore have no business on a view
model. Put them on the Application itself, annotate it @Model, and add this:
/// The window's own actions. Two Runnables, so this knows what they are called
/// and nothing about who performs them.
@Actions
public record WindowActions(Runnable openMenu) {
@Action("app.open-menu") public void open() { openMenu.run(); }
}
public final class Hello implements Application {
private final WindowActions window = new WindowActions(this::openMenu);
@Override public List<Object> models() { return List.of(settings, actions, window); }
private void openMenu() { host.popup(…); }
}
The Application itself is not a @Model. It owns the window, the lifecycle
and the native resources; making it also a thing markup resolves names against
puts two unrelated roles on one class.
Two models may not claim one name; the build says which two.
Inflating a document
var inflater = Widgets.inflater(icons, models().toArray());
var window = inflater.inflate(KdlParser.resource(Hello.class, "window.kdl").getFirst());
From models(), not from a list written out again. Two lists that must agree
are two lists that will not. An action present in models() and missing from the
inflater passes every test and throws no action named "app.toggle-theme" is bound on the first frame.
icons is the one registry that cannot be derived: an Icon is parsed from the
icon set and built scaled to one size, so icon="plus" in a document reloaded on
every keystroke would re-parse and re-scale one per reload. Markup may name an
icon and must never build one. An Icon is an immutable value whose close()
does nothing, so the cost is work rather than a leak.
Widget names need no registration at all. Every module on the path that ships
widgets announces itself, so Widgets.inflater already knows button and
column and anything a third widget module brought with it.
Shipping a widget
If you are writing widgets rather than using them:
@Markup("gauge")
public record Gauge(double value, Observable<?> source, Attributes attributes)
implements Widget.Leaf, Styled, Paints {
public static Widget inflate(KdlNode node, List<Widget> children, Wiring wiring) {
return new Gauge(node.numberProperty("value", 0), wiring.bound(node),
Attributes.of(node));
}
}
That is the whole registration. The build collects every @Markup class in the
module into a catalog and declares it as a service; an application that never
names your module gets your widget.
Every built-in is constructible three ways: Java, KDL, and styleable by CSS. Hold your own widgets to the same rule. It is what makes a document portable between an application and a preview tool.
Where does it go?
| I have… | It goes… |
|---|---|
| a value a widget shows | a @Bind field on the values class |
| a value nothing shows, but something watches | @Bind(…, repaint = false) |
| a value a stylesheet depends on | @Bind(…, restyle = true) |
| something a button does | an @Action on the actions class |
| something only Java calls | a plain method on the actions class |
| a derived answer about the values | a method on the values class |
| a scroll offset, a caret | State on the widget |
| an icon, a font, a native handle | opened in start, closed in stop |
| a menu, a popup, an accelerator | the Application, which has the Host |
| a new node name for markup | @Markup on the widget |
an action that needs the Host | a small @Actions record of Runnables, built by the application |
The package layout that follows
com.example.app
├── Hello.java Application: the Host, the lifecycle. No annotation.
├── Settings.java @Model values, with a nested @Actions record Commands
├── WindowActions.java @Actions record: the actions that need the Host
├── window.kdl structure
├── app.css appearance
└── ui/
├── Panel.java Widget records
└── Gauge.java @Markup, if you ship widgets
Views in their own package, because they should be replaceable without touching the model. Everything else is flat: there is not enough of it to file.
Starting fast
What a user waits for is the process, not the toolkit, so it depends on how the
application is launched. For the showcase, from exec to its first frame on a
Linux desktop:
| Launch | First frame |
|---|---|
| GraalVM native image | about 520 ms, the window open at about 120 ms |
| JVM with a JDK 25 AOT cache | about 1.3 s |
| JVM, cold | about 2 s |
A native image is the fastest and the one a release of the showcase ships. On
the JVM, train an AOT cache (JEP 483, JEP 514, JEP 515): run the application
once with -XX:AOTCacheOutput=app.aot through the screens a user opens first,
then launch it with -XX:AOTCache=app.aot. Classes then arrive loaded and
linked and the hot methods already profiled. The cache belongs to your
application — it is specific to the JDK build and the module path, and it is
trained on your screens — which is why the toolkit documents it rather than
shipping one.
-Dgoldberry.log.level=TRACE prints the start-up timeline after the first
frame: each phase from process start, so you can see which part is yours.
What the build does to all this
Your model is plain Java. An ordinary jar binds it at run time, with no build
step. A native image binds it ahead of time, through one Gradle plugin or one
Maven <execution>. Ahead-of-time binding says when
you need it and how to add it.
Markup
A KDL document is a widget tree written down, and the names in it resolve against what your application registers.
By the end of this chapter you can write a document, parse it, inflate it against your models, wire its buttons and bindings, reload it while the window is open, and know where a document stops and Java begins.
column id="settings" {
text class="heading" "Preferences"
checkbox bind="prefs.frost" change="app.set-frost" "Frosted sidebar"
slider bind="app.gain" min=0 max=100 change="app.set-gain"
row {
spacer
button class="primary" icon="plus" press="app.create" "New"
}
}
var nodes = KdlParser.resource(Hello.class, "settings.kdl");
var inflater = Widgets.inflater(icons, models().toArray());
Widget settings = inflater.inflate(nodes.getFirst());
The result is an ordinary Widget. Put it in a build method, in a Tab, or
return it from root().
The syntax, as Goldberry reads it
Goldberry parses KDL 2.0 with a parser of its own, so that every node carries its line and column.
// A node is a name, then arguments, then properties, then a child block.
button class="primary" press="app.save" "Save" {
// children go here
}
/* Block comments nest: /* like this */ and the outer one still closes. */
text "A long label that continues" \
"on the next line"
/- text "A slashdash takes this whole node out"
progress value=0.5 max=1 indeterminate=#false
| Piece | What it is to a widget |
|---|---|
| node name | the widget type: button, column, radio-group |
| string argument | the primary content, "Save" on a button, "Preferences" on a text |
key=value properties | attributes. A repeated key keeps the last value |
{ … } children | the widget’s children, in source order |
#true #false #null | the keywords. Bare true is not a boolean and is refused |
| numbers | decimal, hex, octal or binary, with _ separators |
"…" and #"…"# | quoted strings with escapes, and raw strings fenced by # |
//, /* */, /- | line comments, nesting block comments, and the slashdash that comments out a node, an argument, a property or a child block |
; and \ | nodes on one line, and a node continued on the next |
Two pieces of KDL are refused by name rather than ignored: type annotations
such as (u8)123, and """ multi-line strings. A document that says
something the toolkit would discard should fail, not look as though it worked.
A parse error is a KdlSyntaxException with the line and column. So is an
unknown node name, and the message lists every name that is registered.
Parsing and inflating
KdlParser turns text into nodes. KdlInflater turns nodes into widgets.
List<KdlNode> fromText = KdlParser.parse("button \"Save\"");
List<KdlNode> fromFile = KdlParser.resource(Hello.class, "window.kdl");
KdlInflater<Widget> inflater = Widgets.inflater(icons, settings, actions);
Widget one = inflater.inflate(fromFile.getFirst());
List<Widget> all = inflater.inflateAll(fromFile);
KdlParser.resource reads a file beside the class, so window.kdl sits in
the same package as Hello.java. KdlInflater.byId(nodes, "bar") finds a
node in the document by its id, and refuses a document that uses one id
twice.
Widget names need no registration. Every module that ships @Markup widgets
announces its catalogue as a service, and Widgets.inflater finds every
catalogue on the path. A module you never name contributes its node names.
The four registries
A document names things it cannot build. Each kind of name resolves against a registry of its own, and the four answer four different questions.
| Attribute | Registry | What the name is | Where it comes from |
|---|---|---|---|
press="app.save" | ActionRegistry | a method | an @Action on a model in models() |
change="app.set-gain" | ActionRegistry | a method taking one value | an @Action(String), (double), (int) or (boolean) |
bind="app.gain" | BindingRegistry | a value that changes | a @Bind field on a model |
icon="plus" | Icons | a resource built once | Icons.strict().bind("plus", icon) |
controller="app.signup-form", validator="app.port-rule" | Named | an object that neither changes nor closes | Named.strict().bind(name, object) |
Widgets.inflater(icons, models...) reads the first two registries off the
models themselves and keeps the icons explicit, because an icon is parsed and
scaled to one size and markup must not be able to build one per reload.
Widgets.inflater(named, icons, models...) adds the fourth.
Important
Hand the inflater the same list
models()returns. Two lists that must agree will not, and the symptom is a window that throws on its first frame.
Strict by default
The registries a model publishes are strict. A name the document writes and nothing bound fails at inflation, with the text quoted and the bound names listed:
no action named "app.sav" is bound. Bound: app.create, app.save, app.set-gain
nothing is bound to "app.gian". Bound: app.gain, prefs.frost
no icon named "pluss" is registered. Registered: plus, palette
That is the point of a registry: press="delte" is a typo, and a button that
silently does nothing is the hardest kind of bug to notice.
A lenient registry resolves an unknown name to nothing. That is what a preview
or a golden image wants, and Widgets.inflater() with no arguments binds
nothing at all. A bound node then draws its argument as the fallback, so
text bind="user.name" "Name here" reads Name here in a preview.
A property is held to the same rule. A widget’s factory asks its node for the properties it understands. Once the whole document is built, the inflater compares what was asked for with what the document wrote, and a property nothing asked for is refused. The message names the node, where it is, and what that node does read:
row at 2:3 ignores gap=8; it reads id, class, tooltip, context-menu, name (line 2, column 3)
gap is a stylesheet property, so that row wants #toolbar { gap: 8px }. A
parent may read its children’s properties as well as its own: line-chart
reads the x and y of each point, and those count.
This holds for a lenient inflater too. An unbound name is something a preview
expects, and a property no widget reads is not. A document that cannot be fixed
at once is built with inflater.unread(UnreadPolicy.WARN), which logs one line
per property, or UnreadPolicy.IGNORE, which does not look.
bind= is a path and nothing else
text bind="app.status"
text bind="prefs.frost"
A path is a name, or names joined by dots. bind="!prefs.frost" is refused
at inflation:
"!prefs.frost" is not a binding path. A path is a name, or names joined by
dots — `frost`, `prefs.frost`. Expressions are not part of the markup contract.
Negation, formatting and arithmetic stay in Java, where they are already
testable. A bound widget is handed an Observable with no set, so markup
reads a value and cannot write it. What the user did goes back up as an action.
The path and the Java lookup Models.observable(settings, "app.gain") are one
name against one registry.
The attributes every node has
| Attribute | What it does |
|---|---|
id="bar" | the #id a stylesheet selects, the name host.anchor and host.focus look up, and the node’s reconciler key |
class="primary danger" | the .class names, space separated. Replaces, never accumulates |
tooltip="…" | text the toolkit shows after a delay, on hover and on keyboard focus |
context-menu="rows" | the name of a menu a right-click opens. See Input and focus |
name="…" | the accessible name, for an icon-only control whose label is empty |
lang="en-US" | inherited locale for spelling and document hyphenation |
spellcheck=#true | opt in to spelling for editable descendant fields |
disabled=#true | on every control: refuses its action, leaves the Tab order, matches :disabled |
There is no key= attribute. In markup the id is the key, and the two
cannot disagree. A list item whose identity is a row of a model gets its key
from Java, with .keyed(row).
The widget-specific attributes are in each widget’s chapter under
Components: min= and max= on a slider,
label= and required= on a field, value= on a radio.
Hot reload
Markup and stylesheets can be re-read while the window is open. The reload
package has two classes: ReloadableSource parses a file and keeps the last
version that parsed, and HotReload watches the file’s directory and applies
changes on the UI thread.
import dev.goldberry.reload.HotReload;
import dev.goldberry.reload.ReloadableSource;
private final ReloadableSource<Stylesheet> styles = ReloadableSource.load(
Path.of("src/main/resources/com/example/app/app.css"),
css -> Stylesheet.parse(CascadeLayer.APPLICATION, css)
);
private final ReloadableSource<List<KdlNode>> document = ReloadableSource.load(
Path.of("src/main/resources/com/example/app/window.kdl"),
KdlParser::parse
);
@Override public void start(Host host) {
reload = HotReload.watch(List.of(styles, document), Goldberry.ui(), source -> {
if (source == styles) {
host.restyle(); // stylesheets() reads styles.current()
} else {
// Your own root is a Widget.Stateful: hand it the new nodes and let
// its State re-inflate them inside setState.
screen.reload(document.current());
}
});
}
@Override public List<Stylesheet> stylesheets() {
return List.of(Controls.baseStylesheet(), Theme.NORD_DARK.load(), styles.current());
}
@Override public void stop() {
reload.close();
}
The first parse is strict: an application that starts with a broken file says so. After that a broken save is the normal case. The last good version stays in force, the failure is logged once with its position, and the next save gets another go. An identical save is ignored. Saving a file is several events, so the watcher waits for a short quiet period before reading.
Because the names a document uses resolve against registries, a reloaded document stays wired to the same handlers the old one had. That is why markup names an action and cannot be one.
Note
On macOS the JDK’s
WatchServicepolls, so a change can take a couple of seconds to be noticed.
What markup cannot say
A document is data. It has no loop, no conditional, and no way to build a
widget from a list. Those are Java, in a build method:
@Override public Widget build(BuildContext context) {
var rows = new ArrayList<Widget>();
for (var member : company.members()) {
rows.add(new Text(member.name()).keyed(member.id()));
}
return new Column(rows);
}
A document cannot hand a Runnable to a widget, cannot compute a colour from
a value, and cannot shorten a list when the model does. It can name every one
of those things, and Java supplies them.
What a document can do is say where such a widget goes. A model field that
holds a widget is placed with slot bind="…",
and the region redraws whenever the model replaces it. A conditional becomes
a model that holds one widget or another, and the loop above becomes a model
that rebuilds the Column.
How Java and markup compose
A document inflates to a Widget, so it goes wherever a widget goes. The
showcase keeps each screen’s static cards in a document whose root is a
masonry, and appends the cards only Java can write:
Masonry cards = Panes.wallOf(inflater, "basic.kdl"); // the document's root
var all = new ArrayList<>(cards.children());
all.add(new ClickCounter(model, actions)); // a card markup cannot write
return new Masonry(all, cards.columns(), cards.minColumnWidth(), cards.attributes());
The other direction works too. A button in a document resolves press=
against an @Actions record the application built in Java, and the window’s
own commands live on a record of Runnables beside the view model
(Building an application).
Read more
- Ahead-of-time binding: what the build does to a model
Styling
A small CSS: four fixed layers, a closed set of selectors and properties, custom properties for everything a theme decides, and transitions that cannot run layout.
By the end of this chapter you can load an application stylesheet, select a widget and its parts, know which properties resolve and which are refused, swap a theme and a density at run time, and animate the properties the toolkit lets you animate.
#root { flex-direction: column; background: var(--gb-bg); color: var(--gb-text) }
#bar { height: 44px; padding: 0 16px; gap: 12px; align-items: center }
.screen { flex-direction: column; gap: 16px; padding-top: 16px }
button.danger:hover { background: var(--gb-button-danger-bg-hover) }
private final Stylesheet styles =
Stylesheet.resource(CascadeLayer.APPLICATION, Hello.class, "app.css");
@Override public List<Stylesheet> stylesheets() {
var sheets = new ArrayList<>(Controls.stylesheets(Theme.NORD_DARK));
sheets.add(styles);
return sheets;
}
Stylesheet.resource reads a file beside the class and parses it at start-up.
A malformed stylesheet is a CssSyntaxException with a position, because a
window that opens unthemed and says nothing is worse than one that refuses to
open. Stylesheet.parse(layer, text) does the same for a string.
A sheet read with Stylesheet.resource may start with @import, which reads
another sheet beside it, as its url()s are: @import "tokens.css";, or with
a media list, @import url(narrow.css) (max-width: 600px);, whose rules then
apply under that condition. The imported rules come before the importing
sheet’s own, so the importer wins a tie. An import that names a sheet that is
not there, or one already being imported, is dropped with a warning. A sheet
parsed from text has nowhere to look beside, so its imports are reported and
skipped. An @import after any other rule is ignored, as CSS ignores it.
Strict and lenient sheets
A sheet that asks for something the subset has not got is a different case from a malformed one, and what happens depends on whose sheet it is.
| Sheet | Parsed | A selector, pseudo-class or at-rule outside the subset |
|---|---|---|
the toolkit’s own (controls.css, the themes, the content sheets) | strict | refuses the sheet with a CssSyntaxException |
an application’s (Stylesheet.resource or Stylesheet.parse in any other layer) | lenient | drops that rule, with one warning naming the selector, the sheet and the line |
WARN app.css, line 42: dropping "lane::before": unsupported pseudo-element
A rule nested inside another that asks for something outside the subset,
a { &::before { … } } say, is dropped by itself with a warning, and the rest of
the rule holding it is read.
A strict sheet also refuses any timing function but the design system’s three
curves, ease-enter, ease-exit and linear, so the toolkit’s own controls
all move on them. A lenient sheet may write any curve CSS has; see
Transition and animation.
A lenient sheet keeps what it dropped in Stylesheet.dropped(), and
StyleLint reports each one as a DROPPED_RULE finding. A property the
engine has not got at all, such as float, is warned about once per
property per sheet when the sheet is read, with the first line it appears on.
A malformed sheet (an unclosed block, a declaration with no value) is refused
in both modes, which is what lets hot reload keep the
last good sheet while you type. The mode can be chosen explicitly with
Stylesheet.parse(layer, text, ParseMode.STRICT).
Run with -Dgoldberry.css.lint=true while developing and the launcher lints
your sheets each time it reads them (Logging).
The cascade: four layers
public enum CascadeLayer { TOOLKIT_BASE, THEME, APPLICATION, INLINE }
| Layer | Holds | Who writes it |
|---|---|---|
TOOLKIT_BASE | controls.css: every control’s metrics and structure, reading colours through var(--gb-*) | the toolkit, Controls.baseStylesheet() |
THEME | nord-light.css or nord-dark.css: the custom properties, plus the density and scrollbar sheets | the toolkit, Theme.NORD_DARK.load() |
APPLICATION | your stylesheets | you |
INLINE | what only a widget can compute, through Styled.restyle | a widget author |
At equal specificity a later layer wins, so an application rule beats a theme rule beats a base rule. Specificity is CSS’s: an id beats a class beats a type.
The four layers’ order cannot be argued with by a stylesheet that loads late.
Inside APPLICATION, an application may order its own rules with @layer:
@layer reset, vendor; names layers in the order they rank, @layer vendor { … } puts rules in one, and @import url(vendor.css) layer(vendor); puts a
whole sheet in one. A rule in no layer ranks above every layer, and a later
layer above an earlier one; !important turns that round. A layer ranks the
way the four layers do, after specificity: it decides between rules of equal
specificity, so a vendor’s .btn loses to your .btn whichever loads last,
but a vendor’s .btn.primary still beats your .btn, where CSS would let
yours win. @layer in a theme or in the toolkit’s sheets ranks nothing.
INLINE has no style= attribute behind it. It is the layer a widget writes
into for a value no selector can express, such as the position of the third
of five segments.
Selectors
button { } /* type */
.primary { } /* class */
#save { } /* id */
panel text { } /* descendant */
row > button { } /* child */
label + text-input { } /* the sibling just after */
heading ~ paragraph { } /* any sibling after */
field:has(> :invalid) { } /* what is below it */
checkbox:hover check-indicator { } /* a part, under a state */
:root { --gb-accent: #b48ead }
list-row:nth-child(even) { } /* where it sits among its siblings */
.steps > :last-child { }
The pseudo-classes are a closed set. A typo such as :hovered is refused in
a strict sheet and dropped with a warning in a lenient one, rather than being
a rule that never matches.
| Pseudo-class | True when | Set by |
|---|---|---|
:hover | the pointer is over the node or a descendant | the router |
:active | a press is held on the node or a descendant | the router |
:focus | the node has keyboard focus, however it got it | the router |
:focus-visible | the node has focus from the keyboard | the router |
:focus-within | the node or something under it has keyboard focus | the router |
:disabled | the widget says it is disabled | the widget |
:enabled | the widget is not disabled | the widget |
:checked | the widget says it is on | the widget |
:indeterminate | a tri-state control is mixed | the widget |
:invalid | a field or its control failed validation | the widget |
:affixed | an affix has pinned itself | the widget |
:drag-over | a compatible drag is over the node | the router |
:window-inactive | the window and its popups lack keyboard focus | the router |
:root | the root element, where a theme hangs its properties | structure |
The structural pseudo-classes say where a node sits among its parent’s children:
| Pseudo-class | True when |
|---|---|
:first-child, :last-child | it is the first, or the last, of its parent’s children |
:only-child | it is its parent’s only child |
:nth-child(An+B) | it is at position An+B, counting from 1; odd and even work |
:nth-last-child(An+B) | the same, counting from the last child |
:nth-child(An+B of S), :nth-last-child(An+B of S) | it matches the selector list S, and is at position An+B among the siblings that match it |
:first-of-type, :last-of-type, :only-of-type, :nth-of-type(An+B), :nth-last-of-type(An+B) | the same five, counted among the siblings of its own type |
The siblings are the children of the node’s parent element, which is also
what > reads. A composition widget is an element with one child, like an
unstyled <div> around one node, so a card a stateless wrapper builds is the
only child of that wrapper. When a parent’s children are added, removed or
reordered, only the children whose structural answer changed are restyled,
and a sheet with no structural pseudo-class restyles nothing.
:hover and :active reach the whole ancestor chain, which is what lets
checkbox:active check-indicator light the glyph when the label is pressed.
The router refuses to set :hover or :active on a disabled widget, which
is how a disabled control stays dull without :not(:disabled):hover.
+and~read the siblings before a node, the same children>and the structural pseudo-classes count.:has()reads the other way: `field:has(>- invalid)
is a field whose own child is invalid,card:has(:checked)a card with a checked box anywhere inside it, andheading:has(+ paragraph)a heading a paragraph follows. Its selectors may start with>,+or~, and start below the node when they do not. A:has()` inside another is refused, as in CSS.
These are the selectors that make one node’s style depend on another node.
Under a sheet that writes + or ~, a change to a node restyles its
siblings; under one that writes :has(), a change restyles the nodes above
it (and, for :has(+ …) and :has(~ …), the siblings before them) whose
type a :has() sits on. A state a widget owns, :checked say, is read before
the frame is styled, so card:has(:checked) changes in the frame the box is
checked. Sheets that write neither, which are the toolkit’s own, pay nothing
for them.
:is(), :where() and :not() take a list of selectors, each of which may
have combinators of its own: :is(button, toggle):hover,
list-row:not(.selected), :is(card > header) text. :is() matches when any
of them does and :not() when none does; each is as specific as the most
specific selector in its list. :where() is :is() with no specificity at
all, which makes it the way to write a default any rule can override. A
selector in the list that is outside the subset, :is(a[href]), drops the
rule it is in, where a browser would ignore that one entry.
A rule that counts siblings through of S restyles every child of a parent
that rebuilds, and the siblings of a child whose state changes, since which of
them match S may have moved. A sheet without one pays nothing.
:focus-within moves with the keyboard: a move between two controls in one
field leaves the field’s answer alone, so a rule on it does not flicker.
Handles.onFocusWithin tells a widget the same thing as a notification.
Not in the subset: attribute selectors, and generated content such as
::before and ::after. A widget’s properties stay out of the
cascade, so a state a stylesheet should see is a class or a pseudo-class; a
part is selected by its type name, and generated content is a widget.
A rule may hold rules, as CSS’s nesting writes them:
card {
padding: 12px;
&:hover { background: var(--gb-surface-hover) }
> header { font-weight: 600 }
.compact & { padding: 6px }
@media (max-width: 600px) { padding: 8px }
}
& is the rule it is inside. A nested selector without one is relative to it:
header means & header and > header means & > header. When the outer
rule has several selectors, & matches any of them, and is as specific as the
most specific, as :is() is. @media may sit inside a rule and holds
declarations for that rule’s selector as well as rules of its own. Order is
kept: declarations written after a nested rule come after it in the cascade.
Every nested rule is read into an ordinary one when the sheet is parsed, so
the selector structure is ready when the sheet is loaded. Nested rules can
also use @media and @supports.
:window-inactive is the window’s state rather than a node’s, so it is written
on whatever the rule is about: spinner:window-inactive or
:window-inactive .badge. A window that is covered or minimized already stops
its animations by itself; this is for motion an application would rather pause
while the user works in another window.
.attention:window-inactive { animation-play-state: paused }
Parts
A control with two surfaces a theme must style differently is two cascade nodes. The inner one is a part: it has a type name, matches pseudo-classes and takes properties, and it cannot be written in a document.
checkbox { gap: 8px }
checkbox check-indicator { border-radius: 4px }
checkbox:checked check-indicator { background: var(--gb-checkbox-bg-checked) }
toggle-track:checked toggle-thumb { transform: translate(16px) }
scroll:hover scroll-thumb.vertical { width: 10px }
check-indicator, toggle-track, toggle-thumb, slider-value,
scroll-thumb, field-message and tab-panel are parts. Each widget’s
chapter lists its own under Styling.
Two parts also answer to the pseudo-element a browser’s sheet would write for
them. A field’s value is ::placeholder while it shows the placeholder, and
so is a select’s while nothing is chosen; a field’s text-selection and a
document view’s selection-layer are ::selection:
text-input::placeholder { color: var(--gb-text-muted) }
text-input:focus::placeholder { color: transparent }
::selection { background: var(--gb-accent-bg-hover) }
A state written before the :: is the control’s. text-input::placeholder
matches the part below the text-input, which is the same node
text-input text-value.placeholder selects; a pseudo-element ends its
selector, and one inside :is() or :has() is refused, as in CSS.
::selection takes background: the highlight is drawn behind the text, and
the text keeps its colour so it stays readable.
An editable field that checks spelling can style its wavy underline with
::spelling-error. The cascade also recognizes ::grammar-error for widgets
that provide a matching part. Spell checking
Properties
The subset is closed. A property the engine does not know is ignored, and the sheet naming it warns once per property when it is read. A known property with a value it cannot read is dropped with a warning that quotes the text.
Box and layout
.toolbar {
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: center;
gap: 8px; /* or gap: 4px 8px, row then column */
padding: 8px 12px;
margin: 0 auto;
width: 100%;
min-height: 32px;
overflow: hidden;
}
.toolbar > button { flex: 1 0 120px; align-self: flex-end }
.badge { position: absolute; top: 4px; left: 4px }
flex-direction, flex-wrap, flex, flex-grow, flex-shrink,
flex-basis, justify-content, align-items, align-self,
align-content, gap, row-gap, column-gap,
padding and its four sides, margin and its four sides, width, height,
min-width, max-width, min-height, max-height, aspect-ratio,
position, inset, top, right, bottom, left, overflow and
display. The layout engine reads these properties.
flex expands as CSS says: flex: 1 is 1 1 0%, flex: auto is
1 1 auto, flex: none is 0 0 auto, and flex: 120px is 1 1 120px.
margin: auto centres on the main axis.
aspect-ratio is auto, a number, or width / height, and sizes the axis the
box does not fix.
Every box is a flex box, so display has three values. display: none takes
the node and everything under it out: nothing is laid out, painted, hit or
reachable by the keyboard, and its elements stay mounted with their state, as a
background tab’s do. display: contents takes the node’s own box away and lays
its children out as its parent’s; whatever the widget draws itself, its text
or its icon, goes with the box. display: flex is what every box is already.
block, inline and grid are dropped with a warning.
visibility: hidden leaves the box’s own drawing out and keeps its room: it is
not painted, the pointer passes through it, and the keyboard skips it.
collapse is read as hidden. pointer-events: none lets the pointer through
to whatever is under the box, which still draws. Both inherit, and both are
per box: a child that says visibility: visible or pointer-events: auto
under a parent that said otherwise is drawn, or hit, as usual.
user-select: text makes the words of a text, and of any other box that
draws words and does not handle the pointer itself, selectable: a drag selects,
a double click takes a word and a triple click the whole box, and Ctrl+C
(Cmd+C on macOS) copies when nothing focused takes the key. user-select: all
selects the whole box at a click. auto leaves a plain text unselectable,
since a label is pressed rather than selected. A rich-text takes the property
as its own selectable: text and all turn selection on, and none turns
it off. In a markdown-view or an html-view, none keeps a press from
selecting, all makes any click select the whole document, and text and
auto are the default. The highlight is --gb-selection. One selection is kept
per window: a press elsewhere clears it, and a press on a button leaves it
alone, so a Copy button can act on it. user-select inherits, and
-webkit-user-select is the same property.
z-index is auto or a whole number, and orders a box among its siblings: a
higher one is drawn later and found first by the pointer, and equal ones keep
document order. It applies to every box, positioned or not, since every box is
a flex item. It orders siblings and nothing else, so a box cannot rise above
its parent’s siblings; something that must cover the whole window is an
overlay.
Lengths are px, %, em, rem, ch, ex, the absolute units in,
cm, mm, Q, pt and pc, at 96 pixels to the inch, and the viewport
units vw, vh, vmin and vmax. ch is the advance of the digit zero and
ex the x-height, both in the face the element is drawn in. A viewport unit is
a percentage of the window; a desktop window has one size, so svh, lvh and
dvh are all vh. A sheet that writes a viewport unit is restyled when the
window is resized, and one that writes none is not.
calc(), min(), max(), clamp(), round(), mod(), rem(), abs()
and sign() are read wherever a length, a number, an angle or a time is,
nested as deep as needed, with e and pi as numbers: rotate(calc(45deg * 2)),
transition-duration: calc(var(--gb-motion-fast) * 2) and
translate(calc(-50% + 4px)) all work. Each is worked out when the style is
computed. A colour’s components are not read this way, and
rgb(calc(255 / 2) 0 0) is dropped. One that
mixes a percentage with a length, like calc(100% - 8px), is dropped with a
warning by width, margin, padding, gap and the rest of the layout
properties, because the layout engine sizes a box by a length or by a
percentage and never by both; give the parent padding instead, or a child
flex: 1. The same goes for min(), max() and clamp() over a percentage
and a length, which cannot be compared before the box is laid out.
The logical properties are read as the physical ones they are with a horizontal
writing mode. The inline axis follows direction and the block axis runs
from top to bottom. margin-inline,
margin-block, padding-inline, padding-block, inset-inline and
inset-block take a start and an end, one value being both;
margin-inline-start, padding-block-end, inset-inline-start and the
rest are one side each; inline-size, block-size and their min- and
max- forms are the width and the height.
place-content is align-content then justify-content, place-items is
align-items then justify-items, and place-self is align-self then
justify-self, one value being both. justify-items and justify-self are
read and change nothing, as CSS says for a flex item, which every box is; a
value CSS would refuse is still dropped. justify-content: stretch is the
start, as it is on any flex container.
overflow takes one value for both axes or two, across then down, and
overflow-x and overflow-y set one each: visible, clip, hidden,
scroll and auto. clip cuts the content off like hidden and nothing
can scroll it. A box is clipped on both axes when either axis is anything but
visible; CSS clips one axis only for visible beside clip.
.chip { padding-inline: 8px; margin-block: 2px 4px }
.centred { place-items: center }
.strip { overflow: hidden auto }
order places a box among its siblings: lower first, document order among
equals, 0 unless a rule says otherwise. Layout, painting and the pointer
follow it; the keyboard’s Tab order stays the order the children are written
in.
direction: rtl runs a box right to left, and its children with it, since it
inherits. A row starts at the right, margin-inline-start and the other
logical properties name the right side, and text-align: start places a line
at the right; left and right stay the sides they name. It is also the base
direction of the box’s text: which side a line starts at, and where the
punctuation and spaces between a right-to-left word and a left-to-right one
go. writing-mode is not in the subset.
.toolbar.rtl { direction: rtl }
.toolbar .primary { order: -1 } /* first, whatever the markup says */
A border takes room, outside the padding, as in CSS: a box’s content starts
inside its border and then its padding. box-sizing says what width and
height measure. Its initial value here is border-box, so a box given a
size keeps that size whatever border it has and its content gives way;
content-box adds the padding and the border to the size instead. A box
sized by its content grows by its border either way.
Math functions divide equal units to produce a number, such as
calc(24px / 8px). Multiplication requires a number on one side.
Text flow
.cell { white-space: nowrap; text-overflow: ellipsis; overflow: hidden }
.readout { text-align: end }
link { text-decoration: underline }
.misspelled { text-decoration: wavy underline var(--gb-danger) }
.log { white-space: pre-wrap; overflow-wrap: anywhere }
white-space: normal | nowrap | pre | pre-wrap | pre-line. A paragraph
never collapses spaces or newlines, so the five keywords are two behaviours:
pre-wrap and pre-line wrap as normal does, and pre stays on one line
as nowrap does. pre-line keeps runs of spaces CSS would fold into one.
overflow-wrap: normal | anywhere | break-word cuts a word wider than the
whole line between grapheme clusters; word-break: normal | break-all may cut
any word at the edge of the line. A text-area cuts its rows the same way, and
its caret, selection and scroll follow the cut. Both inherit.
text-overflow: clip | ellipsis controls what a nonwrapping line shows.
text-align accepts start, center, end, left, right and justify.
text-align: justify sets every line of a paragraph but its last flush with
both edges, sharing the room left on the line among its word gaps. A line a
newline ends is a paragraph’s last too, and so is one with no gap; those sit
at the start. text-justify: none turns it off, and auto and inter-word
both mean the word gaps. A field being edited is never respaced, so its caret
stays on the glyphs: a text-area with justify keeps its lines at the
start.
text-decoration is a shorthand for four properties, written in any order:
text-decoration-line: none | underline | line-through, one or both;text-decoration-style: solid | double | dotted | dashed | wavy;text-decoration-color, which follows the text’s colour until one is written;text-decoration-thickness: auto | from-font | <length> | <percentage>. A percentage is of the element’s font size, andautoandfrom-fontboth take the face’s own thickness.
The shorthand resets the parts it does not name, so text-decoration: underline after text-decoration: wavy red line-through draws a solid
underline in the text’s colour. text-underline-offset: auto | <length> | <percentage> is not part of it. It moves an underline’s top edge to that
distance below the baseline and leaves a line-through where it is. overline
is not drawn, and a declaration that asks for it is dropped.
A decoration reaches the text inside the element that declares it, together
with its style and colour. button.link { text-decoration: underline dotted }
draws a dotted line under the label inside the button. Dots, dashes and waves
keep their rhythm across a line written in several styles, so a bold word in
the middle of an underlined sentence does not restart the pattern.
line-clamp: <n> | none, or -webkit-line-clamp, keeps the first n lines
of a paragraph and draws an ellipsis at the end of the last one when more were
cut. The box is measured at the lines it keeps. Unlike a browser, which also
wants display: -webkit-box and overflow: hidden beside it, the property
alone does it. It does not inherit.
Text in a right-to-left script reads from the right wherever it is: a Hebrew word in an English sentence, a number in an Arabic one, a whole field of either. Each line is placed in reading order, and the caret, a click and a selection follow what is on screen; a selection across a change of direction is highlighted in a piece on each side.
A box’s text takes its base direction from direction. unicode-bidi says
otherwise:
| Value | The base direction of the box’s text |
|---|---|
normal | The box’s direction. The initial value; embed and isolate read the same, since a box’s text is always a paragraph of its own |
plaintext | Each paragraph’s first letter with a direction, and the box’s direction for a paragraph with none. text-align: start and end then follow each paragraph |
bidi-override | The box’s direction, for every character: right-to-left script is drawn left to right under ltr. isolate-override reads the same |
.message { unicode-bidi: plaintext } /* each message reads its own way */
.code { unicode-bidi: bidi-override; direction: ltr }
unicode-bidi does not inherit. In a text-input or a text-area the
arrow keys move through the text in reading order: Left moves on in a
right-to-left paragraph and back in a left-to-right one.
hyphens: none | manual | auto controls discretionary breaks in
Markdown and HTML prose.
manual is the initial value and honours soft hyphens. auto also uses
the bundled English patterns when the view’s lang selects English.
The property inherits.
Typography
.heading { font-family: Inter; font-size: 15px; font-weight: 600; line-height: 20px }
.mono { font-family: "JetBrains Mono" }
.note { font-style: italic }
font-family, font-size, font-weight, font-style, line-height, and the
font shorthand.
A weight is any number from 1 to 1000, or normal (400) or bold (700), and
CSS weight matching chooses the nearest available weight when the family
provides static faces.
font-style: oblique is refused because nothing shears a glyph.
font-family: Inter, sans-serif takes the first name and discards the rest.
Upright Inter and JetBrains Mono are variable faces, and any weight a
stylesheet writes is drawn at that weight: font-weight: 500 is a 500, and
bold a 700. The italics are separate files at 400 and 600 and draw the
nearest of the two. font-stretch (a keyword such as condensed, or a
percentage from 50% to 200%) sets the width of a face that has a width axis,
and font-variation-settings sets any axis a face has by its tag:
.display { font-variation-settings: "opsz" 32 }
.tight { font-stretch: 87.5% }
An axis a face does not have is ignored, and a value past an axis’s range is
brought back inside it. Both inherit, and font resets them.
A font-size is a length, a percentage of the parent’s size, smaller or
larger (a fifth either way from the parent’s), or one of CSS’s keywords from
xx-small to xxx-large, stepped from the root’s size, which is what medium
is. line-height is a length, a number times the size, or normal, which is
1.2 times the size.
font: [style] [weight] <size>[/<line-height>] <family> sets all five, and
puts back to their initial values the ones it does not name: the style and
the weight to normal, the line height to normal.
letter-spacing is added after every character and word-spacing to every
space, each normal or a length, which may be negative. Both inherit as the
pixels the parent computed, so 0.1em on a heading stays the heading’s tenth
in its labels. The text wraps, measures and takes the caret with the spacing it
is drawn with. A percentage is not read for either. font leaves both alone.
text-transform draws text in uppercase, lowercase or capitalize, and
inherits. It changes what is painted and never the text a widget holds, so a
field keeps its value, copies it as typed, and its caret lands where it
would. Every character is cased into exactly one character, which is what
keeps the caret true: ß stays ß in capitals.
text-shadow is a comma list of shadows under the text, the first on top,
each <x> <y> [<blur>] [<color>]; with no colour it is the text’s own. It has
no spread and no inset, as in CSS, and inherits. A shadow with no blur is the
text drawn again at its offset; a blurred one is drawn once into a picture of
its own and kept, so a label that does not change pays for its blur once.
font-feature-settings sets OpenType tags such as "tnum" 1, "liga" 0.
font-variant-numeric reads numeric variants such as tabular-nums and
oldstyle-nums. Both properties inherit and font resets them.
Colour
panel { background: var(--gb-surface); color: var(--gb-text) }
.faded { opacity: 0.5 }
.wash { background-color: rgba(136, 192, 208, 0.2) }
background, background-color, color and opacity.
A colour is a hex value (#rgb, #rgba, #rrggbb, #rrggbbaa); rgb() or
rgba(), with commas or with spaces and a slash before the alpha
(rgb(0 0 0 / 50%)); hsl(), hwb(), lab(), lch(), oklab(), oklch()
or color() in srgb, srgb-linear, display-p3 or xyz; one of the 148
named colours; transparent; currentcolor; or a var(). A colour outside
sRGB is clamped into it. currentcolor is the element’s own color, so
border: 1px solid currentcolor draws the border in the text’s colour; it is
fixed when the style is computed, so a color transition moves the text and
not the border. opacity is a number from 0 to 1 or a percentage.
opacity on a node
with children renders the subtree into a layer and composites it once, so two
overlapping children do not show through each other. A translucent leaf
keeps the cheap path.
Two colours can be made from others. color-mix() mixes two in a colour
space, OKLab when it names none, as much of each as its percentage says:
.primary:hover { background: color-mix(in oklch, var(--gb-accent), black 12%) }
.scrim { background: color-mix(in srgb, var(--gb-surface) 60%, transparent) }
A colour with no percentage takes what the other leaves of 100%, and two that
add up to less than 100% leave the mix that much transparent. A space with a
hue, oklch, lch, hsl or hwb, may say shorter, longer, increasing
or decreasing hue.
A colour function may also start from another colour and name its channels:
r g b in rgb(), h s l in hsl(), h w b in hwb(), l a b in
lab() and oklab(), l c h in lch() and oklch(), r g b or x y z in
color(), and alpha in all of them. Each is the origin’s value as a plain
number, so calc() can work on it:
.soft { background: oklch(from var(--gb-accent) calc(l + 0.15) c h) }
.ghost { border-color: rgb(from var(--gb-accent) r g b / 40%) }
Neither reads currentcolor.
Backgrounds and gradients
.glow { background: radial-gradient(circle at top, #88c0d066, transparent 60%), var(--gb-surface) }
.tint { background-image: linear-gradient(to right, #bf616a33, transparent) }
.running { background: repeating-linear-gradient(90deg, #a3be8c 0 6px, transparent 6px 12px);
animation: march 400ms linear infinite }
@keyframes march { to { background-position: 12px 0 } }
background is a comma list of layers, the first drawn on top, with the
colour in the last one. background-image sets the layers and keeps the
colour; background-color sets the colour and keeps the layers; background
resets both, and background: none is no fill at all.
A layer is linear-gradient(), radial-gradient(), conic-gradient() or
their repeating- forms:
- A linear gradient runs
toa side or a corner, or at an angle (deg,rad,grad,turn, with0up and turning clockwise). It runs to the bottom when it says nothing. - A radial gradient is a
circleor anellipse, sized byclosest-side,closest-corner,farthest-sideorfarthest-corner(the default) or by lengths, and centredata position. - A conic gradient turns clockwise round a centre, from the top or
froman angle, centredata position. Its stops are angles, or percentages of a turn. A repeating one repeats its first period round the turn. - A stop is a colour with up to two positions, each a length or a percentage. Stops are placed as CSS places them. A position alone between two stops is a hint: where the two colours are half and half.
inand a colour space, first in the list, blends the stops in that space rather than in sRGB:srgb,srgb-linear,display-p3,lab,lch,oklab,oklch,xyz,xyz-d50,xyz-d65,hslorhwb. A space with a hue takesshorter,longer,increasingordecreasing hue.
.ring { background: conic-gradient(from -90deg, var(--gb-accent) 0 72%, var(--gb-border) 0) }
.dawn { background: linear-gradient(in oklch to right, #f59e0b, #3b82f6) }
.glare { background: radial-gradient(white, 20%, transparent) }
Each layer is placed in one of the box’s rectangles and cut to another:
background-origin and background-clip, each border-box, padding-box
or content-box. The padding box is the box less its border and the content
box is the padding box less its padding, where its text starts. A layer starts inside the border and is drawn under it too; the
colour is cut to the last layer’s clip, so background-clip: padding-box
keeps a fill out from under a translucent border. Every rectangle keeps the
box’s rounded corners, tightened by the sides it is inside.
background-position, or background-position-x and -y alone, places
each layer with one to four words: lengths, percentages, left, center,
right, top and bottom, and a side with an offset from it, right 8px bottom 4px. A percentage is of the room the layer leaves, so 100% puts a
picture’s far edge on the box’s and moves a gradient, the size of its box,
not at all; only a length moves a gradient. background-size and
background-repeat size and tile a url() picture: repeat, no-repeat,
repeat-x, repeat-y, space (whole tiles, spread edge to edge) and
round (tiles stretched until a whole number fit), one for both axes or one
for each. Every one of these is a comma list matched to the layers, a short
list repeated. The background shorthand takes them all, the position and a
size as <position> / <size>, and one or two boxes: one is both the origin
and the clip, two are the origin and then the clip. It also takes scroll,
which is what a layer does anyway; there is no background-attachment
property and no fixed or local. background-position is animatable,
which is how the stripe above marches.
An image URL resolves beside the stylesheet that names it. Use
Stylesheet.resource for packaged images, or give Stylesheet.parse an image
resolver. A renderer caches resolved pictures for reuse. A missing picture
leaves the other layers and the background colour visible.
Border, outline and shadow
card { border: 1px solid var(--gb-border); border-radius: 8px; box-shadow: var(--gb-elevation-1) }
.tab { border: 1px solid var(--gb-border); border-bottom: none }
button:focus-visible { outline: 2px solid var(--gb-focus); outline-offset: 2px }
border and border-top, -right, -bottom, -left, each
<width> || <style> || <color> in any order. border-width, border-style and
border-color take one to four values, and each side has its own
-width, -style and -color. border-radius takes one to four corners,
and after a / one to four vertical radii, which make each corner a quarter
ellipse; each corner also has its own longhand, border-top-left-radius and
the rest, which takes one radius or a horizontal and a vertical one. A radius
is a length, a percentage, or a calc() of both: a percentage is of the box’s
width across and of its height down, so border-radius: 50% makes a circle
of a square box and an ellipse of any other. The inside of a border’s corner
is the outside less each side’s own width, so a corner between a thick side
and a thin one is an ellipse inside.
outline, outline-width, outline-style, outline-color and
outline-offset. An outline may be any style a border side may be, auto
being solid, and outline-style: none takes it away. box-shadow
is a comma list of shadows, the first on top, each
[inset] <x> <y> [<blur>] [<spread>] <color>.
A border takes room outside the padding, as piece 35 says. A shorthand that
names no style is solid, and the style none or
hidden is a side with no width.
dashedis dashes three widths long with gaps the same, stretched so a side starts and ends on a dash. A square corner is a dash’s end; a rounded corner is one dash shared by the two sides.dottedis round dots as wide as the side, two widths apart, with one on every corner.doubleis two lines a third of the width each, with the middle third empty.insetandoutsetare lit from the top left: aninsetside is a darker tone of its colour on the top and the left and a lighter one on the bottom and the right, andoutsetthe reverse.grooveandridgeare two bands of half the width each, lit one way outside and the other way inside.
An outline is drawn outside the box and takes no room either, so a focus ring cannot move a control by appearing. Its style is always drawn solid.
A shadow is drawn as a stack of rounded rectangles whose alphas ramp across the
blur. An outer shadow is drawn under the background and only outside the box.
An inset shadow is drawn over the background and under the border, inside the
padding box: the box’s own shape, moved by the offset and shrunk by the spread,
is the hole it is seen around, and on a rounded box it follows the inside of
the curve.
A border may also be a picture cut in nine,
border-image:#menu-panel { border-image: url("classpath:/ui/panel.png") 48 fill / 48px stretch } button { border-image: url("classpath:/ui/button.png") 12 fill / 12px } button:hover { border-image-source: url("classpath:/ui/button-hover.png") }
border-image-sliceis one to four numbers or percentages, top first, in the picture’s pixels: they cut it into four corners, four edges and a middle, andfilldraws the middle too.border-image-widthsays how wide each side’s pieces are drawn: a number of border widths (1, the default), a length, a percentage, orautofor the slice’s own size.border-image-outsetpushes the picture out past the box by lengths or border widths.border-image-repeatisstretch(the default),repeatorroundfor the edges and the middle, one value or one per axis.border-image-sourceisnoneor aurl(), read as a background picture is,@2xvariant and#xywh=fragment included. Theborder-imageshorthand is<source> <slice> / <width> / <outset> <repeat>, in any order with the slashes after the slice, and resets what it does not name.The corners are drawn at the size the width gives, so a 48-pixel corner drawn 48 wide is the picture pixel for pixel, at 200% from its
@2xvariant. The picture replaces the border’s colours, and the border’s widths still decide the layout. While the picture loads, or when it cannot be read, the border is drawn from its colours. A border image is not clipped byborder-radius. Because it is a property like any other, a state’s rule swaps the sprite, as the:hoverrule above does.
clip-path keeps part of a box and drops the rest, its children included:
inset() with optional rounded corners, circle(), ellipse(),
polygon() and path(), in the border box or in the box named after the
shape (padding-box, content-box). A box name alone clips to that box. The
pointer finds the box only inside the shape.
.avatar { clip-path: circle(50%) }
.ticket { clip-path: inset(0 12px round 6px) }
.flag { clip-path: polygon(0 0, 100% 0, 85% 50%, 100% 100%, 0 100%) }
mix-blend-mode combines a box with what is drawn under it: multiply,
screen, overlay, darken, lighten, color-dodge, color-burn,
hard-light, soft-light, difference, exclusion and plus-lighter.
isolation: isolate keeps what blends inside a box from blending with what
is outside it. A clipped, blended or isolated box is drawn as a group, like a
box with opacity; mask-image and the hue family of blend modes are not
in the subset.
filter changes how a box and everything in it look, as one picture: blur(),
brightness(), contrast(), grayscale(), hue-rotate(), invert(),
opacity(), saturate(), sepia() and drop-shadow(), applied in the order
written. A drop-shadow() follows the shape of what is drawn, its rounded
corners and its transparent parts, where box-shadow follows the box. A
blurred or shadowed box draws past its edges by about three times the radius.
.disabled-card { filter: grayscale(1) opacity(0.6) }
.sticker { filter: drop-shadow(0 2px 3px rgb(0 0 0 / 35%)) }
backdrop-filter takes the same functions and runs them over what is drawn
under the box instead, inside its border and its rounded corners. The box
itself, its background, border and children, is drawn over the result as
usual, so a translucent background tints the frost:
.toolbar {
background: rgb(236 239 244 / 35%);
border-radius: 12px;
backdrop-filter: blur(24px) saturate(110%);
}
What is under the box is everything drawn before it in the window, or in the
group it is inside: a box with opacity, filter, clip-path,
mix-blend-mode or isolation: isolate keeps its frost to what is inside the
group, and so does a box with rounded corners that clips its children. The
frost follows the box’s opacity and transform. At the window’s edge the
edge pixels are repeated, so a bar along the edge is as frosted there as in
its middle. A blur reads past the box by about three times its radius, so a
change that close to a frosted box repaints the whole box.
A video or a 3D canvas is not drawn into the window’s picture, so it cannot be frosted. Over one, a frosted box shows its own background colour at full strength, the opaque fallback a frosted surface is designed with. Without a GPU the video’s own fallback picture is what is on screen, and it is frosted. A frosted box seen through another frosted box shows without its own frost.
Under @media (prefers-reduced-transparency: reduce), give the box an opaque
background and backdrop-filter: none.
Transform
panel.turned { transform: rotate(20deg) }
panel.grown { transform: scale(1.4); transform-origin: left top }
toast.entering { transform: translate(0, 16px) }
transform with translate, translateX, translateY, scale, scaleX,
scaleY, rotate, skew, skewX, skewY and matrix, and
transform-origin.
translate, rotate and scale are properties of their own as well:
translate: 0 -2px, rotate: 90deg (or z 90deg; no other axis), scale: 0.96 or scale: 1 0.5, each none by default. They apply before
transform, translate first, then rotate, then scale, about the same origin,
and each is set and animated by itself, so a hover can lift a card that a
keyframe is turning. transform-box says what the origin and a percentage
are measured against: border-box (and stroke-box and view-box, a box
being no SVG shape) or content-box (and fill-box), inside the padding.
Layout runs first and the matrix moves the result, so a transform costs no layout pass. Hit testing maps the pointer back through the same matrix, so a scaled button responds where it is drawn.
Transition and animation
button { transition: background-color var(--gb-motion-fast) ease-enter }
button:active { transition: background-color 0ms }
@starting-style { toast { opacity: 0; transform: translate(0, 16px) } }
@keyframes pulse { from { opacity: 0.4 } to { opacity: 1 } }
skeleton { animation: pulse 1.2s linear infinite }
transition and its four longhands, transition-property, -duration,
-timing-function and -delay; animation and its eight longhands:
animation-name, -duration, -timing-function, -delay,
-iteration-count, -direction -fill-mode and -play-state. The longhands are comma
lists that pair up by position with transition-property, the shorter lists
repeated, as CSS pairs them. transition: all names every animatable property,
and a later entry for one of them wins over it. transition-property starts
out empty rather than all, so a duration on its own animates nothing until a
property is named.
The animatable properties are a closed whitelist: opacity,
background-color, background-position, border-color, border-radius,
outline-color, outline-offset, box-shadow, color, transform,
translate, rotate and scale. Every one of them is drawn, never laid out,
so a frame of motion never runs layout. border-radius moves corner by
corner; a transform transition leaves the three individual properties where
they are.
Two shadow lists move pair by pair, the shorter one
padded with transparent copies of the longer one’s shadows; an inner shadow
against an outer one swaps half-way.
transition: width 200ms is a dropped declaration with a warning naming it,
because animating a width would run layout on every frame.
The timing that applies is the one on the style being moved to, so the
two button rules above make a press snap and a release fade.
The design system’s curves are ease-enter, ease-exit and linear, and the
toolkit’s own sheets use nothing else. An application’s sheet may write any
curve CSS has: ease, ease-in, ease-out and ease-in-out as CSS defines
them, cubic-bezier(), steps() with any of its positions, step-start,
step-end and linear() with its stops. A curve may overshoot, and an
animated opacity stays between 0 and 1 when it does. A timing function that
cannot be read, cubic-bezier(2, 0, 0, 1) or steps(0), drops itself with a
warning naming it, and the rest of the declaration runs on the default
ease-enter.
Colours interpolate in OKLCH. Animated values
live in an overlay applied at paint and are never written back into the
computed style, so a transition retargeted halfway starts from where it is.
transition does not inherit.
@starting-style gives an element the style it transitions from on its
first frame. @keyframes names a sequence animation runs under the same
whitelist. Under reduced motion every transition collapses to zero and
keyframe animations do not run.
The desktop’s setting is read at start-up, and
-Dgoldberry.motion.reduced=reduce or =full overrides it.
A keyframe may name its own animation-timing-function: the curve from that
keyframe to the next, in place of the animation’s. A @keyframes block may
sit inside @media; the last block of a name whose condition holds is the one
that runs.
animation-play-state: paused stops an animation’s clock where it is, and
running starts it again from there; a paused animation asks for no frames.
A theme is chosen by swapping a stylesheet. A media query adjusts an existing sheet to the window or the desktop.
A box with a view-transition-name that layout moves or resizes is drawn
where it was, and travels to where it is now:
call-tile { view-transition-name: tile-7; transition: transform 300ms ease-out }
The name is the box’s identity, so a tile moved into another column still
travels from where it was; give each box its own. The move takes the box’s
transition for transform when it has one, and 250 ms ease otherwise.
Under reduced motion the box moves at once. A box that changes size is
stretched while it travels, and whatever is inside it moves with it.
Media queries
@media (max-width: 900px) { .sidebar { width: 200px } }
@media (prefers-color-scheme: dark) { :root { --brand: #88c0d0 } }
@media (prefers-reduced-motion: reduce) { .pulse { animation: none } }
@media screen and (min-width: 600px) and (max-width: 1200px) { }
| Feature | Asked of |
|---|---|
width, height, as min-/max- or a range like (width >= 600px) or (400px <= width <= 800px) | the window’s logical size, in px, em or rem (16px) |
aspect-ratio, as min-/max- or a range, 16/9 or one number | the window’s width over its height |
orientation: portrait | landscape | the same |
resolution, as min-/max- or a range, in dppx, x, dpi or dpcm | the window’s scale |
pointer, any-pointer: none | coarse | fine; hover, any-hover: hover | none | a mouse, until the application says renderer.input(MediaContext.Input.TOUCH) |
prefers-color-scheme: light | dark | the desktop’s theme, light where it does not say |
prefers-reduced-motion: reduce | no-preference | the renderer’s reduced-motion switch |
prefers-contrast: no-preference | more | less | custom | the desktop’s contrast switch; custom while it forces its colours |
forced-colors: none | active | Windows’ high-contrast mode |
prefers-reduced-transparency: reduce | no-preference | macOS’s reduce-transparency switch |
color-gamut: srgb | p3 | rec2020 | srgb holds: everything is drawn to an sRGB surface |
A feature written alone, (hover) or (prefers-contrast), holds unless its
value would be the one that means none. The desktop’s switches are read once,
when the application starts: the settings portal on Linux, the system
parameters on Windows, the workspace on macOS. One a desktop does not have
reads as off.
They combine with and, or, not, only and comma lists, and nest. The
media types all and screen hold and print does not. A query naming
anything else never holds and warns once; in a strict sheet it is refused.
The cascade re-runs when an answer changes: on a resize that crosses a breakpoint, when the desktop’s theme changes, and when reduced motion is switched. A resize that crosses none keeps every resolved style.
@supports holds rules that apply when its condition does: (property: value) asks whether this toolkit reads that property and would apply that
value, selector(…) whether it reads that selector, and not, and and or
combine them as CSS says. The answer is about the toolkit itself, so it is
worked out once, when the sheet is loaded: @supports (display: grid) is
false here, and a fallback written beside it is what applies. Anything else in
parentheses, font-tech() included, is false. @supports may hold @media
and may sit inside a rule.
A box can be a container, which its descendants’ rules can ask about the way
an @media rule asks about the window: container-type: inline-size answers
for its width, size for its width and height, and container-name gives it
names an @container can ask for. The size asked about is the container’s
content box, inside its border and padding.
.card { container-type: inline-size; container-name: card }
@container card (min-width: 360px) {
.card-body { flex-direction: row }
}
.card-title { font-size: clamp(14px, 5cqw, 22px) }
A query takes the features and range forms a media query has for the
window’s size: width, height, inline-size, block-size, aspect-ratio
and orientation. It asks the nearest container that answers for the axes it
reads, and does not hold before that container has been laid out. cqw,
cqh, cqi, cqb, cqmin and cqmax are a hundredth of the nearest
container’s size, and of the window’s where there is none. A frame whose
containers changed size is laid out a second time, never a third, so a
container whose size depends on its own queries settles over the next frame.
Cursor
button { cursor: pointer }
.splitter { cursor: ew-resize }
canvas { cursor: crosshair }
Every keyword CSS has: default, pointer, text, move, wait,
progress, crosshair, not-allowed, the resizes (ew-, ns-, nesw-,
nwse-, col-, row-, and the eight edges and corners from n-resize to
sw-resize), grab, grabbing, help, context-menu, cell,
vertical-text, alias, copy, no-drop, all-scroll, zoom-in,
zoom-out and none, which hides the pointer over the box. Without a picture
from the application, a shape the platform has no cursor for falls back to the
nearest one it has: grab and grabbing to move, the edges and corners to
the two-headed arrows, cell and the zooms to the crosshair, and help,
context-menu, alias and copy to the arrow.
The cursor rides on the painted box and inherits down the stack of rectangles under the pointer, not the element tree.
Custom properties and var()
:root { --gb-accent: #b48ead; --gb-scroll-line: 40px }
#revenue { --gb-chart-1: #b48ead }
.hint { color: var(--gb-text-placeholder, #4c566a) }
A custom property is declared on any node and inherits. var(--name) reads
it, with an optional fallback after a comma. Every colour a control draws
comes through a --gb-* token, so an application rule that redefines one on
:root restyles every control that reads it, and one that redefines it on
#revenue restyles one chart. The tokens that exist are listed in
The design system.
Inheritance
color, the font properties, line-height, white-space, text-align,
text-decoration, overflow-wrap and word-break pass down the element
tree. The layout properties,
background, opacity, transform, transition and the border do not.
ComputedStyle.INITIAL has black text on purpose, so a window with no
stylesheet looks like one. Set color on your root, as the showcase does with
#root { color: var(--gb-text) }. A control that says nothing still reads
right because controls.css sets color on it.
Every property also takes inherit, initial and unset. inherit copies the
parent’s value, even of a property that does not inherit: padding: inherit
copies the parent’s four sides. initial is the property’s initial value,
and unset is inherit for a property that inherits and initial for one
that does not. all takes the three and applies them to every property at
once. revert rolls a property back to what the toolkit’s own sheets give it,
as if the theme and the application had said nothing about it, and
revert-layer to what the layers below the declaration’s give it. With
nothing to roll back to, either is unset.
Restyle versus repaint
A repaint redraws what changed. A restyle throws every resolved style away,
re-reads Application.stylesheets() and rebuilds the renderer. The second is
much more expensive, and almost nothing needs it: a theme and a density, and
very little else.
@Bind(value = "app.theme", restyle = true) private String themeName = "dark";
A field declared restyle = true asks for a restyle when it is assigned, and
the toolkit calls Host.restyle() for you. Everything else that changes a
value asks for a repaint by itself. An application outside the model system
calls host.restyle() directly.
A restyle is not a full recompute of every node. Each element caches its resolved style and re-resolves only when the resolver changed, when the style it inherits changed, or when a pseudo-class or a rebuild invalidated its subtree.
Themes, density and scrollbars
@Override public List<Stylesheet> stylesheets() {
var sheets = new ArrayList<>(Controls.stylesheets(
settings.theme(), // Theme.NORD_LIGHT or Theme.NORD_DARK
settings.density(), // Density.REGULAR or Density.COMPACT
settings.scrollbars()
)); // Scrollbars.OVERLAY or Scrollbars.ALWAYS
sheets.add(styles);
return sheets;
}
Controls.stylesheets(theme), (theme, density) and
(theme, density, scrollbars) return the base sheet, the theme, and whatever
the other two add, in cascade order. Theme.NORD_LIGHT and Theme.NORD_DARK
are the two themes that ship, and a theme is a custom-property layer: the
base rules never name a colour.
Density.COMPACT is a handful of tokens on :root, and every control is 28 tall
instead of 32 with nothing in your tree mentioning a height.
Density.REGULAR ships no stylesheet at all, because regular is what the
toolkit already is.
Scrollbars.ALWAYS reserves a 12 px gutter beside scrolling content.
Following the desktop
@Override public void start(Host host) {
host.systemTheme().ifPresent(this::follow);
host.onSystemThemeChanged(this::follow);
}
private void follow(SystemTheme theme) {
actions.pickTheme(theme == SystemTheme.DARK ? "dark" : "light"); // a restyle = true field
}
host.systemTheme() answers LIGHT, DARK, or empty where the desktop has
no such setting, and empty is a different answer from light.
The toolkit chooses nothing with the answer. A Linux build without the desktop bus
headers cannot ask at all, and says so through
Goldberry.capabilities().contains(Capability.SYSTEM_THEME).
Text scale
The renderer scales text between 90% and 150% without scaling the boxes, which
is the condition every control is built to survive.
The switch is WidgetRenderer.textScale(double), on the renderer an
application builds itself. The launcher does not expose it.
An application sets the scale its windows open at with textScale(), and
changes it while running with host.textScale(1.25): every window draws its
text at the new size from the next frame. The value is clamped to 0.9–1.5.
Offscreen.of(w, h).textScale(1.5) renders a tree at a scale for a test.
Read more
- Sizing with CSS: the layout half, in the Layout part
The design system
What every built-in widget is drawn to, as it is built: Nord's sixteen colours behind alias tokens, one type scale, a 4 px ramp, three motion durations, and the rules that keep them honest.
By the end of this chapter you know which --gb-* tokens exist and what each
is for, what the type classes measure, how big a control is at each density,
and what is not built.
Principles
- Desktop only. Pointer and keyboard first. Hit targets are 32 by 32 at regular density.
- Opaque first. Every surface is designed opaque. Frost is an enhancement layer, and it is not built.
- Token or extend. A screen that needs a value no token names extends the system rather than improvising.
- Keyboard complete. Every interaction is reachable without a pointer and
:focus-visibleis always legible. - Deterministic. Embedded fonts, CPU raster and token-driven colour: the same markup renders the same bytes on every machine, and golden images are the arbiter.
Colour
The raw palette is Nord, exposed as --nord0 to --nord15 in both themes.
Widgets never read the palette. They read alias tokens, and only the alias
tokens change between the two themes.
| Token | Hex | Token | Hex | |
|---|---|---|---|---|
--nord0 | #2E3440 | --nord8 | #88C0D0 | |
--nord1 | #3B4252 | --nord9 | #81A1C1 | |
--nord2 | #434C5E | --nord10 | #5E81AC | |
--nord3 | #4C566A | --nord11 | #BF616A | |
--nord4 | #D8DEE9 | --nord12 | #D08770 | |
--nord5 | #E5E9F0 | --nord13 | #EBCB8B | |
--nord6 | #ECEFF4 | --nord14 | #A3BE8C | |
--nord7 | #8FBCBB | --nord15 | #B48EAD |
The first four are Polar Night, the next three Snow Storm, then Frost, then Aurora. Aurora hues carry meaning: danger, warning, success, info and chart series. They are never decoration on a control.
Alias tokens
panel { background: var(--gb-surface); color: var(--gb-text); border: 1px solid var(--gb-border) }
| Token | Dark | Light | For |
|---|---|---|---|
--gb-bg | nord0 | nord6 | the window |
--gb-surface | nord1 | #ffffff | a panel, a card, a menu |
--gb-surface-2 | nord2 | nord5 | a second plate that is distinct, in no direction |
--gb-surface-raised | nord2 | #ffffff | one step up |
--gb-surface-sunken | black at 22% | black at 7% | a field’s well |
--gb-text | nord6 | nord0 | text |
--gb-text-muted | nord4 | nord3 | secondary text |
--gb-text-placeholder | nord6 at 60% | nord0 at 75% | a field’s placeholder |
--gb-border | nord3 | nord4 | a divider, a card edge |
--gb-border-strong | white at 20% | black at 16% | an edge that must read |
--gb-accent | nord8 | #5c7ea8 | the primary action, a selected tab |
--gb-focus | nord8 | nord10 | the focus ring |
--gb-selection | nord10 at 40% | nord8 at 30% | selected text and rows |
--gb-scrim | black at 55% | black at 40% | the veil behind a dialog or a tour |
A semantic hue has three ranks. --gb-danger is what danger is, a fill;
--gb-danger-fill is what you may put words on; --gb-danger-line is what
you may draw a glyph or a border with on a surface, and it clears 3:1 against
it. --gb-warning, --gb-success and --gb-info have -line ranks for
the same reason, and -text ranks for words on their fills.
Above the aliases sit component tokens: --gb-button-bg,
--gb-button-bg-hover, --gb-checkbox-mark-checked, --gb-toggle-track-bg,
--gb-slider-thumb-border, --gb-chart-1 to --gb-chart-8, and their kin.
An application may override component tokens, never structure. Every one is
listed in nord-dark.css with a comment saying why it exists.
Every text and surface pair in both themes clears 4.5:1, and every mark clears 3:1 against the box it is drawn in.
Spacing
The base unit is 4 px. The legal ramp is 2, 4, 8, 12, 16, 20, 24, 32, 40,
48 and 64, and nothing off it. Component padding is 8 or 12, the gap between
related controls 8, between groups 16, and the window’s content margin 16.
The ramp is a rule, not a set of tokens: a stylesheet writes gap: 8px.
Type
column {
text class="display" "Goldberry"
text class="title" "Preferences"
text class="heading" "Appearance"
text class="body" "Default UI text."
text class="body-strong" "Emphasis, and a button's label."
text class="caption" "Secondary metadata"
text class="mono" "goldberry.log.level=TRACE"
}
| Class | Face | Size / line | Tokens |
|---|---|---|---|
display | Inter 600 | 30 / 36 | --gb-font-display, --gb-line-display |
title | Inter 600 | 22 / 28 | --gb-font-title, --gb-line-title |
heading | Inter 600 | 17 / 22 | --gb-font-heading, --gb-line-heading |
body | Inter 400 | 15 / 20 | --gb-font-body, --gb-line-body |
body-strong | Inter 600 | 15 / 20 | the body tokens and --gb-weight-strong |
caption | Inter 400 | 13 / 16 | --gb-font-caption, --gb-line-caption |
mono | JetBrains Mono 400 | 15 / 20 | --gb-font-code, --gb-line-code |
The two weights are --gb-weight-regular at 400 and --gb-weight-strong at
600. Upright Inter and JetBrains Mono support variable weights. Inter ships
separate italic faces at 400 and 600. The numbers live in the theme, so a large-text theme moves
all of them at once. Text scale from 90% to 150% is a renderer switch beside
them, and scales the text without the boxes
(Text, fonts and icons).
Shape, elevation and materials
Radii are literals in controls.css: 4 on fields, text areas and the
checkbox glyph; 8 on buttons, cards, panels, toasts and messages; 12 on
dialogs; a full radius on badges, chips, progress bars, thumbs and step
markers.
Elevation is three shadow tokens, and a rule never writes the numbers:
card { box-shadow: var(--gb-elevation-1) }
dialog { box-shadow: var(--gb-elevation-2) }
| Token | Geometry | Dark alpha | Light alpha |
|---|---|---|---|
--gb-elevation-1 | 0 2px 8px | 44% | 16% |
--gb-elevation-2 | 0 8px 32px | 56% | 22% |
--gb-elevation-3 | 0 16px 48px | 68% | 28% |
The geometry is the same in both themes and the alpha is not, which is why
they are tokens. A card wears level 1 and lifts to 2 on
card.interactive:hover. Dialogs, toasts, tours, popovers and menus use level 2.
Tooltips use level 1. A popup can show a shadow when the desktop composites
transparent pixels. A desktop without a compositor sees square corners and a
panel without a shadow.
Level 3 is defined and used by nothing.
frost is backdrop-filter: blur(24px) saturate(110%) over the raised
surface at 78% (dark) or 72% (light). It falls back to the opaque raised
surface over a video or a 3D canvas on its own, and under reduced
transparency by a rule of the application’s. No component wears it by
default: a popup is a window of its own, with nothing under it to frost.
Icons
The bundled icon set: 1,870 icons on a 24 by 24 grid with a 2 px round-capped stroke,
compiled into goldberry-core as path data. Display sizes are 16, 20 and 24,
and an icon in a button’s lead slot is 16. An icon is tinted by color, like
text. An icon-only control needs an accessible name
(Text, fonts and icons).
Motion
button { transition: background-color var(--gb-motion-fast) ease-enter }
button:active { transition: background-color 0ms }
| Token | Value | For |
|---|---|---|
--gb-motion-fast | 100 ms | state feedback: hover, check, selection |
--gb-motion-base | 160 ms | component transitions: popover, tabs, toggle |
--gb-motion-overlay | 240 ms | overlays: dialog, toast |
Three easing curves: ease-enter decelerates, ease-exit accelerates,
linear is for continuous indicators. CSS’s ease, ease-out and
ease-in-out run as ease-enter and ease-in as ease-exit, so a
stylesheet written for a browser keeps its motion on the system’s curves
(Transition and animation). The rules are: input feedback is
instant and only its release fades; exits are faster than enters; the focus
ring is never delayed; nothing loops except a spinner, an indeterminate
progress and a skeleton; and under reduced motion every transition is zero
and keyframe animations do not run. The mechanics are in
Styling.
States
Every control renders rest, :hover, :active, :focus-visible and
:disabled, and where it applies :checked, :indeterminate and
:invalid. Hover moves the surface one step and never the text colour.
Disabled is 45% opacity on the whole control and never a colour remap, so a
disabled danger button still reads as danger.
Focus
button:focus-visible,
checkbox:focus-visible { outline: 2px solid var(--gb-focus); outline-offset: 2px }
One focus owner per window. The ring is 2 px of --gb-focus, 2 px outside
the control, following its radius, and it appears only for keyboard focus. It
is one rule over a list of types in the base layer, not one rule per control.
A composite is one Tab stop with the arrow keys moving inside it.
Keyboard conventions
host.shortcut(Shortcut.primary(Key.S), this::save); // Cmd+S on macOS, Ctrl+S elsewhere
host.shortcut("Primary+Shift+Z", this::redo);
Accelerators are written against the desktop’s primary modifier, which
has a name: Primary in a string, Shortcut.primary(key) in Java. It is
Cmd on macOS and Ctrl everywhere else, and nothing is translated: a
shortcut that says Ctrl means the control key on every desktop.
In a dialog Enter presses the affirmative action and Escape the
dismissive one, and the affirmative sits on the right. A button activates on
Space and Enter; a checkbox on Space only, so Enter still reaches the
form’s default action. Tab order is document order.
Density
| Regular | Compact | |
|---|---|---|
control height, --gb-control-height | 32 | 28 |
list row, --gb-list-row-height | 32 | 26 |
table header, --gb-table-header-height | 36 | 30 |
| code-input box | 40 by 48 | 36 by 44 |
| calendar day | 32 | 28 |
Density.COMPACT is those tokens on :root and nothing else. The 16 px glyph
inside a checkbox or a radio does not shrink, so compact costs margin around
the target rather than a smaller target.
Scrollbars
Overlay by default: a 6 px thumb over the content that widens to 10 px with a
track on hover, with no gutter reserved. Scrollbars.ALWAYS swaps in a
classic 12 px gutter with an 8 px thumb and a --gb-surface-2 track, and a
layout must survive the gutter appearing.
Component metrics
Heights at regular density, with compact in brackets, as controls.css sets
them.
| Component | Metrics |
|---|---|
button | height 32 (28); padding-x 12; icon gap 6; radius 8; body size at the strong weight |
text-input, select | height 32 (28); padding-x 8; radius 4; fill --gb-surface-sunken |
text-area | padding 6/8; radius 4 |
checkbox, radio | glyph 16; hit 32; label gap 8 |
toggle | track 36 by 20; thumb 16 |
slider | track 4; thumb 16 with a 1 px edge |
knob | 32 or 48 across |
menu row | height 32 (28); padding-x 8 |
tab | height 32 (28); padding-x 12 |
list row | height 32 (26); padding-x 12 |
table header | height 36 (30) |
badge | height 20; min-width 20; padding-x 4; full radius |
chip | height 24; padding-x 8; radius 12 |
progress | track 4; full radius |
card | padding 12; gap 8; elevation 1 |
panel | radius 8 |
dialog | padding 24; min-width 320; max-width 80%; radius 12; elevation 2 |
toast | width 360; padding 12/16; radius 8 |
tooltip | padding 8/12; radius 4; max-width 320 |
message | padding 12/16; radius 8; icon gap 12 |
steps marker | 24, full radius |
code-input box | 40 by 48 (36 by 44); radius 4 |
Accessibility baseline
Contrast clears its ratios in both themes. Every control is operable from the
keyboard, with the per-widget maps in each chapter. Text scales to 150%
without the boxes moving. Reduced motion is honoured. Hit targets are 32 at
regular density. Every focusable widget has a Role and an accessible name.
There is no screen-reader bridge. The toolkit builds a semantics tree, and nothing on any platform reads it.
Governance
The alias tokens, the component contracts and the metrics tables are the stable tier. A new widget comes with a specification, a metrics row and gallery coverage in both themes.
Read more
- Styling: the CSS that reads these tokens
Text, fonts and icons
Two embedded typefaces, an optional emoji face, bundled stroked icons, and an image that is a value: what an application needs from the text and picture stack, one sample each.
By the end of this chapter you can open a font and measure a string, ship a face of your own, name an icon from markup, draw emoji, put a caret on a canvas, and decode, scale, copy and encode an image.
try (var fonts = Fonts.bundled()) {
Font body = fonts.of(BundledFont.UI, 13);
double width = body.widthOf("Goldberry"); // what layout will ask
body.draw(frame, 16, 16 + body.ascent(), "Goldberry", 0xFFECEFF4);
}
The y of a draw is the baseline. The top of a line is
baseline - ascent().
Faces, fonts and the book
A FontFace is a typeface parsed once. A Font is one size of it. Fonts
is the book that caches both, keyed by family, weight and style, then by
size.
try (var face = FontFace.bundled(BundledFont.UI);
var title = Font.on(face, 24);
var body = Font.on(face, 16)) {
// two sizes, one parse of Inter
}
A second size over a shared face costs microseconds and no memory. The face
must outlive every font over it. Font.bundled(BundledFont.UI, 16) parses a
face of its own, which is right for exactly one size.
Shaping runs in the face’s own design units and the size is applied once, in
the font matrix, so a shaped run is correct at every size. Font exists to
make applying it twice unrepresentable.
A running application does not open a book of its own. The launcher opens one
and hands it to the renderer, and a widget asks Paints.Context.font(style)
for the font its resolved typography names. A canvas that measures its own
labels asks host.fonts().
The bundled faces
BundledFont | File | Family | Weight | Style |
|---|---|---|---|---|
UI | Inter variable | Inter | 400 | upright |
UI_STRONG | Inter SemiBold | Inter | 600 | upright |
UI_ITALIC | Inter Italic | Inter | 400 | italic |
UI_STRONG_ITALIC | Inter SemiBold Italic | Inter | 600 | italic |
CODE | JetBrains Mono | JetBrains Mono | 400 | upright |
EMOJI | Noto Color Emoji | Noto Color Emoji | 400 | upright |
A weight is a face and so is an italic: Inter’s italic is drawn, not
sheared, and font-weight: 600; font-style: italic resolves to a file rather
than to the nearer of three.
A weight is a CSS number, though, and a stylesheet may write any of them: the
face is chosen by CSS’s own nearest-weight rule over the faces the family has,
so over Inter’s two font-weight: 500 is the 400 and bold (700) is the 600,
as a browser draws them.
There is no variable wght axis: Inter’s 500 is not instanced from its
variable file, and an application that wants a 500 ships one. A glyph
neither family has draws .notdef: there is no fallback cascade beyond the
emoji slot, so font-family: Inter, sans-serif keeps the first name only.
Shipping a face
@Override public List<FontSource> fonts() {
return List.of(
forum(400, "fonts/Forum-Regular.ttf"),
forum(700, "fonts/Forum-Bold.ttf")
);
}
private static FontSource forum(int weight, String file) {
return FontSource.stream("Forum", weight, BundledFont.Style.UPRIGHT, () -> MyApp.class.getResourceAsStream(file));
}
Application.fonts() is read once, before start, when the window’s book
opens. A face named here reaches the cascade, paragraph layout, a field’s
caret and the glyph cache together, and a stylesheet names it with
font-family: Forum. The bundled families are searched first, so a file
called Inter cannot replace the face the design system was drawn against.
The weight is any CSS number, 1 to 1000. A family shipped at 500, 600, 700
and 800 gives each of them to the stylesheet that asks, and a weight it does
not have is the nearest one it does, by the rule Inter answers by. The two
named weights, Weight.REGULAR and Weight.SEMI_BOLD, are 400 and 600.
Read the file with your own code. The supplier in FontSource.stream is
the application’s lambda, so it reads a resource with the application’s own
access, and a modular application opens nothing for it.
FontSource.resource(family, weight, style, MyApp.class, name) reads it with
the toolkit’s module instead, and on the module path that needs the package
holding the file opened to dev.goldberry.core (opens com.example.app.fonts to dev.goldberry.core; for fonts/ beside com.example.app.MyApp). A
resource directory is a package of its own, so it is that package, not the
class’s, that has to be opened.
A missing file is said at start. The book looks for every file as it
opens, before the window shows: a resource or a stream is opened and closed
unread. One that is not there is a warning naming the face and why, a
package nobody opened told apart from a file that is missing, and text in it
is drawn in the UI face. Nothing is parsed until something is drawn in the
face. fonts.unreadable() lists them, for an application that would rather
refuse to start.
FontSource.of(family, weight, style, bytes) takes bytes already in hand.
A stylesheet may ship a face too, with @font-face:
@font-face {
font-family: "Forum";
src: url("fonts/Forum-Regular.ttf") format("truetype");
font-weight: 400;
}
A renderer adds the faces its sheets name to the window’s book when it is
built, as if Application.fonts() had answered them, and font-family: Forum then finds them. In a sheet read with Stylesheet.resource, src is a
file beside the sheet; otherwise it is a classpath: address or a file path.
TrueType and OpenType files are read; local() and WOFF are passed over for
the next source in the list. font-weight is a number, normal or bold,
and font-style is normal or italic.
Fallback faces
@Override public List<FallbackSource> fallbacks() {
return List.of(
FallbackSource.of(face("Noto Sans SC", "fonts/NotoSansSC-Regular.otf"),
UnicodeScript.HAN, UnicodeScript.HIRAGANA, UnicodeScript.KATAKANA
),
FallbackSource.of(face("Noto Sans Arabic", "fonts/NotoSansArabic-Regular.ttf"),
UnicodeScript.ARABIC
),
FallbackSource.of(face("Noto Sans Math", "fonts/NotoSansMath-Regular.ttf"))
);
}
private static FontSource face(String family, String file) {
return FontSource.stream(family, 400, BundledFont.Style.UPRIGHT, () -> MyApp.class.getResourceAsStream(file));
}
A name typed in a script the design system’s faces lack is drawn in the
first fallback that has its characters, at the size and on the line of the
text around it. Without one it is a row of .notdef boxes. A fallback is not
a family a stylesheet names: font-family: Inter stays Inter for every
character Inter has, and only the characters it lacks look further.
The face’s own cmap decides. Every face’s characters are read once, when
it opens, and a paragraph checks its text against them before shaping. Text
the face covers is shaped exactly as it was, and a paragraph with no
uncovered character never opens a fallback. The scripts after the source are
a hint read before the face is opened, so an Arabic name does not open a Han
face to learn that it has no Arabic. Characters in no script of their own,
such as punctuation, digits and the mathematical letters, are never ruled out
by a hint, and a source with no scripts is opened for anything.
A run stays whole. A letter and the marks on it go to one face, and a word of Arabic or a name in Han is shaped as one run, spaces included, so it joins and spaces as it should. Right-to-left text is still shaped in logical order and drawn mirrored, as in any other face.
The line is the font’s. Line height, ascent and underlines are the font’s that the stylesheet chose. A fallback glyph that is taller may reach past the line box, as it can in a browser. Carets, selection and clicks work across a fallback run as across any other.
Order, weight and style. Fallbacks are searched in the order given. Several
sources with one family name are one fallback at several weights, and bold
text takes the nearest weight by the rule font-family uses. Nothing is
emboldened or slanted by the toolkit: a family shipped only in regular draws
bold text in regular. An artifact can bring fallback faces as a
dev.goldberry.assets.FallbackFont provider, searched after the
application’s. A font collection (.ttc) is not read: ship one face of it.
A book opened by hand takes the list as Fonts.bundled(shipped, fallbacks).
Paragraphs
A paragraph has a base direction, and text in a right-to-left script is split
into runs that each read their own way, placed in reading order on every
line. Paragraph.of(font, text) takes each paragraph’s direction from its
first letter that has one; a widget’s paragraph takes its style’s direction
and unicode-bidi.
var label = Paragraph.of(font, "שלום, world", 0, 0, Directionality.RTL);
double x = label.caretX(line.start(), line.end(), offset); // where the caret is drawn
List<Stretch> lit = label.stretchesOf(line.start(), line.end(), from, to);
A width is the same whichever way the runs are placed, so widthBetween
sizes a box; where a caret or a highlight goes on a line is caretX and
stretchesOf, and offsetAt is the caret nearest a click.
Text scale
Text scales from 90% to 150% without the boxes around it moving, which is the condition every control is built to survive.
renderer.textScale(1.5); // clamped to WidgetRenderer.MINIMUM_TEXT_SCALE..MAXIMUM_TEXT_SCALE
The factor is applied where a resolved style becomes a Font, nowhere in
the cascade. It is a switch on WidgetRenderer, which the low-level path
builds itself. The launcher does not expose it.
Icons
row {
button icon="plus" press="app.create" "New"
button icon="palette" press="app.toggle-theme" "Switch"
}
@Override public void start(Host host) {
plus = Icon.bundled("plus", Icons.SLOT); // 16, a button's lead slot
icons = Icons.strict().bind("plus", plus).bind("palette", Icon.bundled("palette", Icons.SLOT));
}
The bundled icon set’s 1,870 icons ship in goldberry-core as path data on a 24 by 24 grid.
They are strokes, not fills: 2 px round-capped outlines, so an Icon carries
a stroke width as well as a shape, and it is built pre-scaled to one size so
nothing is transformed at draw time.
BundledAssets.iconNames() lists the set, and Icon.of(name, pathData, size)
builds one from your own SVG path data on the same grid. Icon.bundled throws
for a name the set does not have. Icon.find(name, size) returns an
Optional<Icon> instead, for a name that comes from outside the program.
Markup names an icon and never builds one. icon="plus" resolves against
the Icons registry the application owns, because a document reloaded on
every keystroke would otherwise rebuild one per reload. An Icon is an
immutable value, and its close() does nothing.
An icon is tinted by color, like text. Inside a widget that takes icon= it is
drawn at the size it was built at. The standalone icon
node is the other way round: the stylesheet sizes its box and the outline is
scaled to fit, so icon "plus" at 11 px and at 24 px is one line of CSS each.
It looks the name up in the registry first and then in the bundled set, so it
needs no registration. An icon-only button has an empty label and needs
name= for its accessible name.
Emoji
implementation 'dev.goldberry:goldberry-emoji:<version>'
Noto Color Emoji ships as its own artifact, because five megabytes of
paint graphs should not be inherited by an application that never draws one.
With the module on the path, nothing else changes: the itemizer splits an
emoji sequence out of a line and shapes it in the emoji face, and the rest of
the line stays in the family the cascade chose.
It is the COLRv1 build, drawn from its paint graphs, so an emoji is as sharp
at 400% as at 100%.
A stylesheet reaches the face by name as font-family: "Noto Color Emoji".
Without the module, Font.bundled(BundledFont.EMOJI, size) throws a
MissingEmojiFontException whose message names the artifact, and
BundledAssets.hasEmojiFont() answers false.
Selection and editing
text-input and text-area are controls. Underneath them is an Editor
that is none of those things, and it is reachable on its own: a caret in a
sticky on a board, a label on a shape, anything drawn on a canvas.
var editor = new Editor(font).multiline(true).wrapWidth(240).clipboard(host.clipboard());
new Canvas((frame, size) -> editor.paint(frame, 8, 8, Editor.Ink.of(ink, selection), focused),
new Input() {
@Override public boolean wantsText() { return true; } // turns the keyboard on
@Override public void onKey(KeyEvent e) { if (editor.onKey(e)) e.consume(); }
@Override public void onText(TextEvent e) { if (editor.onText(e.text())) e.consume(); }
@Override public void onPointer(PointerEvent e) {
if (e.kind() == PointerEvent.Kind.PRESSED) {
editor.pointerAt(e.content().x() - 8, e.content().y() - 8, false, e.clickCount());
}
}
});
wantsText() is not optional. The platform produces no characters until
something says it is being typed into, so an editor that has not said so gets
arrow keys and nothing else.
The editor is text-input’s key map, key for key: arrows and Ctrl+arrows,
Home and End on the visual line, Shift to extend, undo and redo with a
typing run folded into one step, and cut, copy and paste. A key it does not
handle is not consumed, so Tab still moves focus. TextGeometry beside it
answers where a caret is on a wrapped paragraph, what a click landed on, what
Up means when lines differ in length, and what shape a selection is across
a break. An input method’s composition arrives through onPreedit and is
drawn beside the document, not in it.
A text-area is also an editor. gutter=#true numbers the hard lines at
the positions the wrap put them, and .onEdit(...) and .edit(...) hand a
shortcut the caret as well as the text.
Tell an editor how tall its box is with viewportHeight and it scrolls: a
keystroke, a click or a drag that carries the caret past the box’s edge moves the
text by the least that shows the caret’s line, and paint draws from there,
clipped to the box. A wheel is scrollBy(dy), which answers whether anything
moved. Points stay in the text’s own space, so a pointer handler adds
scrollTop() to the pointer’s y before calling pointerAt.
(For book/src/guide/text.md, ## Selection and editing.)
Text can carry marks. A MarkedText is a string and its marks, each a kind
over a range; MarkedEdit is the same value with a caret, the marked twin of
TextEdit. Hand the canvas Editor a MarkStyles and it shapes marked words
in their own fonts and takes the formatting keys; without one it keeps the
marks and draws them as plain text.
Images
Image logo = Image.decode(Files.readAllBytes(file)); // or Image.decode(file)
frame.drawImage(logo, 16, 16); // natural size
frame.drawImage(logo, 16, 96, 240, 120, 0.4); // scaled, and faded
byte[] png = logo.scaled(64, 64).encodePng();
Encoded bytes become an Image: PNG, JPEG and QOI through the rasterizer’s
codecs, WebP through the native library, and GIF through a decoder written in Java. The
format comes from the bytes, never from a file name: ImageFormat.of(bytes)
says which. Image.decodeAnimation(bytes) returns every frame of an animated
GIF or WebP with its delay; decode returns the first.
An image has nothing to close. The decoder copies its pixels into a
Java-owned buffer before decode returns, so an image is a value to keep in
a field, a record or a cache. Natural size is one image pixel per device
pixel, so a 96 by 64 image is 96 logical points wide at 100% and 48 at 200%.
encodePng() writes one back out in java.base, and encodeWebp(quality)
through the native library.
In markup an image node takes src=, srcset=, alt=, decorative= and
fit=, and is in Canvas, images and QR codes.
Image.decodeInto decodes into memory the caller owns instead, such as a GPU
transfer buffer or an atlas page being built, and returns the size. The
function is asked for the memory once the size is known. ChannelOrder.RGBA
swaps red and blue in the same pass; BGRA is an image’s own order. Both are
premultiplied.
var size = Image.decodeInto(bytes, ChannelOrder.RGBA,
decoded -> PixelTarget.packed(transfer.map(decoded), decoded.width()));
The clipboard
Image.fromClipboard(host.clipboard()).ifPresent(board::add); // Ctrl+V
picture.toClipboard(host.clipboard()); // Ctrl+C
Underneath is Clipboard’s other half, has, read and write over a
MIME type. One write offers several types in order, so pasting into your
own application keeps a document’s format and pasting into a chat gets a
picture. A write is an offer: the platform asks for the bytes when somebody
pastes.
Subscription watching = host.clipboard().onChange(() -> paste.disabled(!host.clipboard().hasText()));
onChange says that the clipboard changed, whoever changed it, your own
copies included. It does not say what to: ask hasText() or types(). A
platform that cannot tell never calls it.
A picture with no window
byte[] png = Offscreen.of(1200, 900) // physical pixels
.scale(1.5f)
.stylesheets(Controls.stylesheets(Theme.NORD_DARK))
.render(new DocumentPreview(document)) // or .paint(painter)
.encodePng();
Offscreen runs the window’s own sequence with no display, no windowing
layer and no compositor: mount, lay out, tell each widget what size it came out as,
advance a virtual clock past the arrival transitions, and paint what settled.
Two renders of one document are the same bytes. It is what
Testing an application builds on.
Words in the user’s language
dev.goldberry.i18n has CLDR’s plural rules for every locale and ICU’s
message syntax, so a count reads right in any language:
var files = IcuMessage.parse(
"{count, plural, one {# файл} few {# файла} many {# файлов} other {# файла}}"
);
files.format(Locale.forLanguageTag("ru"), Map.of("count", 21)); // "21 файл"
PluralRules.of(Locale.ENGLISH, PluralType.ORDINAL).select(22); // TWO: "22nd"
A message takes {name}, {name, number}, plural and selectordinal
with =0 cases, offset: and #, and select. Every plural and select
needs an other case, and a message without one is refused when it is
parsed.
The toolkit’s own words, a text field’s Cut, Copy and Paste and the names a screen reader hears for close and dismiss buttons, are English until an application gives it a translation:
Labels.use(ResourceBundle.getBundle("app.messages", locale));
// app/messages_ru.properties: goldberry.copy=Копировать
Each ToolkitLabel names its key. A word the bundle lacks stays English.
Call it again when the user switches language, and restyle so open menus
are rebuilt.
Read more
- Text and links: the
textandlinkwidgets
Input and focus
Pointer, wheel and keyboard events route through one router that remembers who is hovered, pressed and focused, against the frame the user is looking at.
By the end of this chapter you can bind an accelerator, make a composite one Tab stop, read a drag without remembering where it started, take a dropped file, open a context menu from the keyboard, and know what a custom widget implements to take part.
@Override public void start(Host host) {
host.shortcut(Shortcut.primary(Key.S), this::save); // Cmd+S or Ctrl+S
host.shortcut("Ctrl+Shift+Z", this::redo);
host.window().onFileDrop(drop -> open(drop.first(), drop.at()));
Menus.contextMenus(host, Map.of("rows", rowMenu()));
}
How an event travels
Dispatch is capture, then target, then bubble. A Handles widget sees the
event in onPointerCapture root-first, then the deepest node under the
pointer sees it in onPointer, then each ancestor does. consume() stops it
at any step. The target stays the same through all three phases, so an
ancestor can tell what happened to it from what happened below it.
The router holds what input has to remember between frames against
elements, because a widget is rebuilt constantly and could not remember
any of it. :hover, :active, :focus and :focus-visible are set on
elements by the router, which is why they survive a rebuild.
Hit testing runs against the snapshot taken while painting, not a fresh layout pass. A pointer event is about what the user can see, and that is the last frame drawn. A transform the painter applied is inverted once, from the very matrix the rasterizer used, so a scaled control responds where it is drawn.
Kinds
PointerEvent.Kind | When |
|---|---|
MOVED | the pointer moved with no button change |
PRESSED, RELEASED | a button went down or came up, with button() and clickCount() |
ENTERED, EXITED | synthetic, derived from pointer flow |
CLICKED | synthetic: a press and its release both landed on this node |
WHEEL | the wheel turned or a touchpad scrolled |
A press that is dragged off and let go elsewhere still releases, so the captor can stop looking pressed, and is not a click. Cancelling a click by dragging off is a gesture people rely on.
A secondary or middle press released over the same node without dragging
produces AUX_CLICKED. Read button() to distinguish them. A pinch gesture
reports PINCH, a factor from scale(), and a pinchPhase() of BEGAN,
CHANGED or ENDED. On platforms that report touchpad zoom as wheel input,
the event carries the Control modifier.
Click handlers
Any widget takes a click handler, with no wrapper around it:
new Panel(row).onClick(event -> select(row, event.button(), event.local().fractionX()))
It hears clicks of every button, with the position as a fraction of the
node’s own box. It consumes the click, so an ancestor’s handler does not run
too, and a control inside the node that takes the click keeps it. A node with
only a click handler is not a keyboard control: for one a keyboard must
reach, use pressable or button.
A press captures the pointer
A press takes an implicit capture until the release, so a drag that leaves a
widget still reaches it and :active cannot get stuck. That is what makes a
slider work.
:hover keeps following the pointer regardless: capture decides who is
told, not what is highlighted. router.capturePointer(element) takes a
capture that outlives the release, for the rare widget that needs one.
Gestures: where the drag started
@Override public void onPointer(PointerEvent event) {
if (event.kind() == PointerEvent.Kind.MOVED && !Float.isNaN(event.dragX())) {
var fraction = event.local().fractionX(); // 0..1 along my own box
onChange.accept(min + fraction * (max - min));
}
}
A widget is a value rebuilt every frame and cannot remember where a drag
began. The router can, and reports it on every event of the gesture:
pressX() and pressY() are where the button went down, and dragX() and
dragY() are how far the pointer has travelled since, NaN when no button
is held.
local() is the pointer in the widget’s own box, with fractionX() and
fractionY() clamped to 0..1. A control whose hit target is bigger than
the thing being pointed along, a slider with a readout beside its track, names
the part to measure against with Handles.localPart(). A
control whose drag is a rate rather than a position, a knob, answers
gestureAnchor() once on the press and gets it back as anchor() on every
event after. A canvas reads content() instead of local(): it is
measured from inside the padding, where the painter draws.
A drag held at the edge of a viewport carries the viewport on, and the selection with it.
The wheel is lines
@Override public void onPointer(PointerEvent event) {
if (event.kind() == PointerEvent.Kind.WHEEL) {
scrollBy(event.deltaY() * lineHeight);
event.consume(); // and the page behind does not lurch
}
}
Wheel deltas are in lines, fractional, positive down and right. A touchpad
sends a fraction of a detent per frame and the fraction is preserved in
deltaY(), and a mouse’s whole detents are in ticksY().
Natural scrolling and the windowing layer’s away-from-the-user sign are both
undone at the boundary, so a widget never sees either. --gb-scroll-line in the theme
says how far one line moves a viewport.
Keys and text are different events
A KeyEvent is a key going down or up, with its Key, its Modifiers and
whether it is a repeat. A TextEvent is committed text: what the platform’s
compose and input method produced, which for anything but a Latin keyboard
is not a key at all. One character can take several keystrokes.
A widget that wants what the user typed implements onText, and says so
with wantsTextInput(). That is what turns the platform’s text input on,
and the input method with it; a board that only wants arrow keys leaves it
off. A field that handles a key consumes it, and a key it does not handle
goes on, so Tab still moves focus.
Accelerators
host.shortcut(Mod.CTRL.and(Key.T), actions::toggleTheme); // enums: cannot be misspelled
host.shortcut("Primary+S", this::save); // the desktop's own modifier
host.removeShortcut("Primary+S");
An accelerator is per window and fires after the focused widget has
declined the key, so a text field keeps its own Ctrl+A. The modifiers must
match exactly: Ctrl+S does not fire on Ctrl+Shift+S. A string that names
no key throws at the call.
Primary is the desktop’s own modifier: Cmd on macOS and Ctrl
everywhere else. Shortcut.primary(Key.S) builds it in Java, and Mod,
CmdOrCtrl and Primary all spell it in a string. Nothing else is
translated: a shortcut that says Ctrl means the control key on every
desktop, which is what a terminal or an Emacs-bound editor needs.
-Dgoldberry.input.primary=ctrl or =meta overrides the answer, so a test
can press the same modifier on every desktop.
A widget that binds keys while mounted, a menubar, passes itself as the
owner and gives them back with removeShortcut(shortcut, owner), so an
unmount cannot take a binding somebody else made.
A held key repeats, and an accelerator fires on each repeat unless its
binding says otherwise. A toggle says so, or holding Escape opens and closes
a menu at the platform’s repeat rate:
host.shortcut(Shortcut.of(Key.ESCAPE), menu::toggle, Repeat.IGNORE); // once per press
host.shortcut(Mod.CTRL.and(Key.Z), history::undo); // repeats while held
Repeat.FIRE is what every other form binds. A repeat that an IGNORE
binding declines is still its key: it does not reach focus navigation or the
focused widget. In an offscreen session, session.hold(Key.ESCAPE, 3)
presses the key, repeats it three times and releases it.
Global shortcuts
An accelerator fires while a window has the keyboard. A push-to-talk key, a mute key or a “show the window” key has to work while another application has it, so it is asked of the desktop instead, and the desktop may say no:
var shortcuts = GlobalShortcuts.open();
shortcuts.bind(
List.of(
GlobalShortcut.of("talk", "Push to talk", "Ctrl+Alt+T"),
GlobalShortcut.of("mute", "Mute the microphone", "Ctrl+Alt+M")
),
event -> {
switch (event.id()) {
case "talk" -> microphone.open(event.isPress());
case "mute" -> { if (event.isPress()) microphone.toggleMute(); }
default -> {}
}
}
)
.thenAccept(grants -> grants.forEach(settings::show));
The answer is a Grant per shortcut, in the order asked:
| Grant | Means |
|---|---|
Granted(id, trigger) | its presses and releases will arrive; trigger is the combination in the desktop’s words |
Refused(id, DENIED, …) | the user said no |
Refused(id, TAKEN, …) | another application holds the combination |
Refused(id, UNMAPPABLE, …) | the key has no code here: Menu on a Mac |
Unsupported(id, …) | this desktop has no way to ask |
Show the answer where the shortcut is configured. A shortcut the user turned down, or that another application holds, is not one to tell them to press.
How each desktop is asked:
| Desktop | Asked through | Notes |
|---|---|---|
| Wayland | the desktop’s GlobalShortcuts portal | the desktop shows the user a dialog, and the user may choose another trigger; the trigger granted is the one they chose. The application’s desktop entry id (-Dgoldberry.desktop.id, as for notifications) is the name the desktop lists the shortcuts under |
| X11 | a key grab on the root window | whichever client grabbed the combination first keeps it; Caps Lock and Num Lock do not matter |
| Windows | RegisterHotKey | whichever application registered it first keeps it |
| macOS | Carbon’s RegisterEventHotKey | no Accessibility permission is asked for; open the shortcuts on the UI thread |
A Wayland desktop gives no application the keyboard while another has focus,
so there the portal is the only way, and a desktop whose portal has no global
shortcuts answers Unsupported for each.
Press and release
The listener hears each granted shortcut go down once and come up once. A held key’s repeats are not passed on, so a push-to-talk opens on the press and closes on the release. On Windows the release is noticed within 20 ms, because Windows reports only the press. Binding again, or closing, releases whatever is held first, so the microphone never stays open because its release can no longer come.
bind replaces the shortcuts bound before; an empty list unbinds them all.
Close the shortcuts when the application ends:
@Override public void stop() { shortcuts.close(); }
Opened on the UI thread, the listener and the answer run on the UI thread.
GlobalShortcuts.open(executor) delivers both to an executor of the
application’s choosing.
In tests
GlobalShortcuts.simulated() grants what it is asked, except what the test
refuses, and presses what the test says:
var shortcuts = GlobalShortcuts.simulated().refuse("mute", Grant.Reason.TAKEN);
var call = new Call(shortcuts); // binds "talk" and "mute"
shortcuts.press("talk");
assertTrue(call.microphoneOpen());
shortcuts.release("talk");
assertFalse(call.microphoneOpen());
Focus
One focus owner per window. Focus moves by a press and by Tab and
Shift+Tab in document order, and host.focus(id, fromKeyboard) moves it
from Java: a dialog putting the caret in its first field, a form jumping to
its first error. It is refused when the node cannot take focus, is disabled,
or is outside a modal that is open.
:focus is true however focus arrived. :focus-visible is true only for
keyboard focus, and the ring is drawn on that one, so a button clicked with a
mouse gets no ring. Handles.onFocusChanged(focused, fromKeyboard) tells a
widget the same thing, and onFocusWithin tells a container when focus
enters or leaves its subtree as a whole.
A composite is one Tab stop
@Override public FocusScope focusScope() {
return FocusScope.VERTICAL; // Up and Down rove; Left and Right are mine
}
A radio group, a tab list, a menu or a toolbar is one Tab stop, with the
arrow keys moving focus inside it. The group says
which arrows rove: HORIZONTAL, VERTICAL, or BOTH for a group whose
direction is the stylesheet’s, which is what radio-group answers. Home
and End reach the ends of any scope. Traversal enters at the descendant
matching :checked, or the first one, so the selection is the roving
position and there is no second piece of state to disagree with it.
The cursor
button { cursor: pointer }
.splitter { cursor: ew-resize }
host.window().cursor(Cursor.WAIT); // or decide it yourself
The cursor is a property of the painted rectangle, set from CSS or from
code, and it inherits down the stack of rectangles under the pointer rather
than the element tree. cursor: pointer on a button therefore covers the
label inside it. During a drag the shape stays the one the drag began with,
whatever is under the pointer. The one exception is the box holding the
pointer: when its own cursor changes in a frame painted during the drag,
the pointer takes the new shape. That is how a card that says grab shows
grabbing once it is lifted.
An application can draw its own shapes. Application.cursors() gives a shape
a picture at each size it was drawn, each with its hot spot:
@Override public List<CursorImage> cursors() {
return Stream.of(32, 48, 64, 96)
.map(size -> new CursorImage(Cursor.GRAB,
Image.decode(read("cursors/grab-" + size + ".png")), size * 3 / 8, size / 8))
.toList();
}
The shapes stay CSS’s, so cursor: grab in a stylesheet and a link’s own
pointer show the application’s picture without naming it, and a shape with
no picture is the platform’s. The smallest size is the shape at 100%, and the
toolkit shows the one the display’s scale wants. Without a picture, grab
and grabbing fall back to move.
Dropped files and text
host.window().onFileDrop(drop -> {
for (var path : drop.paths()) { board.add(path, drop.at()); }
});
host.window().onTextDrop(drop -> note.append(drop.lines()));
A desktop reports a drop as a beginning, a position, one event per file and
an end. The toolkit reassembles that into one FileDrop carrying every path
and the point it landed on, in the window’s logical coordinates, because a
board needs to know where. Both
listeners return a Subscription to close when a widget that listened
leaves the tree.
Dragging between widgets
new Card(ticket.title()).draggable(ticket);
new Column(cards).dropTarget(
payload -> payload instanceof Ticket,
drop -> board.move((Ticket) drop.payload(), status)
);
draggable(payload) and dropTarget(accepts, onDrop) are attributes, so any
widget can be either. The router does the rest. A press on a draggable
becomes a drag once the pointer has moved four logical pixels with the button
down, so a press that does not move is still a click. A control inside the
draggable that consumes its press keeps it: a slider in a draggable card drags
its thumb, and the card is picked up from anywhere else.
While the drag lasts, the source’s own box follows the pointer, faded, drawn
over everything and invisible to the hit test. The router looks for a target
under the pointer: the nearest node up the tree that carries a drop target
whose accepts says yes, skipping the source and what is inside it. That
node matches :drag-over. A target that refuses is passed over and gets no
:drag-over. Letting go over an accepting target calls its onDrop with a
Drop: the payload, and the point measured from the corner of the target’s
content box. Letting go anywhere else, or pressing Escape, puts the drag
back. A press that became a drag is not a click wherever it is let go.
DropTarget carries two more hooks for a target that draws where the drop
would land, as a canvas does:
var target = DropTarget.of(payload -> payload instanceof Event, drop -> week.move((Event) drop.payload(), drop.at()))
.whileOver(drop -> week.showSlotAt(drop.at()))
.onLeave(week::hideSlot);
new Canvas(week::paint).dropTarget(target);
whileOver hears every move, and onLeave hears the drag leave, land or be
put back. For a canvas the point is in the painter’s own coordinates.
From the keyboard, Space on a focused draggable picks it up when something
in the window accepts it. The arrow keys and Tab step between the targets
that accept it, in document order, Space or Enter drops it at the centre
of the one it is over, and Escape puts it back. Drop.fromKeyboard() tells
the two apart. Space is taken before the focused widget hears it, so a
draggable pressable is lifted by Space and activated by Enter.
The payload is the object itself and stays in the application. A drag
cannot cross into a popup, and it leaves the window only when the draggable
has a dragOut offer, which the next section is about.
session.drag("card", "done") carries one in a test.
Dragging out of the window
new Card(frame.title())
.draggable(frame)
.dragOut(() -> DragOffer.image(frame::png).withFiles(frame.exportedPath()))
.onDragOutEnd(outcome -> {
switch (outcome) {
case DragOutcome.Delivered _ -> status.show("Sent to another application");
case DragOutcome.Landed _ -> {}
case DragOutcome.Cancelled _ -> status.show("Not sent");
}
});
A draggable that also has a dragOut offer is the desktop’s own drag once
the pointer has moved four logical pixels with the button down. It can be let
go in a file manager, a browser, a mail client or an editor, which take what
the offer carries. The desktop draws the picture under the pointer: the source
as it was painted, faded, held where the press took hold of it, unless the
offer gives one of its own with withPicture.
An offer is any mix of five kinds, each named the way the desktop expects:
| Offer | Carried as |
|---|---|
files(paths) | the files themselves, which must exist when the drag starts |
link(uri) | a link, and its text |
text(string) | text |
image(png) | a PNG image, and the same image as a PNG file for the targets that take only files |
data(mime, bytes) | bytes under a type the application names |
dragOut takes a supplier, asked once when a drag starts, so a widget that
is built often and dragged rarely pays nothing for its offer. Everything but
the paths is a supplier too, asked for when a target takes it: an image that
is never dropped anywhere is never encoded. Suppliers run on the UI thread.
The target picks what to do with the drag from the operations the offer
allows, COPY alone unless allowing says otherwise, and the user steers the
pick with the desktop’s modifier keys. The toolkit never deletes anything: a
source that hears MOVE decides what moving means.
onDragOutEnd hears how it ended, once:
| Outcome | Means |
|---|---|
Delivered(operation) | another application took it; operation is what it says it did, or null where the desktop does not say |
Landed(accepted) | it was let go over one of the application’s own windows; accepted says whether a drop target there took it |
Cancelled() | it was put back: Escape, a release over nothing that takes it, or a target that refused it |
Over the application’s own windows the drag is still an in-app drag. Drop
targets light up with :drag-over and hear whileOver as before, and a drop
there delivers the payload itself, not a FileDrop of the application’s own
files. The window that started the drag keeps painting while it lasts.
A draggable with no offer stays inside its window, and so does every drag
made from the keyboard. Where the desktop will not start a drag, the gesture
goes on as an in-app drag from where the pointer is, and onDragOutEnd hears
nothing. A test session is such a place: session.drag("frame", "bin")
carries a draggable with an offer onto a drop target like any other.
| Desktop | Notes |
|---|---|
| X11 | the pointer keeps its arrow during the drag, and no picture follows it; data larger than the display server takes in one request is refused |
| Wayland | an offer of a type of the application’s own, with no file and no text beside it, is not seen by the application’s own drop targets while it is out |
| Windows | the drag runs inside a loop of the desktop’s; the window’s posted work, timers and frames run in turns inside it |
| macOS | files go as file URLs, everything else is made when a target asks for it |
Context menus
panel id="company" context-menu="rows" {
text "Frodo Baggins"
text "Samwise Gamgee"
}
Menus.contextMenus(host, Map.of("rows", rowMenu()));
context-menu="rows" on any widget names a menu. A right-click, the Menu
key or Shift+F10 on the focused widget finds the name by walking up from
what is under the pointer, and hands it to the one handler the application
registered with the point it happened at. What the name means is the
catalogue’s, which is why Menus.contextMenus is the line that turns a name
into a menu.
Bare F10 is the menu bar’s.
A widget can also have a menu of its own, which it opens without a name:
text-input and text-area open Cut, Copy, Paste and Select all. At each
widget on the walk a name comes first and the widget’s own menu second, so a
field you gave a context-menu= opens yours, and a field inside a panel that
named one opens its own. A custom widget offers one by implementing
ContextMenuOwner; answering false passes the click on to the widgets above.
What a custom widget implements
A widget takes part in input by implementing Handles. Everything on it has
a default, so a widget overrides what it uses.
| Method | For |
|---|---|
onPointerCapture, onPointer | the pointer, root-first and then deepest-first |
onKeyCapture, onKey | keys, the same two phases |
onTextCapture, onText, onPreedit | committed text, and an input method’s composition |
isFocusable() | whether Tab stops here. False by default |
focusScope() | whether the descendants are one Tab stop, and which arrows rove |
onFocusChanged, onFocusWithin | focus arriving at this node, or anywhere in its subtree |
wantsTextInput() | whether the platform’s text input is on while this has focus |
localPart() | the part local() is measured against, as a CSS type name |
gestureAnchor() | a number to remember for the length of a drag |
caretArea(), caretOffsetIn(area) | where the caret is, for the input method’s candidate window |
A canvas takes the same facts through its own Input, with onPointer,
onKey, onText, onPreedit and wantsText(), and it is focusable exactly
when it has one. The whole contract is in
Writing a widget.
Windows, popups and the host
An application is one class with a root widget. The launcher owns the window, and everything the application may ask of it is a method on Host.
By the end of this chapter you can run an application and know what runs when, open a popup that leaves the window and an overlay that does not, follow the desktop’s theme, go fullscreen, set an icon, put the window back where the user left it, open a second window, and do work off the UI thread and come back.
public final class Hello implements Application {
private Host host;
@Override public String title() { return "Hello"; }
@Override public LogicalSize size() { return new LogicalSize(960, 640); }
@Override public LogicalSize minimumSize() { return LogicalSize.of(480, 320); }
@Override public void start(Host host) {
this.host = host;
host.shortcut(Shortcut.primary(Key.Q), () -> host.window().close());
}
@Override public Widget root() {
return new Column(new Text("Hello").id("greeting"), new Button("Close", Goldberry::stop));
}
public static void main(String[] args) {
Goldberry.launch(new Hello(), args);
}
}
The lifecycle
Goldberry.launch(application, args) takes over the calling thread as the
UI thread and returns when the window has closed. In order:
title(),size(),minimumSize(),maximized(),position(),display()andicon()are read and the window is opened, hidden, put where it was asked, and then shown.fonts()is read and the font book opens.stylesheets()is read and the renderer is built.start(host)runs. Open what has aclose()here, bind accelerators, keep theHost.root()is called once, and the element tree mounts it. Every later rebuild comes from asetStateinside it, or from a@Bindfield that moved.- The frame loop runs, idle whenever nothing is happening.
- After the loop ends: the tree is unmounted, the render tree closed,
stop()runs, then the font book closes and the runtime shuts down.
stop() closes what start opened, in reverse. The launcher closes what the
launcher opened and nothing else: it cannot know that an Icon in a field is
still referenced by a widget that has not been collected.
Everything on Application but root() has a default, so the smallest
application is one method. models() is the wiring for a document’s names
and for repaints, and is the subject of
Building an application.
| Method | Default | What it means |
|---|---|---|
size() | 960 by 640 | what the window restores to when un-maximized |
minimumSize() | no minimum | the window manager stops the drag at the floor, and the application never clamps a frame |
maximized() | false | a state the desktop owns, not a large size: it snaps to the work area and restores to size() |
position() | the platform’s choice | where the window’s top-left opens, clamped onto a display that exists (Where a window opens) |
display() | none | the name of the display to open centred on, and the fallback for a position on no display |
icon() | the platform’s generic icon | several sizes of one Image; the backend picks which the platform scales from |
fonts() | the bundled faces | faces the application ships (Text, fonts and icons) |
Goldberry.launch(app, args) reads four flags from the array and ignores
everything else: --frames=N paints that many frames and exits,
--size=WxH overrides the opening size, --resize=WxH walks the window’s
size a pixel a frame, and --late-budget=N makes a run that misses more
than N refreshes exit non-zero. They exist for an automated run, and
Goldberry.launch(app) passes none.
The host
Host is handed to start and is the only handle an application needs.
It is confined to the UI thread, except repaint().
| Method | What it does |
|---|---|
title(text) | sets the window’s title |
repaint() | asks for a frame. Coalesced, and safe from any thread |
restyle() | re-reads stylesheets() and rebuilds the renderer. What a theme switch is (Styling) |
shortcut(...), removeShortcut(...) | window accelerators (Input and focus) |
overlay(widget, corner), fill(widget) | floats a widget over the content, in a corner or over everything |
popup(...), tooltip(...), attachedPopup(...) | opens a widget tree in a platform window of its own |
anchor(id) | the painted rectangle of the node with that id, from the last frame |
focus(id, fromKeyboard) | moves keyboard focus |
after(delay, action) | runs on the UI thread after a delay, on the frame loop’s own timer |
clipboard(), primarySelection() | the session’s clipboard, and X11’s middle-click buffer where there is one |
fileDialog(spec, onChoice), fileDialogs() | the platform’s open, save and folder dialogs |
tray(spec) | an icon in the notification area, or empty where the desktop has none |
systemTheme(), onSystemThemeChanged(listener) | the desktop’s light-or-dark setting |
reducedMotion() | whether the desktop asks for less movement |
openExternal(url) | hands a URL to the desktop’s browser or mail client |
webView(spec), embeddedWebView(spec, bounds) | a web page in a window of the engine’s own, or inside this one where the window system allows it |
canFullscreen(), isFullscreen(), setFullscreen(on), onFullscreenChanged(listener) | fullscreen |
frames() | what the frame loop has been managing lately |
fonts() | the renderer’s font book, for a canvas measuring its own text |
clock() | the clock frames are timed against. Virtual in a test |
onContextMenu(handler) | what a context-menu="…" right-click opens |
displays() | the displays connected now, the primary one first (Displays) |
openWindow(spec, root) | a second top-level window with a tree of its own (More than one window) |
window() | the Window, for the close hook, the cursor, position, attention, resize and scale notifications |
window() is an escape hatch and is named as one. Reaching for it is a
signal that something belongs on Host instead.
host.capture(path) writes what the window shows now, GPU layers included, to
a PNG: what a “report a problem” button attaches.
Overlays and popups
Something can open over a window in two places, and they are different things.
In the window
Overlay hud = host.overlay(Hud.stages(), Corner.BOTTOM_END);
// ...
hud.remove();
An overlay is a sibling of the application’s root, painted after everything
and taking no space from anything. Every window has an overlay layer from its
first frame, so adding one never re-parents the application and a toast
cannot cost the tree its state. Corner is TOP_START, TOP_END,
BOTTOM_START or BOTTOM_END, and a third argument sets the margin from the
edges instead of Overlay.WINDOW_MARGIN. host.fill(widget) covers the whole
window, which is what a tour’s veil and a dialog’s scrim are. A
Dialogs.show(host, dialog) and a Toasts.at(host, controller, corner) are
this call with a widget the catalogue wrote.
Each overlay is its own node, told apart by its Overlay handle and never by
what its widget looks like. Two equal widgets shown at once are two nodes, and
one shown in the same turn another was removed starts with fresh state.
A widget on the layer finds its own handle with
WindowRoot.overlayOf(context).
remove() takes an overlay away at once. dismiss() takes it away the way its
widget leaves: a dialog fades out first and is removed when the fade is over.
An overlay whose widget has no exit is removed at once by either call. Both are
idempotent.
In a window of its own
Optional<Popup> menu = host.popup(new Menu(items), "menu-button", Placement.BELOW);
A popup is a real platform window, parented to this one and free of its
bounds. A dropdown near the bottom of a window is routinely taller than the
space under its button, and an in-window overlay would be clipped. The
content is measured with no surface, placed by Placement against the
anchor with a flip if it would not fit and a shift to stay inside the
display’s work area, and then opened. Placement.BELOW, ABOVE and
AFTER ship, with .gap(px) and .align(...) on each. By id, the popup
follows its anchor when the window moves; by rectangle, it opens where the
rectangle was.
A popup is light-dismissed by default: a press anywhere in the owning window,
or Escape, closes it. popup.close(), isOpen(), lightDismiss(false),
takesFocus(false) and content(widget) are on the handle.
Important
Optional.empty()is a normal answer. Popup support belongs to the video driver, and thedummydriver has none. A caller that gets empty falls back to an overlay at the cost of being clipped to the window.Menus.open(host, "menu-button", menu)does the measuring, placing, opening and the submenus for aMenu.
Where the desktop shows transparent pixels as transparent, the window is
larger than the content by the room the content’s box-shadow reaches, and the
content is drawn inset by it. Placement, bounds(), offset(), move and
resize all speak of the content, never of that room, and a press in the room
is a press outside the popup.
The desktop’s theme
host.systemTheme(); // Optional<SystemTheme>: LIGHT, DARK, or empty
Subscription following = host.onSystemThemeChanged(theme -> actions.pickTheme(theme));
Empty means the desktop has no such setting, and that is a different answer
from light: the first is a default, the second a theme.
The toolkit chooses nothing with the answer, and asking once at start-up is
the bug onSystemThemeChanged exists to prevent.
Capabilities
if (!Goldberry.capabilities().contains(Capability.SYSTEM_THEME)) {
// follow the user's own choice, and say why
}
A platform integration is compiled into the native library only where the
machine that built it had the headers. Where it was not, the call answers
“the desktop does not say”, and Goldberry.capabilities() reports the
difference from the library’s own record of how it was built.
The values are SYSTEM_THEME, INPUT_METHOD, DEVICE_HOTPLUG,
FILE_DIALOG, SCREENSAVER_INHIBIT, WINDOW_DECORATIONS, WAYLAND,
WEB_VIEW and NOTIFICATIONS. It may be asked before a window is open, and is
empty where there is no native library at all, apart from WEB_VIEW and
NOTIFICATIONS, which are a second library being there.
Opening links and one running copy
The system can ask an application to open something: a link of a scheme the
application registered, or a file opened from the desktop. It arrives in
onOpenUrl:
@Override
public void onOpenUrl(URI target) {
router.open(target);
}
On Windows and Linux the system starts a new process for a link. An application that names an id is one running copy, and a second launch hands its command line to the first and exits:
@Override
public Optional<String> singleInstance() {
return Optional.of("dev.example.chat");
}
Registering the scheme is the installer’s: a .desktop file with
MimeType=x-scheme-handler/chat;, CFBundleURLTypes in Info.plist, or a
registry key under HKCU\Software\Classes.
Secrets
A token that keeps the user signed in belongs in the system’s own store, not
in a file. Keychain.system() keeps one secret per service and account in
the Secret Service on Linux (gnome-keyring, KWallet, KeePassXC), the login
Keychain on macOS and the Credential Manager on Windows:
var keychain = Keychain.system();
Thread.startVirtualThread(() -> {
keychain.store("chat", account, refreshToken);
var token = keychain.loadText("chat", account);
});
Every call waits for the store, and a locked store asks the user to unlock it
first, so never call one on the UI thread. A refusal is a KeychainException
whose reason() says which: UNAVAILABLE where there is no store (a
container, a desktop without a keyring daemon), DENIED when the user
dismissed the prompt, FAILED otherwise. The Credential Manager holds at most
2560 bytes per secret. In a test, Keychain.inMemory() stands in for the
system’s store.
Notifications
host.notify(Notification.of("Gate waiting", "prod-eu needs an approval")
.onActivate(() -> actions.showGates()));
A notification is drawn by the desktop: GNOME’s banner, macOS’s Notification
Center, Windows’ toast. notify answers whether the desktop took it, and
false is an ordinary answer. The action runs on the UI thread when the user
clicks the notification, and the window repaints after it.
| Platform | Shown by | A click | Needs |
|---|---|---|---|
| Linux | The org.freedesktop.Notifications service, over the session bus | Reported | A notification daemon on the session bus |
| macOS | UNUserNotificationCenter | Reported | An .app bundle, and the user’s permission |
| Windows | The notification area’s balloon, shown as a toast | Reported, for the latest notification | Nothing |
On macOS a plain java process has no bundle identifier, and macOS posts
nothing for it. notify answers false and says why once, at info. Package the
application as an .app. A real Windows toast needs an AppUserModelID
registered at installation. Both are the application’s packaging, not the
toolkit’s.
Capability.NOTIFICATIONS says whether this process can ask at all.
The badge
host.badge(3); // a number on the dock or launcher icon
host.badge("!"); // any short text, on macOS
host.badge(0); // none
macOS shows any short text on the dock icon. A Linux dock shows a number:
Ubuntu’s dock, Dash to Dock, Plank and KDE’s task manager read the Unity
launcher signal. A dock finds the application by its desktop entry, which only
the application knows. Name it with -Dgoldberry.desktop.id=ru.example.App,
without .desktop, or start the application from its entry, which sets
GIO_LAUNCHED_DESKTOP_FILE. On Windows the badge sits over the window’s taskbar button: up to three
characters, white on a red disc, and a number past 99 as 99+.
Fullscreen
if (host.canFullscreen()) {
host.setFullscreen(!host.isFullscreen());
}
host.onFullscreenChanged(on -> model.setFullscreen(on));
Fullscreen is a state the platform owns. setFullscreen is a request whose
answer arrives through onFullscreenChanged, several frames later on macOS,
and the user can change it without the application, so isFullscreen() is
what the platform last reported.
canFullscreen() is false for a host with no window under it, which is what
a media-player reads to decide whether to offer the button at all.
Vertical sync and a frame cap
A window presents in a PresentMode. VSYNC waits for the display’s vertical
blank, which is the default and what every window has. MAILBOX shows the
newest frame at the blank and drops the older ones, so the loop never waits.
IMMEDIATE shows each frame at once and may tear. A game’s options screen
switches between them while it runs:
window.presentMode(PresentMode.MAILBOX).frameCap(144);
var inEffect = window.presentMode();
A driver without the mode asked for presents in the nearest it has: MAILBOX
falls back to IMMEDIATE, then VSYNC. presentMode() says which mode is in
effect, which is what an options screen shows. A window presenting on the CPU
keeps the request and presents as its window surface does until it moves to
the GPU.
The frame loop follows the mode. A window in VSYNC is painted at most once a
refresh. A window in MAILBOX or IMMEDIATE is painted as fast as it asks,
and frameCap(hertz) limits it. Zero lifts the cap. A cap above the display’s
rate changes nothing in VSYNC. A frame the cap holds back is not counted
late, and a hud’s budgets are a share of the cap where it is slower than the
display. The pacing reading shows both settings.
When nobody is looking
A window that is animating asks for its next frame only as often as it can be seen and as the desktop allows.
| The window is | Animation frames |
|---|---|
| covered by other windows, on another Space, hidden or minimized | none, until it can be seen |
| on a desktop saving power | at most 30 a second |
| not focused, with an inactive cap set | at most the cap a second |
| anything else | as fast as it presents |
Only the frames an animation asks for are held: a transition, a keyframe animation, a spinner. A click, a state change or a new video picture is painted as soon as it is due. An animation that waited catches up to the clock on the first frame that is seen.
Occlusion is what the platform reports: macOS reports it, and X11 does under a window manager that sends visibility events. A desktop that does not say leaves the window counted as visible.
An unfocused window is not slowed by default, since the window beside the one being typed in is still being looked at and a video in it is still being watched. An application whose motion is decoration asks for it:
window.inactiveFrameCap(4);
Or it pauses the motion itself, from the stylesheet:
.attention:window-inactive { animation-play-state: paused }
Or from code, with the window’s own signals:
window.onFocusChanged(focused -> ticker.paused(!focused));
window.onOcclusionChanged(hidden -> feed.paused(hidden));
window.onPowerChanged(power -> sparkles.setVisible(!power.onBattery()));
window.powerState() says where the power comes from, how much battery is
left, and whether the desktop’s saving mode is on: macOS’s Low Power Mode,
Windows’ battery saver, or a Linux desktop’s power-saver profile. No platform
announces a change, so a window reads it again every 20 seconds and tells
onPowerChanged what changed. While the saving mode is on, the window holds
its animations to 30 frames a second by itself; running on battery alone
changes nothing until the application decides it should.
Where a window opens
@Override public Optional<LogicalPoint> position() { return settings.position(); }
@Override public Optional<String> display() { return settings.display(); }
@Override public void start(Host host) {
var window = host.window();
window.onCloseRequest(() -> {
window.normalBounds().ifPresent(bounds -> settings.position(bounds.origin()));
settings.size(window.normalSize());
settings.maximized(window.isMaximized());
window.display().ifPresent(display -> settings.display(display.name()));
return true;
});
}
A window is created hidden, so where it opens is decided before anybody sees
it. position() is its top-left in the desktop’s coordinates, the space
Window.position() reports and every Display rectangle is in: the primary
display’s corner is usually the origin, and a display to its left has a
negative x.
What was saved may not fit the desktop the application opens on. A monitor was unplugged, or a laptop left its dock. So the position is checked, in order:
- on a display that exists: it opens there, clamped into that display’s usable bounds, clear of the taskbar or the dock;
- on no display: it opens centred on the display named by
display(), if that one is still connected, and otherwise centred on the primary display.
With no position, a display() alone opens centred on that display, and
nothing at all leaves it to the platform. The same clamp applies to
window.move(point), so a window can never be put off every screen.
normalBounds() is what to save rather than the current bounds. They are
the bounds the window returns to when it stops being maximized or
fullscreen, so a window closed maximized opens maximized and still restores
to the size the user last gave it. They are still answered after the window
has closed. onMove(listener) reports every move.
Note
Wayland places every window itself. A compositor tells no application where its windows are, and refuses to put one anywhere. There,
position()is empty,movereturns false,normalBounds()is empty andnormalSize()is the whole of what can be restored. X11, Windows and macOS place windows as asked.
Displays
for (var display : host.displays()) {
log.info("{} {} at {}", display.name(), display.bounds(), display.scale());
}
A Display has a name, its full bounds(), the usableBounds() a window
may occupy (less panels and docks), its scale(), and whether it is the
primary() one. Its id() is good for this run only. Remember a display by
its name, which is a monitor’s model as a rule. window.display() is the
display most of a window is on. DisplayLayout holds the rule above, for an
application that wants to check a position itself.
Asking for attention
Goldberry.async(this::export)
.thenRun(() -> host.window().requestAttention(Attention.UNTIL_FOCUSED));
requestAttention(Attention.BRIEFLY) or UNTIL_FOCUSED asks the desktop to
draw the user’s eye to a window that is not in front: the dock icon bounces
on macOS, the taskbar button flashes on Windows, and X11 sets the urgency
hint, which the desktop shows its own way. cancelAttention() withdraws it,
and raise() brings a window to the front, which a desktop may answer with a
flash instead. It is not a notification. It says which window, and nothing
about why.
More than one window
private WindowHost settings;
void openSettings(Host host) {
if (settings != null) {
settings.window().raise();
return;
}
var spec = WindowSpec.of("Settings", LogicalSize.of(480, 360)).withOwnership(Ownership.OWNED);
settings = host.openWindow(spec, new SettingsPage(model)).orElseThrow();
settings.onClose(() -> settings = null);
}
host.openWindow(spec, root) opens a second top-level window with root in
it and returns its WindowHost, which is a Host for that window plus
close(), isOpen() and onClose(action). The new window has its own tree,
router, overlays, focus, accelerators, popups and tooltips. It shares what
belongs to the application: the stylesheets (a restyle() from any window
restyles every window), the fonts, the models (a change repaints every
window) and the clock. A widget in it reaches its own window’s host through
BuildContext.host().
spec.withOwnership(...) says whether it belongs to the window it was opened
from:
| Ownership | What it does |
|---|---|
NONE | a window of its own, the default |
OWNED | kept above its owner and minimized with it; closes when its owner closes. Opens centred on the owner unless the spec says where |
MODAL | OWNED, and the owner takes no input until it closes. A press on the owner brings the modal window to the front |
Closing the application’s first window closes every other one and ends the
application, as Goldberry.stop() does. Closing any other window takes its
tree down on the next turn of the loop and then runs its onClose actions.
Threads
Goldberry.async(() -> readTheFile())
.thenAccept(text -> host.title(text)); // already on the UI thread
There is one UI thread, and every window, style and box tree is confined to
it. Goldberry.async(work) runs the work on a virtual thread and delivers
its result on the UI thread, so every callback chained onto the future may
touch a window with no hand-off to write.
Goldberry.ui() is the UI thread as an Executor, Goldberry.isUiThread()
says whether you are on it, and host.repaint() is safe from anywhere.
A write to a model from a background continuation is not a write the toolkit
was watching for. Models.refresh(model) after it sweeps the fields, and is
a no-op once the model is bound ahead of time
(Ahead-of-time binding).
Caution
On macOS the JVM must start on the process’s first thread, because AppKit requires it. Run with
-XstartOnFirstThread. Without it the windowing layer reportsNo available video device, and the toolkit’s message says which flag is missing.
Closing
host.window().close() closes the window, and the loop ends when the last
window has closed. The first window is the application’s: closing it closes
every window openWindow opened. window.onCloseRequest(handler) sees the user’s close
button first and returns whether to allow it. Goldberry.stop() asks the
loop to finish from any thread.
The low-level path
var window = Window.open("Hello", 960, 640);
window.onPaint(frame -> frame.fill(0xFF2E3440));
Goldberry.run();
That is the whole API for a window with no widgets: no backend to name, no
event loop to build. Window.open(WindowSpec) takes a spec with
withMaximized, withMinimumSize, withDecorated, withResizable,
withPosition and withDisplay.
Painting takes logical coordinates, colours are straight 0xAARRGGBB, and
the frame is the platform’s own buffer wherever it lends one.
Window.open may be called more than once, and Goldberry.run() returns
when every window has closed or something called Goldberry.stop(). Either
way it closes what is still open and releases the windowing layer before it
returns, so nothing is left for the process to leak. A window opened after
run() returns starts again from nothing. An application launched through the
launcher opens a second window with widgets in it through host.openWindow,
not here.
Read more
- Overlays and Menus and the tray: the widgets that open over a window
Testing an application
Render a widget tree to pixels with no display, step a virtual clock, drive input through the real router, and compare pictures with a tolerance that absorbs antialiasing and nothing else.
By the end of this chapter you can assert that your documents inflate against your models, photograph a screen in a JUnit test, step an animation to a known frame, click a button through the router, answer a dialog, find a widget by id or role, assert that nothing overruns its box, and skip cleanly on a machine with no native library.
@Test
void theSettingsScreenRenders() {
byte[] png = Offscreen.of(800, 600)
.stylesheets(Controls.stylesheets(Theme.NORD_DARK))
.render(new SettingsScreen(settings, actions))
.encodePng();
assertArrayEquals(Files.readAllBytes(golden("settings.png")), png); // or a tolerant compare
}
Nothing opens. Offscreen runs the window’s own sequence into memory: no
backend, no windowing layer, no compositor.
What ships, and what is test-scope
| Where | An application can use it | |
|---|---|---|
Offscreen and its Session, Image, Clock.virtual(), ElementTree, WidgetRenderer, RenderTree, PointerRouter, HitTest, Frame.over, PixelBuffer.allocate | goldberry-core | yes |
Host | goldberry-core, an interface | yes: implement or proxy it for a test |
GoldenImage, Tolerance, ScaleInvariance, RendererRequirement, TestClock, TestFrames | core’s test fixtures | no. The fixtures are not published |
TestHost, TestLoop, CatalogMarkup | widgets’ tests | no |
the headless backend | core, package-private | no |
Everything below uses only the first two rows.
Documents inflate against the real models
@Test
void everyDocumentResolvesItsNames() {
var app = new Hello();
var inflater = Widgets.inflater(Icons.lenient(), app.models().toArray());
for (var name : List.of("window.kdl", "settings.kdl")) {
var nodes = KdlParser.resource(Hello.class, name);
assertDoesNotThrow(() -> inflater.inflateAll(nodes), name);
}
}
The registries a model publishes are strict, so a press= or a bind=
that names nothing fails here with the text quoted, rather than on the
window’s first frame. Icons are lenient because a test has no reason to
build them. The result is a list of widgets a test can walk to assert which
node types a document holds.
Pictures
A tree that builds to nothing renders as its background, so an overlay’s empty state can be rendered on its own.
Offscreen.of(width, height) is in physical pixels. .scale(1.5f) changes
how much content fits in them, .stylesheets(...) sets the cascade,
.settle(ms) moves the virtual clock between the two passes, 200 ms by
default, and .background(argb) fills under a tree whose root paints
nothing. .render(widget) runs three passes, because a widget is told what
size it came out as after layout and may rebuild in response. .paint(painter)
draws a painter instead.
The clock is frozen, so two renders of one tree are the same bytes. A spinner is at whatever it is at 200 ms, on every machine. That is what makes a picture cacheable and a golden image possible.
Comparing with a tolerance
One reference set serves every platform when it is compared with a per-channel tolerance of 2 in 256 and a cap of 2% of pixels allowed to differ at all. The rasterizer compiles its pipelines for the CPU it finds, and AVX2, SSE2 and NEON agree on what they draw and not on the last bit of a blended edge. The tolerance absorbs antialiased edges and nothing else: a colour that changed or a box in the wrong place moves thousands of pixels by tens of levels.
GoldenImage is a test fixture, so an application writes the comparison:
static void assertClose(Image expected, Image actual) {
assertEquals(expected.width(), actual.width());
assertEquals(expected.height(), actual.height());
int differing = 0;
for (var y = 0; y < actual.height(); y++) {
for (var x = 0; x < actual.width(); x++) {
if (channelsApart(expected.argb(x, y), actual.argb(x, y)) > 2) {
differing++;
}
}
}
assertTrue(differing <= 0.02 * actual.width() * actual.height(), differing + " pixels differ");
}
Image.decode(Files.readAllBytes(golden)) reads the reference back. Keep
goldens in your repository as PNGs, and give the test a system property of
your own that rewrites them instead of asserting. The review is then
git diff --stat.
Determinism rules
A golden is only a golden if the same tree draws the same bytes everywhere.
Embedded fonts only, a fixed scale factor, the virtual clock, a seeded random
source, and no wall-clock or locale dependence. A widget that reads
System.nanoTime() or LocalDate.now() in build is not photographable.
A second check redraws the tree at 2x and 1.5x and asks whether the pictures
describe the same thing, which is a second question rather than a second set
of files.
The virtual clock
var clock = Clock.virtual();
var renderer = new WidgetRenderer(Controls.stylesheets(Theme.NORD_DARK), fonts).clock(clock);
renderer.render(tree); // frame 0: the transition starts
clock.advance(50); // exactly 50 ms of a 100 ms transition
renderer.render(tree);
Clock.virtual() is a clock that moves only when told to, in milliseconds.
A WidgetRenderer takes one with .clock(clock), and a Host answers one
from clock(), so a widget that asks how long ago something happened can be
asked what happens after a timeout without sleeping. A mid-transition frame
is then the exact frame at 50 ms, on every machine.
Offscreen.of(w, h).measure(root) is a strip for a frame’s cost rather than
its picture. It paints into one buffer and, as a window does, only where
something changed, so a frame with nothing changed paints nothing. Each
frame() says what it cost and how much it painted, and stats() reads as a
window’s statistics do.
try (var meter = Offscreen.of(2560, 1440).stylesheets(sheets).measure(new Hud(model))) {
for (var i = 0; i < 600; i++) {
model.tick();
var frame = meter.frame();
log(frame.timings().paintNanos(), frame.damagedPixels());
meter.advance(16);
}
var p99 = meter.stats().percentile(FrameStage.PAINT, 99);
}
meter.picture() is a copy of what the buffer holds, for a check beside the
numbers.
Driving input
A widget test hands an event straight to the widget. A screen test opens a session and drives it the way a user does: through the router, against the frame it laid out, which is the shipping path.
try (var session = Offscreen.of(800, 600)
.stylesheets(Controls.stylesheets(Theme.NORD_DARK))
.session(new SettingsScreen(settings, actions))) {
session.click("apply"); // by id
session.click(session.byRole(Role.BUTTON, "Reset").orElseThrow());
session.focus("name");
session.type("Deploy Orc");
session.key(Key.ENTER);
session.key("Ctrl+S"); // as a menu prints it
assertEquals(1, settings.saves());
}
Offscreen.session(root) mounts the tree once, as strip does, and keeps
it until close(). After every piece of input it builds, lays out and
captures the regions, without painting, so the next event is answered
against what the last one changed, as a window answers it between two
frames. frame() is when there is a picture.
click(id) presses at the centre of what is visible of that node and
refuses when something else would take the press: a dialog’s scrim, a
toast, a sibling drawn over it. The exception names what is on top. A click
that a user could not make is never quietly delivered somewhere else.
click(x, y) presses wherever it is told. hover, wheel, type (text
committed in one piece) and key round it out. router() is there for a
gesture the session does not spell out, such as a drag.
Input does not move the clock. advance(Duration) does, and it stops at
every timer on the way, so a dialog’s closing animation ends, and its
handler runs, at the moment it would in a window.
A press on a disabled widget sets nothing. Set
-Dgoldberry.input.primary=ctrl in your test task, so a test that presses
Ctrl+C is the same test on macOS.
The router underneath is public too. pointerMoved, pointerPressed,
pointerReleased and pointerWheel take window coordinates;
keyPressed(Key.TAB, Modifiers.NONE, false) and keyReleased move focus
and fire accelerators; textInput("a") is committed text. A test of one
widget with no window around it can drive a PointerRouter over its own
ElementTree, calling router.updateRegions(HitTest.capture(render))
after each layout.
A host for a test
A session’s tree is built with a host, so BuildContext.host() answers and
an application’s own Dialogs.show(host, dialog) works unchanged:
session.click("delete"); // the screen opens a dialog
assertEquals(1, session.overlays().size());
session.click(session.byRole(Role.BUTTON, "Delete").orElseThrow());
session.advance(Duration.ofMillis(300)); // past the closing animation
assertEquals("deleted", screen.answer());
fill and overlay put the widget on the overlay layer the window root
draws, so the dialog is painted over the content, takes the pointer, and is
taken off by its own handle. after is a timer on the session’s virtual
clock. Focus by id, accelerators and isModal() are the router’s.
There are no popup windows, which is the real answer under the dummy
video driver, and no tray, web view, clipboard or file dialogs. window()
throws. session.host() is the same host, for a test that opens something
itself.
A test of one widget can implement Host itself and hand it to
ElementTree(root, host), recording what it was asked for. Answer clock()
with Clock.virtual() and popup(...) with Optional.empty().
OverlayLayer is the list a WindowRoot draws and the door overlays go
through, so such a host’s fill can return an overlay whose remove()
works.
Finding a widget
session.byId("apply"); // Optional<Element>, drawn or not
session.byRole(Role.BUTTON); // every button, in tree order
session.byRole(Role.BUTTON, "Apply"); // the one a reader calls Apply
session.elementAt(120, 48); // the topmost node drawn there
session.regions(); // every rectangle, in paint order
session.focused(); // and hovered()
Every focusable widget in the catalogue implements Semantics with a Role
and an accessible name, so byRole(Role.BUTTON, "Apply") finds the button
without a pixel. The queries search the overlays as well as the content. An
element has id(), type(), classes(), widget() and children(), and
type() is the CSS type, which is also the markup name.
Overruns
assertEquals(List.of(), session.overruns());
An overrun is a box laid out past the box it is in: a status line pushed out
of a 600-pixel dialog, a button off the end of its row. The layout pass
checks every subtree it lays out and logs each new shape once, as a
warning, through OverflowLog. That log is process-wide and says each
shape only once, so whether it is empty depends on every test before
yours.
session.overruns(), and RenderTree.overruns() under it, walk the whole
tree as the last frame laid it out, log nothing, and give the same answer
every time. An empty list is evidence. The exemptions are the log’s: a box
that clips on purpose (overflow other than visible), a child placed by
insets, and a pixel or two of rounding.
Running the launcher without a display
Goldberry.launch(app, new String[] {"--frames=3"}) paints three frames and
exits. With -Dgoldberry.backend.videoDriver=dummy nothing opens a window, so
that is a smoke test of the whole front door: the window spec, start,
root, the first frames and stop. It needs the native library, and under
dummy every host.popup(...) answers empty.
Skipping without the native library
A test that rasterizes needs libgoldberry. On a machine without it, the
first paint throws UnsatisfiedLinkError, and a missing library is an
ordinary state on a developer’s machine where a broken one is not.
RendererRequirement is a fixture, so an application writes the check
itself: try a two-by-two raster and abort the test on UnsatisfiedLinkError,
NoClassDefFoundError or ExceptionInInitializerError.
@BeforeEach
void needsARasterizer() {
try {
Offscreen.of(2, 2).paint((frame, size) -> frame.fill(0xFF000000));
} catch (UnsatisfiedLinkError | NoClassDefFoundError | ExceptionInInitializerError e) {
Assumptions.abort("no libgoldberry here: " + e);
}
}
-Dgoldberry.native.library=/path/to/libgoldberry.so points a test JVM at
a library that is not in a jar on its path.
Read more
- Tests and gates: how the toolkit tests itself
Logging and diagnostics
Goldberry logs through SLF4J and binds nothing. Add a provider and the start-up timeline, the frame timings and the platform's own libraries appear under names you can level.
By the end of this chapter you can see where a slow start or a slow frame went, silence a native library by name, read which way a window presents, set the properties that change the toolkit’s behaviour at run time, and recognise the failure messages that come up most.
runtimeOnly 'ch.qos.logback:logback-classic:1.6.5'
Add nothing and you get silence, including from SLF4J itself, which would otherwise print a “no providers were found” warning. Binding a provider is an application’s decision and never a library’s.
A logback configuration
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder><pattern>%d{HH:mm:ss.SSS} %-5level %logger{0} - %msg%n</pattern></encoder>
</appender>
<!-- The toolkit. DEBUG is the window lifecycle and backend start-up;
TRACE adds the start-up timeline and a line per frame. -->
<logger name="dev.goldberry" level="${goldberry.log.level:-DEBUG}"/>
<!-- What the platform's own libraries say. -->
<logger name="native" level="warn"/>
<logger name="native.glib.libayatana-appindicator" level="off"/>
<root level="INFO"><appender-ref ref="CONSOLE"/></root>
</configuration>
goldberry.log.level is a variable this file reads, not a property the
toolkit knows. The showcase’s logback.xml is the one above, and
-Dgoldberry.log.level=TRACE is how its run switches the toolkit to trace.
The start-up timeline
At TRACE, one table is printed after the first frame:
start-up timeline (866.6ms to here):
533.8ms +533.8ms runtime starting
559.6ms +25.8ms libgoldberry mapped (1.9ms)
722.6ms +162.9ms SDL video subsystem up (99.2ms)
866.6ms +117.1ms first frame presented
Each phase is measured from process start, so the first row says how long
the JVM took before the toolkit saw a line of your code. Startup.mark("my phase") and Startup.time("my phase", work) add your own rows, and
Startup.sinceProcessStart() is what the showcase’s status bar reads. What
the numbers should be, and how to make them smaller, is in
Starting fast.
Frames
At TRACE, every painted frame logs one line:
frame 312 in 1840us: buffer 12, paint 1105 (begin 40, draw 980, end 85), present 723
The stage timings are FrameStats, which host.frames() reads live and a
hud draws on screen. Two properties go deeper, and both are properties
rather than log levels because a diagnostic that costs an isTraceEnabled()
per element per frame would be measuring itself:
-Dgoldberry.trace.frames=truecounts what each frame did to the element tree: elements built, styles resolved, subtrees thrown away.=allreports the quiet frames too.-Dgoldberry.trace.input=truereports every pseudo-class the pointer and the keyboard set, one line per node of the chain.
Measuring says what to do with the numbers.
The platform’s own libraries
What GLib and the windowing layer log is an ordinary SLF4J event, on
native.<library>.<subsystem>: native.glib.libayatana-appindicator,
native.sdl.video. Nothing of theirs reaches stderr past your configuration.
Level, route or switch them off by name like anything else.
-Dgoldberry.log.native=false installs no bridge and gives each library its
stderr back, which is what to reach for when something in the platform layer
is being debugged and a logging configuration might be hiding it.
-Dgoldberry.log.glib.writer=true also installs a GLib structured-log
writer, only if nothing else in the process sets one.
Which way a window presents
Each window logs one line at INFO when it starts presenting a different
way, tagged [GPU] or [CPU], with the reason.
The same fact is window.presentation(), with label() for a status bar,
and onPresentationChange(listener) for a change mid-run: a GPU that failed,
or goldberry.gpu.composite=auto taking the GPU for a layer and giving it
back.
What this build can do
Set<Capability> can = Goldberry.capabilities();
The desktop integrations are compiled into the native library only where the
machine that built it had the headers. Goldberry.capabilities() answers
from the library’s own record, before any window is open, and is empty
where there is no native library at all. The
values are in Windows, popups and the host.
Properties an application can set
All read with -Dname=value on the command line, or set before the toolkit
starts.
| Property | Values | What it does |
|---|---|---|
goldberry.backend.videoDriver | a video driver: x11, wayland, dummy, … | overrides the video driver. On a Linux Wayland session the toolkit asks for x11,wayland by default. dummy opens no window and has no popups |
goldberry.backend.vsync | false | turns the frame loop’s pacing to the display off |
goldberry.frame.rate | a number; 0 | holds the loop to that many frames a second instead of the display’s rate; 0 measures the unthrottled loop |
goldberry.paint.threads | a count; 0 | pins the painter’s worker count; 0 paints synchronously |
goldberry.gpu | off, auto | whether any GPU is used at all |
goldberry.gpu.composite | never, auto, always | whether a window presents through the GPU: never, while it shows GPU layers, or from its first frame. always is the default |
goldberry.gpu.driver | metal, vulkan, direct3d12 | names the GPU driver, with goldberry-gpu on the path |
goldberry.gpu.debug | true | the GPU driver’s validation layer |
goldberry.gpu.power | low, high | which GPU the device prefers on a machine with an integrated and a discrete one; low by default |
goldberry.gpu.inPlace | auto, on, off | whether a composited window paints its frame in memory the GPU copies from, skipping a copy on the CPU; auto by default, which measures the device’s upload memory once at start-up and stays staged where it reads slower than ordinary memory |
goldberry.input.primary | ctrl, meta | what Primary resolves to, instead of reading os.name |
goldberry.motion.reduced | reduce, full | overrides the desktop’s reduced-motion answer; anything else asks the desktop |
goldberry.popup.settle | milliseconds | how long to disbelieve a focus-lost after a popup opens |
goldberry.native.library | a path | loads libgoldberry from there instead of the natives jar |
goldberry.webview.library | a path | the same for libgoldberry-webview |
goldberry.media.libdir | a directory | use a local media library and its media-layout.properties |
goldberry.media.mediaFoundation | false | disable the Windows system decoders |
goldberry.media.ffmpeg | executable path | enable an external decoder as a fallback |
goldberry.vector.libdir | a directory | use a local vector library and its layout stamp |
goldberry.log.native | false | no bridge: native libraries write to stderr again |
goldberry.log.glib.writer | true | also catches GLib’s structured messages |
goldberry.trace.frames | true, all | counts what each frame did to the element tree |
goldberry.trace.input | true | reports every pseudo-class input sets |
goldberry.css.lint | true | lints the application’s own stylesheets against everything in force whenever the launcher reads them, and logs each finding at warn. The development switch: dead declarations, rules a lenient parse dropped, and @media blocks that can never apply |
goldberry.golden.update, goldberry.golden.scales, goldberry.gpu.required
and the other *.required properties belong to the toolkit’s own test tasks
and do nothing in an application.
Failure messages, and what they mean
| You see | It means | Go to |
|---|---|---|
SDL_Init failed: No available video device, with a line naming -XstartOnFirstThread | on macOS, main is not on the process’s first thread. Add the flag to the java command | Windows, popups and the host |
no action named "app.sav" is bound. Bound: … | the document names an action no model in the inflater publishes. Usually the inflater was built from a list other than models(), or the name is misspelled | Markup |
nothing is bound to "app.gian". Bound: … | the same, for a bind= | Markup |
"!prefs.frost" is not a binding path | a bind= holds an expression. Only dotted paths are allowed | Markup |
unknown node "buton"; registered: … | the node name is not in any catalogue on the path | Markup |
… its package is not open to this module. Add opens com.example.app to dev.goldberry.core; | a @Model in a named module, bound at run time, needs its package opened | Ahead-of-time binding |
libgoldberry not found at … | the natives jar for this platform is not on the path, or the library was not built | Native image, and -Dgoldberry.native.library above |
cannot find -lz while building the native library | the linker needs zlib1g-dev, not only zlib1g | Native image |
the emoji face is not on the module path … | Font.bundled(BundledFont.EMOJI, …) without goldberry-emoji | Text, fonts and icons |
dropping "transition": width … is not a valid value | a transition names a property outside the whitelist | Styling |
unsupported at-rule "@font-face" | the CSS subset has @media, @starting-style and @keyframes and nothing else. In an application’s sheet the block is dropped with this warning; in the toolkit’s own it is a CssSyntaxException | Styling |
app.css, line 42: dropping "lane::before": … | a lenient sheet left out one rule that asked for something outside the subset; the rest of the sheet is in force | Styling |
app.css, line 7: "letter-spacing" is not a property this toolkit has | every declaration of that property in the sheet does nothing; said once per property per sheet | Styling |
easing "ease-in-out" is read as ease-enter | at info: CSS’s keyword runs on the system curve the table names | Styling |
nowhere to put a menu logged by the showcase | the video driver has no popup windows, or the anchor was not painted yet | Windows, popups and the host |
Read more
- Measuring: the HUD and the benchmarks
Writing a widget
A widget is an immutable record that describes a box. Implement the few interfaces it needs, annotate it with its node name, and the build registers it for markup.
By the end of this chapter you can write a leaf widget that paints, give it a CSS type and parts, let a document build it, take input and focus, follow a bound value, give it a role, and hold it to the same tests the catalogue passes.
@Markup("gauge")
public record Gauge(double value, @Nullable Observable<?> source, Attributes attributes)
implements Widget.Leaf, Styled, Paints, Attributed<Gauge>, Bindable<Gauge>, Semantics {
public static Widget inflate(KdlNode node, List<Widget> children, Wiring wiring) {
return new Gauge(node.numberProperty("value", 0), wiring.bound(node), Attributes.of(node));
}
}
That is the whole registration. The build collects every @Markup class in
the module into a catalogue and declares it as a service, and an application
that never names your module gets gauge in its documents.
The three shapes
| Shape | Implements | For |
|---|---|---|
| composition | Widget.Stateless with build(BuildContext) | a widget made of other widgets. Pure: it is called more often than you can predict |
| state | Widget.Stateful with createState(), and a State<W> | a widget that remembers something across rebuilds: a scroll offset, a caret, an open tab |
| leaf | Widget.Leaf, usually with Styled and Paints | a widget that produces a box of its own |
A widget is a value. It holds no state, is rebuilt constantly, and must copy
any collection it is handed. The element tree is what persists: :hover,
focus and a State live on the element and survive a parent re-describing
its child.
record Counter(String label) implements Widget.Stateful {
public State<?> createState() { return new CounterState(); }
}
final class CounterState extends State<Counter> {
private int clicks;
@Override public Widget build(BuildContext context) {
return new Button(widget().label() + ": " + clicks, () -> setState(() -> clicks++));
}
}
setState runs the mutation now and defers the rebuild, coalesced with every
other change in the frame. Re-read widget() on every build, because a
rebuild can hand the same state a new widget value. initState is where a
subscription goes and dispose is where it is cancelled; after dispose,
setState throws rather than leaking quietly.
BuildContext answers findAncestor(type), findAncestorState(type),
host() for the window’s Host, and
token(name, fallback) and duration(name, fallback) for a custom property
resolved at this node.
A state reaches the same BuildContext its builds are handed through
context(), from initState until dispose. The host is known when the
state is mounted, so something timed that starts when the widget appears is
set in initState and cancelled in dispose, and the build stays a
description:
@Override protected void initState() {
opening = context().host().map(host -> host.after(Duration.ofMillis(400), this::deal));
}
@Override protected void dispose() {
opening.ifPresent(EventLoop.Timer::cancel);
}
Styled: a name for the cascade
@Override public String cssType() { return "gauge"; } // the default is the class name in kebab-case
Styled is what lets a stylesheet see the widget. cssType() is the type
selector, id() and classes() come from the attributes, and the state
flags isDisabled(), isChecked(), isIndeterminate(), isInvalid() and
isAffixed() are mirrored onto the element so a stylesheet, a hit test and
the semantics agree about them. Not every widget is Styled: a composition
that only returns other widgets has nothing to style, and a type name for it
would put a node in the cascade no author knows about.
restyle(ComputedStyle) is the inline layer, for a number no selector can
express: the position of the third of five segments, a thumb’s length, a
scroll offset. It runs after the cascade and before the frame’s animations
observe the style, so what a widget writes there transitions like anything
else. A fact a
selector could match on is a class, not a restyle.
Parts
A control with two surfaces a theme styles differently is two cascade
nodes. The inner one is a part: a Styled leaf of its own, returned as a
child from the control’s children(), with a type name a stylesheet selects
and no @Markup, so a document cannot build one on its own.
record GaugeNeedle(Attributes attributes) implements Widget.Leaf, Styled, Paints {
@Override public Box render(ComputedStyle style, List<Box> children, Context context) {
return Box.of().style(style);
}
}
gauge gauge-needle { background: var(--gb-accent) } then reaches it. The
catalogue’s check-indicator, toggle-thumb and scroll-thumb are parts.
Paints: from a style to a box
Paints.render(style, children, context) answers one question: given what
the cascade resolved for this node and the boxes its children produced, what
box is it? The Box is a value, and the retained render tree is reconciled
against it rather than mutated by the widget.
@Override public Box render(ComputedStyle style, List<Box> children, Context context) {
var shown = source != null && source.get() instanceof Number n ? n.doubleValue() : value;
var fraction = Math.clamp(shown, 0, 1);
var ink = style.color();
var track = context.color("--gb-progress-track-bg", 0xFF4C566A);
return Box.of()
.style(style)
.size(Length.points(96), Length.points(56))
.painting((frame, size) -> {
var cx = size.width() / 2;
var cy = size.height() - 8;
var radius = Math.min(cx, cy) - 4;
frame.strokePath(Path.arc(cx, cy, radius, Math.PI, Math.PI), Stroke.round(4), track);
frame.strokePath(Path.arc(cx, cy, radius, Math.PI, Math.PI * fraction), Stroke.round(4), ink);
});
}
Box.of().style(style) takes the layout, the background, the border, the
opacity, the transform and the cursor from the resolved style, and the
widget adds what the stylesheet cannot decide: its content. size sets an
intrinsic size, painting draws into the content box through a Painter
that is handed a Frame translated to the box’s corner and clipped to it,
and children(...) lays the children’s boxes out inside. Box.text(paragraph, argb) and Box.icon(icon, argb) are the other two kinds of content.
The Context is what a render pass offers beyond the style. font(style)
and paragraph(style, text) go through the window’s font book and the
paragraph cache; always call paragraph rather than Paragraph.of, because
shaping costs 56 µs and the render tree keeps the measure callback it already
has only when the same instance comes back. color(name, fallback) and
length(name, fallback) read a custom property resolved for this node, so
#cpu { --gb-progress-track-bg: … } recolours one gauge. nowMillis() is
the frame’s time and reducedMotion() the user’s preference.
Animating
A widget that moves by CSS declares nothing: a transition is the renderer’s
to track. A widget that draws itself from nowMillis() says so with
isAnimating(), and the frame loop keeps coming while it is true:
@Override public boolean isAnimating() { return indeterminate; }
It is a property of the description, so a progress bar that has been given a
value stops asking and nothing has to be started or stopped. The overload
isAnimating(style, context) is for a widget whose answer depends on the
clock.
Attributes and binding
@Override public Gauge withAttributes(Attributes attributes) { return new Gauge(value, source, attributes); }
@Override public Gauge bound(Observable<?> source) { return new Gauge(value, source, attributes); }
@Override public Observable<?> binding() { return source; }
Attributed<Gauge> gives the widget id, styled, keyed, tooltip,
contextMenu, onPointerEnter and onPointerExit as chainable steps, and
the chain keeps its type: new Gauge(0.4).id("cpu") is a Gauge. The one
method a record writes is withAttributes, because only it knows its own
components. Attributes.of(node) reads id, class, tooltip,
context-menu and name off a markup node, with the id as the key.
Bindable<Gauge> is the chainable bind=, and Widget.binding() is what
the element subscribes to: a change marks the element as needing a build, by
the route a setState takes. The value is an Observable and never a
Property, so a widget reads and watches and cannot write. What the value
means is the widget’s business: Gauge reads a Number and falls back to
its own value for anything else.
The inflate method
public static Widget inflate(KdlNode node, List<Widget> children, Wiring wiring) {
return new Gauge(node.numberProperty("value", 0), wiring.bound(node), Attributes.of(node));
}
@Markup("gauge") requires a public static Widget inflate(KdlNode, List<Widget>, Wiring) on the same class, and the build fails naming the
class if it is missing. The inflater is depth first, so children are
already built. KdlNode reads stringProperty, numberProperty(key, fallback), booleanProperty and flagProperty, and argument() is the
primary content. Wiring holds the four registries and the readings nearly
every widget needs: Wiring.label(node) for the argument, wiring.bound(node)
for bind=, wiring.action(node, "press") for a Runnable,
wiring.valued(node, "change") for a Consumer<String>,
wiring.icon(node) for icon=, and wiring.handle(node, "controller", FormController.class) for a named object.
The build of a widget module writes the catalogue. In Gradle that is one line:
plugins { id 'goldberry.weave' }
The Maven form is in Ahead-of-time binding.
Input and focus
A widget takes part in input by implementing Handles. Everything on it has
a default. A gauge the user can set adds a Consumer<Double> onChange
component and implements it:
public record Gauge(..., Consumer<Double> onChange) implements ..., Handles {
@Override public boolean isFocusable() { return source == null; } // only an unbound gauge is set by hand
@Override public void onPointer(PointerEvent event) {
if (event.kind() == PointerEvent.Kind.PRESSED || !Float.isNaN(event.dragX())) {
onChange.accept(event.local().fractionX());
event.consume();
}
}
@Override public void onKey(KeyEvent event) {
if (event.is(Key.RIGHT)) { onChange.accept(Math.min(1, value + 0.05)); event.consume(); }
}
}
onPointer sees the event on the target and then on each ancestor,
onPointerCapture sees it root-first before the target does, and
consume() stops it. A press captures the pointer until the release, so a
drag that leaves the box still arrives, and dragX() says how far it has
travelled (Input and focus).
| Method | Answer |
|---|---|
isFocusable() | whether Tab stops here. False by default |
focusScope() | NONE, or HORIZONTAL, VERTICAL or BOTH for a composite whose descendants are one Tab stop |
localPart() | the CSS type of the part local() is measured against, for a control bigger than the thing it points along |
gestureAnchor() | a number to remember for a drag, handed back as anchor() |
wantsTextInput() | whether to turn the platform’s text input on while focused. A field says true; a board that wants arrow keys says false |
onFocusChanged(focused, fromKeyboard) | focus arrived or left. A radio raises its change here, so an arrow key moves the value and the tick follows |
onFocusWithin(within, fromKeyboard) | focus entered or left the subtree as a whole |
onText, onPreedit, caretArea() | committed text, an input method’s composition, and where the caret is for its candidate window |
A canvas takes the same facts through its own Input, which is how a
painter without a widget of its own gets a pointer and a caret.
Semantics: a role and a name
@Override public Role role() { return Role.STATUS; }
@Override public @Nullable String accessibleName() { return attributes.name(); }
Every focusable widget implements Semantics. Role is the closed set:
BUTTON, CHECKBOX, RADIO, RADIO_GROUP, SWITCH, TEXT_FIELD,
SLIDER, COMBO_BOX, OPTION, ROW, TAB, MENU_ITEM, MENU_BUTTON,
SCROLL_VIEW, SEPARATOR, DISCLOSURE, FIGURE, GROUP, GRID,
DIALOG and STATUS. The name is the user’s text, never an id or a type,
and null is an answer when something else names the widget. live() says
whether the widget’s arrival is worth interrupting a reader for, which only a
toast’s is. There is no accessibility bridge, so nothing outside the toolkit
reads the tree. The data is there so that a bridge is an adapter.
A widget must not hold a close()
An Icon, a Font, a Fonts book, a native handle: anything with a
close() is opened in Application.start and closed in stop, and a widget
borrows it. A widget is rebuilt and thrown away constantly, and one that
owned a resource would leak one per rebuild or close one that a sibling still
draws with. The same rule is why markup names an icon against a registry
rather than building one.
What the catalogue’s tests hold a widget to
Every built-in exists three ways, as a record, a node and a CSS type, and
three sweeps over Widgets.inflater().registered() hold it to that. Hold
your own widgets to the same list:
WidgetParityTest. The node inflates with nothing bound. The widget it builds isStyled, itscssType()is the node name, exactly one node in what it describes carries that type, and it renders to a box. The record built in Java and the one inflated from the equivalent markup areequals. A part is not constructible from a document.ImmutabilityTest. A collection handed to the constructor is copied, so a caller holding the original cannot reach in afterwards.ChainingTest.styled(...)keeps the type,id(...)is also the key, and a chain of withers builds the same value a constructor would.
@Test
void javaAndKdlAgree() {
var fromJava = new Gauge(0.4, null, new Attributes("cpu", Set.of("warm"), "cpu"));
var fromKdl = Widgets.inflater().inflateAll(KdlParser.parse("""
gauge id="cpu" class="warm" value=0.4
""")).getFirst();
assertEquals(fromJava, fromKdl);
}
A golden image for a widget
@Test
void restsAtForty() {
var actual = Offscreen.of(120, 72)
.stylesheets(Controls.stylesheets(Theme.NORD_DARK))
.render(new Gauge(0.4, null, Attributes.NONE));
assertClose(Image.decode(Files.readAllBytes(golden("gauge-40.png"))), actual);
}
GoldenImage is a test fixture of the toolkit’s and is not published.
Offscreen is the entry point for your own goldens, and the comparison is
yours, with the 2 in 256 tolerance and the scale sweep in
Testing an application. A widget
that is deterministic under a frozen clock is photographable. One that reads
the wall clock in render is not.
Read more
- Building an application: where a widget goes in an application
- Ahead-of-time binding: the build step that writes the catalogue
Ahead-of-time binding
An ordinary jar binds its models while it runs and needs no build step. A native image, or a library that ships widgets, adds one build step: the weaver.
When you need it
| You are building | Add the weaver? | What it does for you |
|---|---|---|
An application run on the JVM: java -jar, gradle run, an IDE | No | Nothing to add. Models are bound at run time |
| A GraalVM native image | Yes, --models | Binds the models at build time, so the image needs no reflection |
A library with @Markup widgets | Yes, --catalog | Registers the widgets, so a document finds them by name |
The annotations and the behaviour are the same either way. A model that works in a jar works in an image.
What it does
A model is plain Java. Markup binds to its fields and calls its methods:
@Model
public final class Settings {
@Bind("app.gain") private int gain = 40;
@Action("app.louder") private void louder() { gain++; }
}
slider bind="app.gain" min=0 max=100
button "Louder" press="app.louder"
gain++ moves the slider. Building an application covers
the annotations. Java cannot observe a field write from outside the class, so
the weaver rewrites the compiled classes:
- each assignment to a
@Bindfield, in the model or in any class beside it, becomes a call that stores the value and notifies the controls bound to it; - the model gets a table of its bindings and actions, built from the annotations, so nothing is looked up reflectively;
- a class that neither is a model nor writes to one is left untouched.
It runs between compileJava and jar, on the .class files, using the JDK’s
class-file API. It needs no agent, no opens and no code generated at run time.
Adding it to a build
The weaver is one jar, dev.goldberry:goldberry-weaver. It takes directories
of compiled classes and rewrites them in place, resolving the module’s own
types against its compile classpath, goldberry-core included. --models and
--catalog select one half; with neither, it runs both.
Gradle
The dev.goldberry.weave plugin runs both halves at the right moments:
// settings.gradle
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
}
}
// build.gradle
plugins {
id 'java'
id 'dev.goldberry.weave' version '2026.3'
}
The catalog is declared before classes on every build. The models are woven
when goldberry { nativeImage = true } is set, or for one build with
-Pgoldberry.nativeImage=true; ./gradlew weaveModels weaves them on demand.
The weaver runs on the project’s Java toolchain.
Maven
Run it with exec-maven-plugin in the process-classes phase:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.5.0</version>
<executions>
<execution>
<id>weave</id>
<phase>process-classes</phase>
<goals><goal>java</goal></goals>
<configuration>
<mainClass>dev.goldberry.weaver.WeaverMain</mainClass>
<arguments>
<argument>${project.build.outputDirectory}</argument>
</arguments>
<classpathScope>compile</classpathScope>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>dev.goldberry</groupId>
<artifactId>goldberry-weaver</artifactId>
<version>${goldberry.version}</version>
</dependency>
</dependencies>
</plugin>
Any other build
java -cp goldberry-weaver.jar:target/classes:<compile classpath> \
dev.goldberry.weaver.WeaverMain target/classes
Put the classes and their compile classpath on the classpath. The weaver loads
your types to rebuild the methods it rewrites, and without them it fails with
Could not resolve class. It prints one line per class it changed and exits
with 1, naming the member, when it refuses a model.
Widget catalogues
A module that ships widgets annotates each with @Markup("name"). The
--catalog half collects them into the module’s WidgetCatalog and declares
it in both module-info.class and META-INF/services, so the module works on
the module path and on the class path. Widgets.inflater(...) then finds every
catalogue on the path, and an application uses the widgets without naming the
module.
There is no run-time equivalent: finding annotated classes while the program
runs would mean scanning the class path. A widget library runs --catalog in
every build. Writing a widget covers the rest.
Without it: the sweep
A model that is not woven is bound at run time. Reads are exact. Writes are found by comparing each field with its last value, which happens:
- after every action a document dispatches;
- at the start of every frame, for the models
Application.models()returns; - whenever you call
Models.refresh(model).
A field written from anywhere else, such as a background callback, needs the explicit call:
job.onFinished(text -> {
model.status = text;
Models.refresh(model); // does nothing once the class is woven
});
In a named module, the model’s package must be open to the toolkit:
opens com.example.app to dev.goldberry.core;
The error message quotes this line if it is missing. A class-path application needs nothing.
What it refuses
The weaver at build time, and the run-time binder on first use, refuse the same models. Each refusal names the member.
| Refused | Because |
|---|---|
a static @Bind field | A binding belongs to one instance |
a final @Bind field, unless a Property | A value that cannot change has nothing to notify |
| an array | Only assignment is observed, so values[0] = x notifies nobody. Assign a new List |
a path that is not a.b.c | The binding path grammar |
| two members with one name | One name, one value |
an @Action with two parameters | An action reports that something happened, or what it should become |
an @Action parameter that is not String, double, int, boolean or a box | A valued action arrives as the string the document wrote |
a static @Action | An action changes a model instance |
an abstract or empty @Model | Nothing to bind |
@Actions with a @Bind field, or with no @Action | A class with values is a @Model; one with no actions publishes nothing |
@Model and @Actions on one class | Pick one |
a @Model extending a @Model | Inherited fields would notify nobody |
@Bind(restyle = true) on a Property | Writes to a Property are not rewritten, so there is nowhere to restyle from |
@Markup without public static Widget inflate(KdlNode, List<Widget>, Wiring) | The node name has nothing to build |
two classes with one @Markup name | A document would get whichever loaded last |
Native image
A Goldberry application can be built as a GraalVM native image: no class loading, no reflection on the binding path, and a start-up measured against the process rather than against a JVM. The binding schema is designed for that.
The Showcase packages the desktop library, web-view shim, media codecs and SVG renderer on Linux x64, macOS arm64 and Windows x64. It carries fonts, icons, stylesheets and the widget catalogues it uses. The modules an application includes determine the executable’s size.
Before anything else: the C toolchain
native-image links with the system gcc, so it needs a C toolchain and the
development package for zlib — not merely the runtime one, which is what a
desktop already has:
sudo apt install build-essential zlib1g-dev # Debian / Ubuntu
sudo dnf install gcc glibc-devel zlib-devel libstdc++-static
Without it the build runs to completion, spends a minute on analysis, and fails
at the last step with cannot find -lz. zlib1g alone is not enough: the linker
resolves -lz through the libz.so symlink that zlib1g-dev installs.
The two commands
./gradlew :example:nativeImageMetadata -Pgraalvm.home=/path/to/graalvm
./gradlew :example:nativeImage -Pgraalvm.home=/path/to/graalvm
GRAALVM_HOME works instead of the property. Either way it must be a GraalVM
and not a stock JDK — native-image and the tracing agent ship only with the
former, and the task says so if you point it at the wrong thing.
The result is one executable in example/build/native/goldberry-showcase-<target>.
Goldberry embeds the shared libraries from the classifier jars as resources and
extracts each library to a temporary file when first loaded.
Showcase CI embeds the core and web-view libraries, media codecs and SVG
renderer. To include the codecs and SVG renderer in a local image, first run
./gradlew :media:nativesBuild :vector:nativesBuild. For builds from another
runner, pass their install directories with -Pgoldberry.media.libdir and
-Pgoldberry.vector.libdir. Run the resulting executable with
--verify-native-libraries to check that the web-view, media and SVG libraries load.
Web views and system decoders use the operating system’s installed runtimes.
That makes a writable temp directory a requirement, and
-Dgoldberry.native.library is the way out of one that is read-only or
noexec.
Why there are two commands
A closed world has to know every foreign function the program will call before it
runs, and Goldberry’s are not knowable from the source: a binding class takes a
SymbolLookup obtained at run time and builds its handles from it, which is what
lets an application choose which libgoldberry it loads. libgoldberry exports
246 symbols, plus six upcalls from five owners: the event watch, the file
dialogs, the tray, the layout engine’s measure callback and the clipboard.
The list and the bindings agree in both directions: an exported
symbol nothing binds is dead weight in every artifact, and a bound symbol nothing
exports is a link error at the first call.
So the first command runs the showcase under GraalVM’s tracing agent and records what it saw — the foreign descriptors, the resources, the reflection Logback does — into
example/src/main/resources/META-INF/native-image/dev.goldberry/goldberry-example/
That path is under src, not build: the metadata is source. It is reviewed in a
diff, it changes when the application does, and being inside the jar is what lets
a downstream image build find it without being told.
The trace is only as good as the run, and that is why resources are not
traced. :core, :widgets and :example each ship a
META-INF/native-image/…/reachability-metadata.json declaring their own files by
glob, because that set is finite and a directory listing cannot be one screen
short. A stylesheet or a font the far side of a toggle the run never flipped is
not in a trace.
Because those declarations travel in the jars, an application building its own image gets the toolkit’s resources without knowing it needs them.
What is traced — the reflection, the services, the upcall stubs — really does depend on what the code did, and the warning applies to it unchanged: a screen the run never reaches contributes nothing. Re-run the metadata task after adding one, and read the diff.
The FFM descriptors are not traced. A holder links its handle in its class
initializer, but a …Calls record binds when its wrapper is first used, so a
run that opened no Markdown would initialise no MarkdownCalls and a trace would
record none of its five functions. :natives:foreignMetadata initialises every
holder and every upcall owner and writes the foreign section itself, into the goldberry-natives jar under
META-INF/native-image/, where native-image reads it for any application.
The image is woven, the jar is not
nativeImage depends on weaveModels, and the build orders it before jar.
That is not a detail: an image built from classes the weaver has not run over would bind its models
by reflection, which is the one thing an image must not do. nativeImage arranges
it for you. Ahead-of-time binding covers an image
built without this task.
What the flags are for
| Flag | Why |
|---|---|
--module-path / --module | The showcase runs modular, as it does everywhere else |
--enable-native-access=…natives | JEP 472, naming the one module that touches native code |
--no-fallback | Not passed. A fallback image is a JVM in a trench coat. GraalVM 25.3 builds none, and the flag only warns that it has no effect |
-H:+ReportExceptionStackTraces | Names the class that could not be reached, rather than a stack in the builder |
Nothing about class initialization is passed here. :natives ships its own
META-INF/native-image/dev.goldberry/goldberry-natives/native-image.properties
naming the two classes that have an opinion, and they are opposite opinions:
| Class | When | Why |
|---|---|---|
NativeLibrary | run time | It dlopens in its initializer, which must not happen in the builder |
Downcalls | build time | It holds the shared Linker, and every holder’s initializer calls Downcalls.link |
the …calls packages | build time | A downcall handle is only a call if it is a compile-time constant, and only a build-time initializer makes it one |
They are packages and they have to be. A holder is a nested class, and naming
its enclosing class does not reach it. The call then costs 4538 ns against 8,
silently, because the image builds and runs. Naming a hundred and thirty-four
nested classes in a flag is not a list anyone can maintain, and naming the
binding packages instead would build-time initialize the binding classes
themselves, whose holder idiom dlopens the library in the builder. So the holders live in
packages that contain nothing else.
All of them travel in the jar, so an application building its own image gets them without knowing they exist, as it gets the resource declarations.
The one flag the frame rate depends on
GraalVM’s FFM downcalls are not optimized — oracle/graal#8113
lists it as open work, and it costs a factor of 450 on the call itself. Goldberry
takes the workaround: a holder’s FD_<symbol> handle is unbound (it takes the
address to call as an argument), so it can be linked while the image is being
built, which is what turns it into a constant the compiler can lower into a
direct call.
Sixty frames of the showcase, headless (--resize=WxH walks the
window a pixel a frame while it runs, and --late-budget=N fails the run past N
missed refreshes):
./example/build/native/goldberry-showcase-linux-x64 -Dgoldberry.backend.videoDriver=dummy --frames=60
| 60 frames | per frame | |
|---|---|---|
without the --initialize-at-build-time lines | 2.55 s | 42.5 ms |
| with it | 0.061 s | 1.0 ms |
The same rule applies one level down, and it is the trap to know before editing a
binding: a downcall handle has to be read by the method that calls it. Passing
one into a helper as an argument costs 810 ns a call in an image against 8.9 ns
when the helper names the constant itself — the JVM inlines and folds it, and
native-image does not. That is why a holder’s call names its own
FD_<symbol> field rather than taking a handle, and why the handle is
static final on the holder rather than a component of it: an instance field is
a value read from an object, not a constant read from a class, and measures
4540 ns/call.
And the list of packages is its own hazard. native-image.properties is the
one file in :natives that nothing compiles, runs or reads — it is a hand-typed
package list consumed by a tool that is not part of this build — so a package
added to the module and not to the file is invisible in every way but the
measurement above. The shipped resource is held to
ForeignSurface.holderClassNames(), with one deliberate exception:
desktop.calls stays out, because PortalSettings binds a
dozen desktop-bus functions in a static initialiser. Build-time initialising it
either fails the image with a MemorySegment in the image heap or bakes the
build machine’s session bus into it.
Nothing fails when it is missing. The image builds, runs, paints correctly
and is forty times slower. It is silent because the generated metadata registers
the descriptors anyway. A descriptor registered nowhere raises
MissingForeignRegistrationError and names itself. To see the difference, move the properties file aside and rebuild passing
the run-time half by hand:
./gradlew :example:nativeImage -Pgraalvm.home=… \
-Pgraalvm.args="--initialize-at-run-time=dev.goldberry.natives.NativeLibrary"
Two metadata directories: traced, and written
The agent’s output goes to
META-INF/native-image/dev.goldberry/goldberry-example, and nothing
hand-written goes in there — the next trace overwrites it. Anything a human has
to add lives in the sibling …/goldberry-example-manual. native-image reads
every META-INF/native-image/** it finds, so the two are merged for the tool and
kept apart for the diff.
It holds one entry:
{ "module": "dev.goldberry.example", "glob": "logback.xml" }
Logback asks a ClassLoader for logback.xml, so the agent records it as a
classpath resource. The image runs on the module path, where that file is at
the root of a named module and has to be registered against that module or it is
not there at all. The symptom is the worst kind: with no configuration found,
logback ends with no appenders and prints nothing — not even its own status — so
an image that is working perfectly looks like an image that is doing nothing.
The general shape of that trap is worth remembering: the agent records how a
lookup was made, not where the file will be. A resource fetched through a
ClassLoader by a library that knows nothing of modules is recorded without one.
An application’s own logback.xml is the same file with the same trap, so it
belongs in that application’s hand-written directory too.
In a native image, Logback’s search for duplicate configuration files can
trigger DNS lookups when a module-resource URL is hashed. To give Logback
the file directly, register a Configurator that loads the module’s
logback.xml with JoranConfigurator and returns DO_NOT_INVOKE_NEXT_IF_ANY.
The Showcase uses this approach.
What the trace does not record
The trace records no widget class, neither the toolkit’s nor an application’s.
The element tree asks the two widgets for their restyle answer and compares
them, so no widget class is reflected on, and every class in
dev.goldberry.widget is in a closed list, as a model bound ahead of time is.
The natives jar is a module
Each classifier jar names itself: dev.goldberry.natives.linux_x64,
dev.goldberry.natives.linux_aarch64, dev.goldberry.natives.macos_aarch64,
dev.goldberry.natives.windows_x64. A modular build keeps it on the module
path instead of splitting it onto the class path.
Nothing requires a platform’s module, so the JVM does not resolve it, and
NativeLibrary reads the library from the module path anyway: this module, the
system class loader, then the jar on --module-path by its name. The library’s
directory is not a package name, so nothing has to be opened.
native-image is the exception. An image takes only resolved modules, so
the natives jar either stays on -cp, which is what the showcase does, or
goes on the module path with --add-modules dev.goldberry.natives.<target>.
Why the library is carried rather than linked
Statically linking the archives into the image is the obvious answer and it does
not work. The linking part is fine — -Wl,-u,<symbol> pulls the code in, given
-lstdc++ and -lm which native-image does not pass. What fails is that
Goldberry resolves every native function by name at run time, so the symbols
have to be in the executable’s dynamic symbol table, and native-image links with
its own --version-script that makes everything it does not list local.
--export-dynamic-symbol does not beat it, and a second version script is refused
outright — “anonymous version tag cannot be combined with other version tags”.
What is not built
No image task in build. Neither task is wired into build, because a
local build has no GraalVM to count on. A release of the showcase carries an
image for each of the three platforms on its GitHub Release.
No image of the toolkit on its own. :core and :widgets are libraries; an
image is a property of an application, and :example is the application here.
Contributing
Goldberry is Apache 2.0 with no contributor agreement, and every change passes the same gates whether it comes from a maintainer or from a stranger.
A change is a pull request against master on GitHub. This chapter says what the repository expects of one. The five chapters after it say how to build, where things live, what the tests check, how a release goes out, and how a decision is written down.
The licence
The code is under the Apache License 2.0. There is no CLA to sign. A pull request is a contribution under that licence, and LICENSE and NOTICE ship inside every jar under META-INF.
Third-party software is disclosed in THIRD-PARTY-NOTICES.md and licenses/, and the two are held together by a task:
./gradlew checkLicenses
A dependency named in one and not the other fails the build.
What a change passes
./gradlew check is the gate. CI runs the same thing on Linux, macOS and Windows, and a pull request is green only when all three are.
| Gate | What it holds | Fixed by |
|---|---|---|
| Formatting | Every Java file matches palantir-java-format | ./gradlew spotlessApply |
| Error Prone and NullAway | src/main compiles with no finding, and every package is @NullMarked | Reading the finding |
| PMD | The hand-picked rules in config/pmd/ruleset.xml | Reading the finding |
| SpotBugs | Reports only. build/reports/spotbugs/main.html per module | Nothing. It does not gate |
| Tests, twice | The suite passes bound reflectively and again bound ahead of time | The test, or the code |
| Goldens | Every reference image matches what the code draws | ./gradlew blessGoldens, then review the diff |
| Export list | Every symbol bound in Java is exported, and nothing exported is unbound | Editing goldberry.symbols |
package-info | Every package has one, with a doc comment and @NullMarked | Writing it |
| Javadoc | A [link] in a published module resolves | Fixing the link |
| Markdown | No trailing whitespace, a final newline | ./gradlew formatMarkdown |
| Licences | THIRD-PARTY-NOTICES.md and licenses/ agree | Editing both |
Tests and gates says what each one runs and why.
Tip
Run
./gradlew spotlessApply checkbefore pushing. The formatter is the one gate that fixes itself.
A widget arrives whole
A new widget is not done when it draws. Before review, it arrives with:
- a row in the widget specification, in the
core-widgets.mdformat; - a row of design-system metrics;
- a card in the showcase gallery, on the screen of the chapter that documents it, linking that section;
- semantics assertions, so the sweep finds a role and a name;
- golden images, in both themes and at both densities.
The gallery is the demo, the visual-regression corpus and the accessibility sweep at once, so a widget that is not in it has no visual or accessibility test. The gallery has a screen per chapter of this guide and a card per section, and GalleryDocsTest fails on a section with no card, a card with no link, or a link to a heading that does not exist. Writing a widget walks through the code. The sweeps that read the registry are in Tests and gates.
Decisions are recorded
A change that chooses between designs gets an architecture decision record beside the code, in the same pull request. The log is read on GitHub. Recording a decision says how to write one and what the build checks about it.
The chapters
Where to ask
Open an issue at https://github.com/DigitalSmile/goldberry/issues. A bug report is most useful with the platform, the display scale, and the start-up timeline the toolkit logs at TRACE. Logging and diagnostics says how to turn that on.
Status says what is built, and TODO says what is left out and why. A question that one of those answers is answered there first.
Building from source
One command builds and tests every Java module and the native library for this machine, and one property leaves the native library out.
The JDK
The build needs a JDK 25 toolchain. Gradle provisions one if it cannot find one, so the only hard requirement is a JDK that can run the Gradle wrapper.
./gradlew build
That compiles and tests every Java module. It also builds libgoldberry for this machine when the library is missing or out of date.
The native superbuild
libgoldberry is one shared library per platform. A CMake superbuild statically links the native dependencies into it: the rasterizer, the layout engine, the text shaper, the windowing layer, the Markdown parser and the WebP codec. Building it needs CMake 3.28 or newer, Ninja and a C/C++ toolchain.
Check for them first:
./gradlew :natives:checkToolchain
The task prints the absolute path and version of each tool it will use, and names the packages to install if anything is absent. On Linux it also names the desktop development headers the windowing layer needs, in terms of apt or dnf.
The tools are searched for on the PATH first and then in the usual install directories. A Homebrew, MacPorts, CMake.app or pip install --user toolchain is found even from a Gradle daemon that an IDE started with a bare PATH. To point at a tool somewhere else:
./gradlew build -Pgoldberry.cmake=/path/to/cmake # also -Pgoldberry.ninja
Caution
The first native build downloads about 330 MB. The superbuild clones the upstream sources of the native dependencies. Git reports its progress as it goes, so a configure step that looks idle is a slow connection rather than a stuck build.
The clones land in natives/.deps/<target>, outside build/, so ./gradlew clean does not throw them away. To discard them on purpose:
./gradlew :natives:cleanNativeDeps
Once the sources are present the build is about a minute of work. Every upstream is pinned in gradle/libs.versions.toml, and the superbuild reads that file itself, so a pin that moves reconfigures the build.
Java only
For a build with no native toolchain:
./gradlew build -Pgoldberry.skipNative=true
Tests that need real native code skip when no library is loadable, so this stays green. It verifies less: nothing that shapes text or paints a pixel runs. CI’s Java jobs build this way, and the per-platform jobs run the rest against the library they built.
The properties
Everything the build reads, in one place:
| Property | What it does |
|---|---|
-Pgoldberry.skipNative=true | Builds no native library. Everything that needs a rasterizer skips |
-Dgoldberry.native.library=<path> | Runs the tests against a library built somewhere else, and builds none |
-Dgoldberry.native.required=true | Turns those skips into failures. CI’s native legs pass it |
-Pgoldberry.allowDegradedPlatform=true | Builds the library without the desktop-integration headers, on a machine that has none. The library it produces reports no capabilities |
-Pgoldberry.depsDir=<path> | Where the superbuild’s upstream checkouts live, instead of natives/.deps/<target> |
-Pgoldberry.cmake=<path>, -Pgoldberry.ninja=<path> | A tool somewhere the search does not look. Taken at its word |
-Pgoldberry.nativeImage=true | Binds @Bind and @Action ahead of time, into the compiled classes, which is what a native image runs |
-Pgoldberry.lenient | Turns Error Prone off. For triage only, never for a green build |
-Pgoldberry.nullaway=warn | Demotes NullAway from error to warning, for a sweep |
-Pgoldberry.golden.update=true | What blessGoldens passes: rewrites the reference images from what the code draws |
-Pgoldberry.example.frames=N, -Pgoldberry.example.size=WxH | Runs the showcase for N frames, at a size, and exits |
-Pgoldberry.backend.videoDriver=dummy | Runs the showcase against the dummy video driver, with no compositor |
-Pgoldberry.gpu.videoDriver=offscreen, -Pgoldberry.gpu.required=true | The GPU tests’ driver, and whether a missing device is a failure |
A library built somewhere else
Released artifacts are built on native runners per platform, so a locally built library is for development only. A .so from a developer machine links against the host’s glibc and has a higher floor than the published one. Only the container build in CI ships.
To check a library built somewhere else, a CI artifact or a colleague’s build, point the tests at it instead of building one:
./gradlew :natives:test \
-Dgoldberry.native.library=/path/to/libgoldberry.so \
-Dgoldberry.native.required=true
Supplying a library is also what tells the build not to build its own. Adding goldberry.native.required=true turns “no library, skip quietly” into a failure, which is how CI verifies that the artifact it just built loads.
Running the showcase
:example is an ordinary subproject that runs on the module path, which is what catches an unexported package or a wrong --enable-native-access.
./gradlew :natives:cmakeBuild # once, to build libgoldberry
./gradlew run
On the first run, :example:prepareAssets fetches the spelling dictionary and
the Unicode emoji table. It prints the asset and its URL on a cache miss. A
download times out after 30 seconds waiting for headers or for the next body
data and gets up to four attempts. Downloads verified by SHA-256 are reused
from .gradle/assets.
A window opens, maximized, with a menu bar, a bar that reports what start-up cost, and a gallery of seventeen screens. To paint a few frames and exit, which is what CI does under Xvfb:
./gradlew run -Pgoldberry.example.frames=3
To drive it without touching the real compositor:
./gradlew run -Pgoldberry.example.frames=3 -Pgoldberry.backend.videoDriver=dummy
Warning
SDL_VIDEODRIVER=dummyin the environment does not reliably reach the application. A GradleJavaExecfork inherits the daemon’s environment rather than the shell’s. Use the property.
Caution
GNOME Shell 46 segfaults in its own
wl_client_destroypath when this client disconnects. An accidental real run on that desktop costs a session. Status has the details.
The native image
The showcase also builds as a GraalVM native image, one file with libgoldberry inside it. It needs a GraalVM and a C toolchain with the zlib development package:
./gradlew :example:nativeImage -Pgraalvm.home=/path/to/graalvm
./example/build/native/goldberry-showcase-linux-x64
Native image has the whole recipe, the metadata, and what to do when the image fails at the last step with cannot find -lz.
Platform notes
macOS
AppKit has to be driven from the process’s first thread, so any Goldberry application needs -XstartOnFirstThread. ./gradlew run passes it for you. An application of your own passes it itself, as any JVM application that drives AppKit does. Without it the windowing layer fails to start with “No available video device”, which says nothing about threads.
Only macos-aarch64 is built.
Linux
The windowing layer compiles its X11 and Wayland drivers in only where the development headers are present, and several of the X11 ones are hard stops: the configure fails at the first one it cannot find. checkToolchain names every package before CMake runs. The table it reads is LinuxDependencies in build-logic, and a test holds it to what CI installs.
Its desktop-bus, input-method and device-hotplug support is different. It compiles out silently, into calls that succeed and answer nothing. The superbuild probes for those headers and stops rather than shipping a library that cannot ask the desktop anything. On a machine that has none:
./gradlew build -Pgoldberry.allowDegradedPlatform=true
The library that produces reports no capabilities, so an application can tell “this desktop has no such setting” from “this build cannot ask”.
Windows
libgoldberry on Windows is built with MSVC. Open an “x64 Native Tools Command Prompt for VS 2022”, or run vcvars64.bat, and build from that shell, because cl.exe is on the PATH only there. The build does not leave the compiler to a search: checkToolchain resolves cl.exe the way it resolves cmake and refuses when it is absent. It has to, because a MinGW cc.exe on a stock runner configures without complaint and writes a libgoldberry.dll that depends on libstdc++-6.dll. The library an MSVC build writes is goldberry.dll, which is what goldberry-natives ships.
Every CI step on Windows runs in bash, so ./gradlew means the same script on all three runners and -Pgoldberry.skipNative=true is not split at the dot by PowerShell.
The IDE
Import the root project. :example is a subproject, so the IDE sees it with the rest and ./gradlew run is a run configuration like any other. Keep the showcase on the module path: an unexported package and a wrong module name fail there and nowhere else.
A Gradle daemon that an IDE started carries the environment the IDE was launched with, which on macOS is launchd’s four directories and no Homebrew. The build does not depend on it. Every native tool is resolved to an absolute path once, and both the check and the use run that path. If checkToolchain prints a tool you did not expect, -Pgoldberry.cmake overrides the search.
Note
build-logicis an included build with tests of its own../gradlew :build-logic:testruns them, and:natives:checkruns them as part of the ordinary build.
Repository layout
Thirteen Gradle modules, nine of them published, and a package rule that lets you read the pipeline off the package list.
The modules
settings.gradle is the map. Every published artifact is goldberry-<module> under the group dev.goldberry.
| Module | Artifact | What it holds | Published |
|---|---|---|---|
:common | goldberry-common | What both halves need and neither owns: logging and the start-up timeline. The lowest module, it requires nothing of Goldberry’s | Required |
:natives | goldberry-natives, plus a classifier jar per platform | The FFM bindings and the CMake superbuild that produces libgoldberry | Required |
:core | goldberry-core | The widget model, style, layout, text, paint and the backend SPI | Required |
:widgets | goldberry-widgets | The widget catalogue, charts included | Required |
:html | goldberry-html | Markdown through the native library, and HTML in Java | Optional |
:emoji | goldberry-emoji | The Noto Color Emoji face and nothing else, 5 MB of paint graphs | Optional |
:gpu | goldberry-gpu | canvas3d and the GPU composition path | Optional |
:media | goldberry-media, plus natives-<target> classifiers | Audio and video over the bundled media engine, and the operating system’s own decoders behind the same SPI | Optional |
:vector | goldberry-vector and natives-<target> classifiers | SVG rendering and a themed SVG widget | Optional |
:mic, :camera | goldberry-mic, goldberry-camera | Audio and video capture | Optional |
:spell | goldberry-spell | Optional Hunspell provider | Optional |
:bom | goldberry-bom | A java-platform pinning every published artifact | Yes |
:toolkit | goldberry | The umbrella: no code, the required modules as dependencies, the optional ones listed <optional> | Yes |
:assets | none | A build-time tool that fetches the pinned fonts and icon set and compiles them into resources :core packages | No |
:weaver | goldberry-weaver | A build-time tool that runs over compiled classes: it collects @Markup widgets into a catalog, and binds @Bind and @Action ahead of time for a native image | Yes |
:gradle-plugin | dev.goldberry.weave | Gradle support for ahead-of-time binding | Yes |
:example | none | The showcase. A subproject so Gradle and every IDE see it | No. A native image of it is attached to each release |
A new optional module is one line in PublishedModules in build-logic plus id 'goldberry.publish' in its build script. The BOM and the umbrella pick it up, and PublishedModulesTest holds each module’s build script to the list.
The package rule
A package is named for the part its contents play, not for the library or the file they came from. The CSS engine is a compiler, so it is css.parse, css.select, css.cascade and css.value. Input is a dispatcher, so it is input.event, input.key, input.hit and input.handler. A native library is split where the foreign memory stops: the wrappers that hold a handle stay beside the binding class, and the enums and values get packages of their own. The module descriptor is the fence.
Every package has a package-info.java whose doc comment says what the package is for and whether, and to whom, it is exported. Every package of a module under the conventions is @NullMarked, so NullAway sees it. PackageInfoTest in build-logic fails on a package with no package-info.java, on one without a doc comment, and on one that is not marked.
Important
A raw
MemorySegmentnever leaves:natives. The module descriptor enforces it,ExportedSurfaceTestreads the descriptor and fails if anything reachable from outside mentions one, and:nativesexports to:coreand to nobody else.
Where things are
| Path | What it is |
|---|---|
docs/ | The design documents. ARCHITECTURE.md is the system layer by layer. core-widgets.md, design-system.md, content-widgets.md and charts.md are the specifications. testing.md and releasing.md are the runbooks, book.md is the guide’s style guide, and status.md and TODO.md say what is built and what is not |
book/ | This guide, and the decision log under book/src/adr/ |
site/ | The landing page at goldberry.dev. build.mjs prerenders it and content.js is what it says |
build-logic/ | The convention plugins, and the drift guards in its tests |
natives/src/main/cmake/ | The superbuild: CMakeLists.txt, the export list in exports/goldberry.symbols, and the C shim |
assets/ | The fetch-and-compile tool for fonts and icons |
weaver/ | The class-file weaver |
example/ | The showcase |
config/ | The PMD ruleset, the SpotBugs exclusions, and Qodana’s profile and baseline |
gradle/libs.versions.toml | Every version and every upstream ref. The only place a ref lives |
licenses/ | The verbatim upstream licence texts, vendored by hand |
tools/ | Scripts: the nullness sweep, and move_package.py for a package move |
Which document wins. design-system.md and core-widgets.md are the authority on what a widget is. ARCHITECTURE.md is a summary of them and says where it departs from them, in its §17.1. The decision log is the authority on why, and a design document describes what. Status says what is built and TODO what is not, and the two are kept apart on purpose.
The convention plugins are seven precompiled Groovy script plugins under build-logic/src/main/groovy/, thin over the Java beside them, which carries the logic and its unit tests:
| Plugin | What it configures |
|---|---|
goldberry.java-conventions | The toolchain, the module path, Error Prone and NullAway, Spotless, PMD, SpotBugs, JaCoCo, blessGoldens, PIT, and the CI annotations; it applies goldberry.benchmarks |
goldberry.benchmarks | The src/benchmark/java source set and the benchmark task, one module at a time; check only compiles it |
goldberry.native-tests | Every test task of a module whose tests load libgoldberry: the grant, the library, the forwarded properties, the native build first; and nativeTests.gpuTests(...) and nativeTests.probe(...) |
goldberry.asset-tool | assetTool.bundle(entries, package): prepareAssets into the resources, and vendorLicences |
goldberry.versioning | The group and the calendar version, printVersion and bumpVersion |
goldberry.publish | The Maven Central publication, applied by the shipped modules and refused anywhere else |
goldberry.weave | The weaver over a module’s compiled classes, catalog half always and model half for a native image |
No build script reads another project’s configuration. What one module’s tests share with another’s is a test fixture — :natives’ library and GPU requirements and its first-thread launcher, :gpu’s compositing harness, :core’s goldens and TimeBudget — and the native target matrix is NativeTarget in build-logic rather than a table :natives lends out.
The build is written in the Groovy DSL. The root build.gradle is a container: it aggregates coverage and owns checkLicenses, checkMarkdown, formatMarkdown and the root blessGoldens.
Tests as drift guards
A fact that has to be true in two places gets a test that reads both.
| Test | Reads | Holds |
|---|---|---|
LinuxDependenciesTest | The dependency table and the workflows | Every required package is installed by the workflows that run checkToolchain |
ExportListTest | goldberry.symbols and the Java bindings | A symbol bound in Java is exported, and a symbol exported is bound |
PackageInfoTest | Every package directory | A package-info.java, a doc comment, @NullMarked |
DecisionLogTest | book/src/adr/ and its README.md | Numbered, contiguous, with a status, and listed in the log’s index |
PublishWorkflowsTest | .github/workflows/ | Only publish.yml uploads to Central, and the per-OS workflows have no push trigger |
PublishedModulesTest | Each module’s build script | The published list and the scripts agree |
DeclaredResourcesTest | src/main/resources | Every resource is covered by a native-image glob |
ExportedSurfaceTest | :natives’ descriptor and class files | No reachable member mentions MemorySegment |
WrittenNamesTest | The weaver’s constants | Every class name the weaver writes as text resolves |
BoundaryTest, DeterminismTest | The whole graph, through ArchUnit | The module arrows in ARCHITECTURE.md §2, and no clock, random source or default locale in the deterministic layer |
SiteTest | site/content.js and the book | The pages the landing page links by name are where it says |
SourceDocsTest | Every Java, Gradle and workflow source, and the book | No record number in a source; every goldberry.dev/docs link lands on a page and a heading that exist; every published package links the guide; no Java source names a file under docs/ |
BenchmarkLaneTest | Every source tree, the build scripts, docs/testing.md and the workflows | No benchmark in a test tree or under a tag; every probe task runs a class in its module’s src/benchmark; every measurement is in the inventory; only benchmarks.yml runs one |
ForwardedPropertiesTest | The workflows | Every switch a workflow sets for a test JVM is on the one list the build hands on |
NativeTargetTest | natives/build.gradle and media/build.gradle | The libraries are installed where every module’s tests look for them |
Most of these live in build-logic/src/test/, which ./gradlew :build-logic:test runs. The ArchUnit pair lives in :widgets, because that is the module whose test classpath holds the whole graph.
The export list and the layout probe
natives/src/main/cmake/exports/goldberry.symbols is the list of symbols libgoldberry exports, and the library exports exactly those and nothing else. The file states its own rule: a symbol bound in Java but missing here fails at load time, and a symbol here that nothing binds is dead weight. ExportListTest enforces both halves by reading the two files as text. It needs no library, because the question is what the source says.
The bindings are hand-written rather than generated. The check that rests on is the layout probe: libgoldberry exports a table of every struct’s size and every field’s offset, and LayoutVerificationTest compares it against what the Java side declares. It needs a built library, so it skips without one and fails under -Dgoldberry.native.required=true. CI’s verify legs pass that flag on every platform.
Tests and gates
Pixels are the assertion for painters, every suite runs in both binding modes, and a cost is guarded by a count rather than a clock.
This chapter is what a contributor needs before the first pull request.
Principles
- Determinism is a feature under test. Embedded fonts, CPU rasterization, seeded randomness and a virtual clock make output byte-stable. The suite asserts exact results, and nondeterminism is itself a bug.
DeterminismTestbans clocks, randomness, the default locale and the default time zone in the layer whose output is asserted exactly. - Pixels are the assertion for painters. Line coverage of paint code proves reachability. Golden images prove correctness. Logic modules are asserted the classic way.
- Both execution modes are first-class. Every suite runs bound reflectively, which is what a jar does, and again bound ahead of time, which is what a native image does. The two must agree, and CI runs both.
- A widget is not done until it is in the gallery. The showcase is the demo, the visual-regression corpus and the accessibility sweep at once.
- Test the seams that break silently. Native struct layouts, cascade order, cache invalidation, focus order. Not getters.
The test kinds
| Kind | What it is | Where |
|---|---|---|
| Unit | JUnit 5 over pure logic with exact assertions: the CSS compiler, KDL and the inflater’s errors, layout property mapping, text segmentation, tick labelling, aggregation, easing, binding paths. jqwik property tests over the chart stack | Every module |
| Headless widget | The headless backend renders to memory and pumps synthetic events through the normal dispatch path. A virtual clock steps animations. Every test task presses Ctrl as the primary modifier on every desktop | :core, :widgets, :html, :example |
| Golden | A rendered frame against a committed PNG, with a tolerance | :widgets, :core, :html, :example |
| Native layer | The layout probe, the export list, FFM lifecycle, and the GPU tests on the JVM’s first thread | :natives, :gpu, :media |
| Benchmark | JUnit classes and probes under src/benchmark/java. They print numbers and assert almost nothing | ./gradlew benchmark and the Benchmarks workflow; check only compiles them |
| Accessibility | Contrast over the token tables, and sweeps that read the widget registry | :widgets |
| Drift guard | A test that reads the repository rather than the JVM | build-logic, :natives |
Repository layout lists the drift guards.
What check runs
./gradlew check
In every module under the conventions, check runs:
- the compile, with Error Prone and NullAway as errors in
src/main; spotlessCheck,pmdMain, and SpotBugs as a report;test, and in:natives,:gpu,:mediaand:examplealsogpuTest;benchmarkClasses: the benchmarks compile, and none of them runs;jacocoTestCoverageVerification, which passes trivially where a module declares no floor;javadoc, in every published module, with doclint on;- in
:natives, the tests of the includedbuild-logicbuild.
CI’s fast lane adds checkLicenses and checkMarkdown, and then runs the suite a second time, bound ahead of time:
./gradlew build checkLicenses checkMarkdown -Pgoldberry.skipNative=true
./gradlew test -Pgoldberry.skipNative=true -Pgoldberry.nativeImage=true
Two invocations rather than two tasks, because the weaver rewrites the compiled classes in place and one build cannot hold both forms. Coverage survives the split: the exec file is named for the mode and the report reads every file it finds.
Important
-Pgoldberry.lenientturns Error Prone off and is for triage only. Nothing in CI sets it, sochecknever passes with it.
With and without the library
Every module whose tests load libgoldberry applies one plugin, goldberry.native-tests, and every test task in it gets the same wiring: JEP 472’s grant, the library named by -Dgoldberry.native.library or else the one this machine’s :natives:cmakeBuild makes, that library as an input so a rebuilt one re-runs what paints through it, and cmakeBuild first unless -Pgoldberry.skipNative=true asks for a Java-only build or a library was handed over. The switches a test reads from the command line — goldberry.native.required, goldberry.golden.update, goldberry.gpu.videoDriver, goldberry.timing.slack and the rest — reach every test JVM from one list in build-logic, ForwardedProperties, so a flag cannot work in one module and stop at the Gradle daemon in the next.
The Java-only jobs build with -Pgoldberry.skipNative=true, so a test that rasterizes calls RendererRequirement.enforce() first and skips without a library. To check a change the way those jobs will, point the library at nothing and run everything:
./gradlew test --continue -Dgoldberry.native.library=/nonexistent/libgoldberry.so
Failures there are the defect. Skips are correct.
The per-platform jobs do the opposite. They download the library their native job built and pass -Dgoldberry.native.required=true, so a skip is a failure. CI verifies the binary that ships and cannot pass without loading it.
The web view library, libgoldberry-webview, may be missing from a local build where the web view engine’s development headers are absent, so its tests skip without it. A published one may not: CI builds it for every target. On Linux it is built in a job of its own on Ubuntu 22.04, because the manylinux image has no web view engine to build against. Every verify job puts it beside libgoldberry and passes -Dgoldberry.webview.required=true, so WebviewBindingTest fails rather than skips if the library does not load, report the right ABI and bind.
The GPU tests
GPU tests are tagged gpu, left out of test, and run by :natives:gpuTest, :gpu:gpuTest, :media:gpuTest and :example:gpuTest on the JVM’s first thread, which macOS’s Cocoa needs for a GPU device. They need a video driver with a Metal view or a Vulkan surface: the desktop’s default, or -Pgoldberry.gpu.videoDriver=offscreen for lavapipe on a runner with no display, and never dummy. They skip without a device, and -Pgoldberry.gpu.required=true makes that a failure.
Ray-tracing tests that use the independently opened Vulkan device run
under :gpu:test. Select the software Vulkan device with
-Pgoldberry.raytracing.device=llvmpipe. Use
-Pgoldberry.raytracing.required=true on a runner that supports the test.
The live tray suite opens and drives a desktop tray on macOS and Windows.
Use -Pgoldberry.tray.required=true in a suitable desktop session.
Goldens
A golden compares a rendered frame against a committed PNG. One reference set serves every platform, compared with a per-channel tolerance of 2 of 256 and a cap of 2% of pixels allowed to differ at all. Both gates must pass. The rasterizer compiles its pipelines at run time for the CPU it finds, AVX2 on one runner and NEON on another, and the pipelines are not required to agree on the last bit of a blended subpixel. The tolerance absorbs antialiased edges and nothing else: a colour that changed or a box in the wrong place moves thousands of pixels by tens of levels.
The scale sweep. Every golden that matches is then redrawn at 2x and 1.5x and checked for describing the same picture, with nothing further committed. A layer blitted at the wrong size is invisible at 1x, and the sweep is what sees it. -Dgoldberry.golden.scales=false turns it off.
Goldens render through the shipped Offscreen entry point, so every golden also tests the API an application would use to take the same picture.
A golden does not photograph the machine. Some screens show what the build machine has, such as the capabilities libgoldberry was compiled with, or whether the web view and the media engine are there. Each of these is pinned for the picture. The test task points the web view and the media engine at nothing. ShowcaseScene hands every screen a fixed set of capabilities instead of Goldberry.capabilities(). A screen that reads anything else from the machine takes it from its GalleryContext too.
Blessing a change. After a deliberate visual change:
./gradlew blessGoldens
git diff --stat
The task runs the whole suite with goldberry.golden.update=true and rewrites every reference from what the code draws. It is not part of check, because a build that re-blessed on every run would assert nothing. Commit the PNGs and explain the visual change in the pull request. The image diff is the review. A golden failure in CI uploads the actual, expected and diff images as a run artifact.
Static analysis
| Tier | Tool | Scope | What it does |
|---|---|---|---|
| Blocking at compile | Spotless with palantir-java-format | Every Java file | spotlessCheck fails, spotlessApply fixes. The step is wrapped so an import that only a /// doc link uses is kept |
| Blocking at compile | Error Prone | src/main | A finding is a compile error. Off for tests and JMH sources |
| Blocking at compile | NullAway | src/main, every @NullMarked package | OnlyNullMarked mode, and every package is marked |
| Blocking after triage | PMD | src/main | The hand-picked rules in config/pmd/ruleset.xml. module-info.java is excluded on purpose, because PMD cannot read two modifiers on a requires |
| Reports | SpotBugs | src/main, max effort | build/reports/spotbugs/main.html per module. It does not gate |
| Blocking | ArchUnit | The whole graph, from :widgets | BoundaryTest asserts the module arrows and the FFM boundary. DeterminismTest bans clocks, randomness and the default locale |
| Blocking | Javadoc | Every published module | check generates it with doclint on, so a rotted [link] fails four minutes in rather than partway through an upload |
| Blocking | checkMarkdown | docs/, book/, the top level | Trailing whitespace and a missing final newline. formatMarkdown fixes them |
Note
:nativesruns no Error Prone. It is hand-written FFM bindings, and its contract is the layout probe. It keeps its@Nullableannotations, because:core’s NullAway reads them.
Advisory dashboards
Three more analysers run and none of them blocks a merge:
- CodeQL, in
codeql.yml, on pull requests and weekly. A finding that is not fixed is answered with a reason. The alerts need a token to read, and the same scan runs locally in about six minutes. - Qodana, in
qodana.yml, against a committed baseline inconfig/qodana/. The gate fails on new high-severity findings only. The profile is reviewed as code. It inspectsmainonly. The tests are left out, and so is every other source set,src/benchmarkandsrc/jmh, by name inqodana.yaml;QodanaScopeTestfails on one that is not. - Codecov, a step in
linux.yml, guarded on its secret and silent without it.
Coverage is one of them. JaCoCo measures every module, the Linux Java job aggregates both binding modes into one report and uploads it, and nothing reads the figure as a gate: there is no coverage floor in any module. The figure moves with which tests a machine ran, which decoders it had and which library it loaded, so a number that goes red for the machine’s reasons is read as a dashboard, not a gate.
A cost is guarded by a count
A timing assertion on shared CI hardware fails for reasons that have nothing to do with the code. So the benchmarks live in a source set of their own, print measurements and assert almost nothing, and check only compiles them:
./gradlew benchmark # every module, one at a time
./gradlew :widgets:benchmark --tests '*TextAreaFrameBenchmark*'
No pull request, push or snapshot runs them. The Benchmarks workflow does, by hand or when the nightly workflow calls it, and the nightly does nothing on a night master has not moved.
What check is owed instead is the counting pair. TextAreaKeystrokeCostTest asserts that typing into a 500 kB note shapes and draws about what typing into a 2 kB note does, in characters, which is the same number on every machine. BlockReuseTest counts blocks built and kept for the Markdown preview. FrameBudgetBenchmark’s style row reads 3.6 ms alone and 20 ms under a parallel Gradle, which is why it is a benchmark and not a gate. Measuring says how to read one.
A clock bound has room
A bound on a measured duration lives in a benchmark and nowhere else. A benchmark that holds a figure compares it with a TimeBudget from :core’s test fixtures, which has two numbers: the bound, a generous multiple of what the operation takes when it works, and the defect, what it takes when it is broken — the timeout it was meant to beat. The allowance may grow towards the defect and never reach it, and -Dgoldberry.timing.slack=3 multiplies every bound by three for a machine known to be loaded; it is 1 when unset and cannot be less.
TimeBudget.of(Duration.ofSeconds(2)).shortOf(Duration.ofSeconds(5))
.assertWithin(elapsed, "the style pass on the Diagnostics screen");
No test under check reads one. A test asserts what holds however the machine schedules it: that a read gives up with the exception the timeout names, that a queue never rises with nothing written, that a close returns. How long each took is not compared with anything. Where the defect is a wait that would never end, a pump that sits its timeout out or a close that waits a 30 s stall out, the wait is made longer than the test’s own @Timeout, so the defect fails on the hang guard every test has and a loaded machine fails nothing. A figure on its own, the sink’s drain rate at 4x, the audio device’s per-pull latency or a count of readings that moved, is a benchmark’s to measure. No test task runs a failed test again.
A delay that goes through the event loop is not a clock bound at all. EventLoop.after reads a clock the loop was given, and TestClock in :core’s test fixtures is one a test moves. DrivenRuntime.install(backend) starts the launcher over it and gives a test three steps: afterTheNextPump, for an event it posted; elapsed(by, then), for a delay; and afterTheFirstFrame, the one wall-clock wait, for the frame hit testing runs against. TooltipTest finds no tooltip at 499 ms and one at 501 ms, PopupLifecycleTest reads a focus-lost a tick past the settle delay, and no machine can make either reading wrong. A test that waits for something to happen polls until it does, with a deadline that only ends the loop, rather than sleeping a fixed time and looking once.
Accessibility sweeps
The catalogue sweeps read the registry, not a list. WidgetParityTest, ImmutabilityTest and ChainingTest walk every widget Widgets.inflater() registers, and each has a theExemptionsAreLive test so an exemption cannot go stale. SemanticsSweepTest reads the source tree and fails on any focusable widget that does not implement Semantics, a role and an accessible name. Contrast is a unit test over the token tables: every text and surface pair at 4.5:1 or better in both themes.
No bridge exports the semantics tree to the platform, and the sweep does not need one.
The CI matrix
| Workflow | Trigger | What it does |
|---|---|---|
linux.yml | Pull request, and every push through snapshot.yml | The Java job: build checkLicenses checkMarkdown without the library, then the suite bound ahead of time, then the coverage report. The natives job builds libgoldberry inside a manylinux_2_28 container, and the web view job its library on Ubuntu 22.04. The verify job runs :natives:test, the :core, :widgets, :html and :emoji suites with every golden, then the GPU tests on lavapipe, and the Showcase tests against the downloaded libraries. The Showcase also runs for 120 frames under a headless Wayland compositor |
macos.yml, windows.yml | Pull request, and every push through snapshot.yml | One job: :natives:cmakeBuild, then ./gradlew build against the library it made with native.required and webview.required, then the upload publish.yml packages. The live tray tests are required on Windows and on the macOS GPU lane |
snapshot.yml | Push to master | Calls publish.yml, which calls all three per-OS workflows and then uploads one -SNAPSHOT of every module to Central |
release.yml | A v* tag. A manual run rehearses into mavenLocal | The same chain as a signed release to a Central Portal deployment, after the licence check, then a pull request that bumps the version |
showcase.yml | A v* tag, or by hand | The native Showcase verifies its packaged libraries and presents 300 frames while resizing on Linux, macOS and Windows. On a tag, the executables are attached to the draft Release |
media.yml | A pull request touching media/, and the publish chain | Builds the media library for four targets and runs :media against the resulting libraries |
vector.yml | A pull request touching vector sources, and the publish chain | Builds SVG support for four targets and verifies the matching library on each |
nightly.yml | 03:40 UTC, when master has moved since the last nightly | PIT mutation testing and SpotBugs, and the Benchmarks workflow. Numbers to read, not gates to pass |
benchmarks.yml | Called by nightly.yml, or by hand with an optional --tests filter | Every module’s benchmarks, one module at a time, and JMH on :core |
codeql.yml | Pull request, and weekly | The security and quality query suite |
qodana.yml | Pull request and push | IntelliJ’s inspections, new findings against the baseline |
pages.yml | Changes to the site, book or changelog, plus scheduled refreshes | Checks the landing page and builds it with this book |
The per-OS workflows have no push trigger of their own. A commit builds each library once, through publish.yml, and the library that passed verification is the one published. PublishWorkflowsTest holds every workflow to it.
A change to site/ alone runs the Pages workflow. Changes to the book
also run the tests that compare examples and screenshots with the code.
A failure names itself. On a runner, every failed test and the build’s own failure become check-run annotations, which the public API serves where a job log needs a login.
Note
Goldens run on every pull request, not behind a label. They are the assertion for painters, so gating them behind a label would mean the check that matters most runs least.
Releasing
A version is a year and a count, every push to master publishes a snapshot, and a release is a tag on the commit that declares it.
Versions
Versions are YEAR.RELEASE[.PATCH]: 2026.1, 2026.2, 2026.2.1. The release count starts at 1 each year, and there is no .0 patch. What a user of a toolkit wants from the number is how old it is, and that is what the year answers.
gradle.properties holds the line being worked towards, and never -SNAPSHOT:
goldberryVersion=2026.1
The build resolves the actual version. Nothing else types the suffix:
| Inputs | Version |
|---|---|
| nothing | 2026.1-SNAPSHOT |
-Pgoldberry.release=true -Pgoldberry.releaseTag=v2026.1 | 2026.1 |
-Pgoldberry.release=true -Pgoldberry.releaseTag=v2026.2 | The build fails, naming both |
goldberryVersion=2026.1-SNAPSHOT in the file | The build fails, and so does BuildVersionTest |
./gradlew -q :core:printVersion
A release tag that does not match the property fails the build before anything is compiled, so a tag pushed on the wrong commit stops at configuration rather than at Central.
Where things go
The group is dev.goldberry, and the artifact ids are goldberry-<module>.
| What | Where | When |
|---|---|---|
goldberry-{common,natives,core,widgets,html,emoji,gpu,media,vector,camera,mic,spell,weaver}, goldberry-bom, goldberry, as -SNAPSHOT | The Central Portal’s snapshot repository | Every push to master |
| The same, released | Maven Central | A v* tag |
goldberry-natives classifiers linux-x64, linux-aarch64, macos-aarch64, windows-x64 | Beside goldberry-natives | With it |
goldberry-media classifiers natives-<target>, one per target the Media workflow built | Beside goldberry-media | With it |
goldberry-vector classifiers natives-<target> | Beside goldberry-vector | With it |
goldberry-showcase-native-{linux-x64,macos-aarch64}.tar.gz, goldberry-showcase-native-windows-x64.exe | The tag’s GitHub Release, created as a draft | A v* tag. A manual run leaves them as the run’s artifacts |
The BOM knows versions and not platforms, so an application adds the goldberry-natives classifier jars itself. All four is the default worth writing, because NativeLibrary picks the right one at run time. Installing has the dependency block.
A release needs the media and vector libraries for all four targets.
Snapshots
Every push to master runs snapshot.yml. It calls publish.yml, which builds Linux, macOS and Windows through the per-OS workflows, then publishes every module and every classifier jar in one Gradle invocation. It has to be one: a snapshot’s classifier jars are listed in the metadata its upload writes, and a runner publishing its own platform would leave Central naming whichever finished last.
So a snapshot appears only after all three platforms are green. One broken platform stops every snapshot, which is the point. Runs are queued rather than cancelled, because an upload stopped halfway leaves a snapshot whose modules disagree about which build they are.
Without the Central secrets, a snapshot run rehearses into mavenLocal and says so in the run’s summary instead of failing.
Preparing the documentation
Review and compact the decision log, promote staged documentation into
the guide, and write an Unreleased changelog with upgrade steps. Update
the site’s news, links and downloads. Build Javadoc across the modules,
and check the guide’s examples and screenshots with the renderer.
Cutting a release
Rehearse. Actions, Release, Run workflow on master. It builds every platform and runs the whole chain into mavenLocal, uploading nothing. Fix anything red before tagging.
Check the licences. The release run enforces it, and a bumped upstream pin means re-copying that component's file from the new checkout.
Write the release's section of CHANGELOG.md, and update the install coordinates and the site announcement to the release version. The section is the body of the GitHub Release.
Tag the commit that declares the version. release.yml publishes to a Portal deployment and opens the tag's GitHub Release as a draft with the notes, and showcase.yml builds the native images and attaches them to it.
Publish in the Portal, then publish the draft GitHub Release, so the binaries and the artifacts appear together. Central takes a few minutes to an hour to sync.
Merge the bump. release.yml opens it as a pull request moving goldberryVersion to the next line.
Step 2 is one command, and releaseCheck turns a warning about an unvendored licence into a failure:
./gradlew checkLicenses -Pgoldberry.releaseCheck=true
Step 3 is a section of CHANGELOG.md, newest first: rename ## Unreleased to the version and the date, or write one. A tag whose version has no section is refused before the release is opened. The notes it makes, through .github/release-notes.md, are one command away:
./gradlew -q :core:releaseNotes # prints the file it wrote, core/build/release-notes.md
Put the release commit on the default branch before pushing its tag. The version-bump job reads that branch after publication.
git tag -a v2026.3 -m "Goldberry 2026.3"
git push origin v2026.3
A release stops in the Portal for a person to press Publish, unless the repository variable CENTRAL_AUTO_RELEASE is true. A release on Central is permanent.
Merge the version-bump pull request so master publishes snapshots of the next line. Maven orders a snapshot before the release with the same number. If the job could only push the branch, this is the command it ran:
./gradlew -q :core:bumpVersion
A patch
A patch is cut from a release branch that declares the patch version. bumpVersion on a patch line moves to the next patch rather than to the next release.
git switch -c release/2026.1 v2026.1
# fix, then set goldberryVersion=2026.1.1, or ./gradlew -q :core:bumpVersion
git tag -a v2026.1.1 -m "Goldberry 2026.1.1"
git push origin release/2026.1 v2026.1.1
Patch branches publish no snapshots. snapshot.yml runs on master only.
The showcase binaries
Every release tag builds three GraalVM showcase executables for Linux x64, macOS
arm64 and Windows x64 and attaches them to the tag’s GitHub Release. Each
executable embeds libgoldberry, the web-view shim, the media codecs with their
layout file and the SVG renderer. Before uploading, the workflow verifies that
the executable opens those libraries and presents 300 frames. Use the manual
Showcase workflow to build the same executables as run artifacts.
The two Unix binaries are tarballs rather than zips, because the zip format the artifact upload writes does not carry the executable bit.
Rehearsing locally
The whole chain without any upload, with stand-in libraries:
for t in linux-x64:libgoldberry.so linux-aarch64:libgoldberry.so \
windows-x64:goldberry.dll macos-aarch64:libgoldberry.dylib; do
mkdir -p /tmp/art/${t%%:*} && echo stand-in > /tmp/art/${t%%:*}/${t#*:}
done
./gradlew publishToMavenLocal -Dmaven.repo.local=/tmp/m2 \
-Pgoldberry.skipNative=true -Pgoldberry.artifactsDir=/tmp/art -x test
-Pgoldberry.artifactsDir is what attaches the four classifier jars, and each jar refuses to build without its library.
The one-time setup
Central’s side is set up by a person, once, and nothing in the repository can check it: the dev.goldberry namespace verified by a DNS TXT record on goldberry.dev, snapshots enabled for it, a user token, a signing key on a keyserver, and the four repository secrets.
Recording a decision
A choice with alternatives and costs gets one immutable record, numbered next in line, and the build checks that it is there.
Why the log exists
docs/ARCHITECTURE.md says what the design is, in the present tense, with the reasoning compressed out. Six months on, nobody can tell which lines are considered choices and which are placeholders that survived because nobody revisited them. The decision log is the reasoning: one record per choice, with the forces that pushed on it, what was decided, what else was on the table, and what it costs. The point is that the reasoning survives the people who did it. The log is book/src/adr/, read on GitHub, and its index lists every record.
A record is reviewed in the same pull request as the code that implements it. Commit messages are keyed to changes, and a decision made across five commits is unrecoverable from them.
When a change needs one
A record is for a choice: there were alternatives, each had a cost, and the next maintainer could undo the choice without knowing what it was load-bearing for. A bug fix is a commit. It becomes a record when fixing it meant choosing between designs, or when the bug was invisible for a reason worth writing down.
Two tests of whether a change needs a record:
- Could a reviewer ask “why not the other way?” and need more than a sentence?
- Would someone a year from now be tempted to reverse it?
A record with no costs listed has not been thought through. If there is nothing to put under Consequences, there was no decision.
The template
Start from the template. Its sections, in order:
| Section | What goes there |
|---|---|
| Title | # ADR-NNNN: Title, or # NNN. Title. The log accepts both |
| Status | Proposed, Accepted, or Superseded by ADR-NNNN. A bullet, or a ## Status section |
| Date | The day it was recorded |
| Relates to | The ARCHITECTURE.md section, and the records it leans on or amends |
| Context | The forces at play. What makes this a decision rather than an obvious call. The constraints stated honestly, including the ones about time or taste |
| Decision | What was decided, in the active voice. One paragraph if possible |
| Alternatives considered | What else was on the table, and the specific reason each was rejected. “It was worse” is not a reason |
| Consequences | What becomes easy, what becomes hard, and what becomes expensive to reverse. The costs, not only the benefits. This is the section future readers come for |
Numbering
Take the next unused number across the index, release staging and
the retired register.
Name the file NNNN-kebab-case-title.md. Once assigned, a number stays with
its decision even when the file leaves the active log.
The build checks that each number is unique, each published or staged record has a matching heading and a status, and each published record appears once in the topic index.
./gradlew :build-logic:test --tests '*DecisionLogTest*'
At release, review the log and retire short operational notes and fixes whose rationale is preserved elsewhere. Record retired numbers and update links to cite a current decision or the original file at a fixed commit.
Status values
| Status | Meaning |
|---|---|
| Proposed | Written down and not agreed. An open question |
| Accepted | Agreed and in force |
| Superseded | Replaced. The record names what replaced it |
Supersession
Records are immutable once accepted. A decision that turns out to be wrong is not edited. A new record supersedes it, the old one gains a Superseded by ADR-NNNN line in its status, and the wrong turn stays visible.
A record may also amend one without superseding it: a matrix that lost two rows, a mechanism that stayed while the numbers changed. The amending record says so in its status, and the amended one gains a blockquote pointing forward.
The log contains records that are wrong. That is intended.
Where a record is linked from
A record is not built into the site, so a link to one is its GitHub address:
[ADR-0063](https://github.com/DigitalSmile/goldberry/blob/master/book/src/adr/0063-data-flows-down-events-flow-up.md)
From docs/, the path is ../book/src/adr/NNNN-slug.md. A chapter of this guide states what the toolkit does and cites no record. A Java doc comment does not cite one either: its reader has a tooltip or a javadoc site, not the repository, so the comment states the rule in plain words and links the chapter of this guide that covers it. Writing a doc comment is the house style.
The title
A title states the decision as a sentence, so the table of contents reads as a list of what was decided:
- A version is a year and a count
- A package is a role, and the module is the fence
- Every package says what it is, and is null-marked
- A preflight check that cannot fail is not a check
Not Versioning, and not Use calendar versions. The sentence is the decision, and a reader scanning the log should be able to stop at the title.
Status and TODO
Two pages in docs/ are updated when a record lands:
- Status says what is built. A record that completes a piece moves its row.
- TODO says what is left for later, what is broken, and what is specified and unbuilt. An entry leaves the top half when a record answers it and moves to Answered rather than being deleted, because each one records a trap somebody hit and the reasoning that got out of it. A record that closes an entry says so in its status.
docs/ARCHITECTURE.md §17.1 lists where the design documents disagree with each other, and a record that settles one strikes the entry through rather than deleting it.
Writing one
Take the next free number. Check the decision log, release staging and the retired register.
Copy 0000-template.md to NNNN-kebab-case-title.md and fill every section. Consequences last, and honestly.
Stage the record for the next release. Add it under its subject in the index when promoting it.
Link it from the status row or the TODO entry it changes, and from any record it supersedes or amends. A chapter of the guide does not cite it.
Run the build-logic tests and checkMarkdown. Put the record in the same pull request as the code.
./gradlew :build-logic:test checkMarkdown
Writing a doc comment
A doc comment tells the reader what the object is, how to use it, and how it works. Then it points at the chapter of this guide that says more. It does not cite the decision log.
Who reads it
A doc comment is read in three places: in an IDE as a tooltip over a name, on
a javadoc site after a release, and in the source by the next maintainer. Only
the last of those has the repository. The first two have the published jar and
a browser, so everything a comment leans on has to be reachable from there.
This guide is, at https://goldberry.dev/docs/. The decision log is not: it is
read on GitHub, and a reader with a tooltip that names a record has nowhere to
go.
So a comment explains, and links the guide. The reasoning behind a choice lives in the log, which is read on GitHub.
The shape
A type’s comment has four parts, in this order. The first is required; the others appear when there is something to say.
- What it is, in one sentence a user of the type would write. Name the
thing, not the mechanism. A row of a word and, sometimes, an icon that
opens a target when pressed says what a
Linkis; the state the inflater builds forlinksays where it came from. - How to use it. For a widget, the markup and the Java that make one. For an API, the call. A short fenced sample beats a paragraph.
- How it works. The mechanics a user needs in order to predict the object: what it holds, what it closes, which thread it runs on, what happens at the edges. The reason for a choice that would otherwise surprise is a sentence here, in plain words: the icon is closed by the state that made it, because nothing else knows it exists. A citation is not a reason.
- Read more, as the last paragraph: one link to the chapter of this guide that covers the type, anchored to its heading when it has one.
/// Text that does something when pressed: an in-app action, an external
/// target, or both.
///
/// ```kdl
/// link action="app.show-docs" "Read the docs"
/// link href="https://goldberry.dev" "Goldberry"
/// ```
///
/// `action=` runs through the application's action registry. `href=` is
/// handed to the desktop's own handler for its scheme, and the link says so:
/// it carries a trailing `external-link` icon and its accessible name ends in
/// "opens outside this window", because a colour cannot say that. The toolkit
/// keeps no history, so `visited` is the application's to set.
///
/// Read more: [Text and links](https://goldberry.dev/docs/components/text.html#link).
public record Link(...) { }
A member’s comment is one or two sentences: what it does and, when the reader would otherwise be surprised, why. It links the guide only when it needs a different page than its type does.
A package-info.java says what the package is for and whom it is exported to,
and its last paragraph links the chapter the package belongs to. Every package
of a published module has such a link, so a reader who lands anywhere in the
javadoc is one click from the guide. SourceDocsTest in build-logic holds that.
The link
A link into this guide is absolute, names the page mdBook writes, and anchors a heading when one fits:
https://goldberry.dev/docs/components/forms.html#text-input
https://goldberry.dev/docs/guide/input.html#focus
https://goldberry.dev/docs/layout/index.html
In a /// comment it is a Markdown link, [Fields and forms](https://…). In
a /** */ comment it is <a href="https://…">Fields and forms</a>. The text
is the chapter’s title, or the heading’s, so the reader knows where they are
going. Keep doc comment lines at or below 120 columns, including indentation.
If a guide link needs room, put it on its own line after Read more:.
tools/book/guide_links.py reports long lines and can list the guide’s
anchors.
An anchor is the heading as mdBook writes it: lower case, a hyphen for each
space, code marks and punctuation dropped. The cascade: four layers is
the-cascade-four-layers; text-input is text-input. SourceDocsTest
fails on a link to a page the book does not have, or to a heading the page does
not have, so a renamed heading is found by the build and not by a reader.
What a comment does not do
- Cite a record. A record number means nothing to a reader of the javadoc.
Say the rule: data flows down and events flow up, so the widget never writes
the value it shows.
SourceDocsTestfails on a record number in a Java, Gradle or workflow file. - Cite a section of a working document. A section of a specification under
docs/is a file in the repository, not a page a user has. State the rule, and link the chapter that states it. - Quote a specification at itself. A comment that says §2: “External links carry a trailing icon” is a footnote. An external link carries a trailing icon is documentation.
- Narrate the history. What a type used to do, and the bug that changed
it, belong in the log and in
git log. The comment describes the type as it is. The exception is a test, whose comment says what broke and how the test would catch it again, because that is what the test is for. - Link a type another module owns with
[Type]. Doclint resolves a Markdown reference against the imports, and an import for a doc link alone is kept by the formatter only when the type is on the compile path. A name from another module goes in backticks, with a link to the guide.
A test’s comment
A test is documentation of a rule, so its comment says the rule, what breaks
when the rule is broken, and how the test sees it. Its @DisplayName reads as
a sentence with no numbers in it: data flows down and events flow up, not
a record number. An assertion message explains the failure to the person reading a
red build, and says what to do about it.
Which chapter a package links
The chapter a package’s types link is the one that documents them to a user.
Where two fit, the more specific one wins: a Slider links Values and
progress, not The catalogue.
| Module and package | Chapter |
|---|---|
dev.goldberry (the host, the application, the launcher) | Building an application, Windows, popups and the host |
dev.goldberry.bind.* | Markup, Building an application |
dev.goldberry.css.* | Styling; contrast under The design system |
dev.goldberry.drive | Testing an application |
dev.goldberry.frame, dev.goldberry.stats | What a frame costs, Measuring |
dev.goldberry.icon, dev.goldberry.image.*, dev.goldberry.text.* | Text, fonts and icons; the QR encoder under Canvas, images and QR codes |
dev.goldberry.input.* | Input and focus |
dev.goldberry.kdl, dev.goldberry.reload, dev.goldberry.widgets.markup | Markup |
dev.goldberry.layout | How layout works |
dev.goldberry.motion | The design system; the clock under Testing an application |
dev.goldberry.offscreen | Testing an application |
dev.goldberry.paint.* | Architecture, Keeping frames cheap |
dev.goldberry.platform | Logging and diagnostics |
dev.goldberry.render.* | Windows, popups and the host; the backends under Architecture |
dev.goldberry.widget.* | Writing a widget |
dev.goldberry.widgets and widgets.core | The catalogue, the Layout chapters |
dev.goldberry.widgets.controls.* | Buttons, badges and chips, Choices, Values and progress |
dev.goldberry.widgets.data.* | Charts |
dev.goldberry.widgets.form.* | Fields and forms |
dev.goldberry.widgets.menu, widgets.shell.tray | Menus and the tray |
dev.goldberry.widgets.nav.* | Navigation |
dev.goldberry.widgets.overlay.* | Overlays |
dev.goldberry.widgets.panel.* | Panels; list, table and tree under Collections; masonry and split under Layout |
dev.goldberry.widgets.text | Text and links |
dev.goldberry.widgets.core.web, widgets.shell.web, dev.goldberry.html.*, dev.goldberry.content.*, dev.goldberry.markdown.* | Markdown, HTML and the web |
dev.goldberry.media.* | Audio and video |
dev.goldberry.camera.* | Camera |
dev.goldberry.mic.* | Microphone |
dev.goldberry.vector.* | Canvas, images and QR codes |
dev.goldberry.spell.*, dev.goldberry.text.spell.* | Spell checking |
dev.goldberry.text.hyphen | Wrapping and hyphenation |
dev.goldberry.gpu.* | The GPU canvas |
dev.goldberry.natives.* | Architecture, Native image |
dev.goldberry.weaver | Ahead-of-time binding |
dev.goldberry.log.* | Logging and diagnostics |
dev.goldberry.emoji | Text, fonts and icons |
dev.goldberry.assets.* (the build-time preparer) | Building from source |
dev.goldberry.example.* | Your first Java application, Building an application |
dev.goldberry.build.* | Building from source, Tests and gates, Releasing |
| A test, in any module | Tests and gates; the test-scope API under Testing an application |
Checking
./gradlew :build-logic:test --tests '*SourceDocsTest*'
./gradlew javadoc
The first holds the rules above: no record number in a source, every guide
link lands on a page and a heading that exist, every published package links
the guide, and no Java source names a file under docs/. The second is
doclint over the published modules, which finds a [Type] that does not
resolve. Before either, python3 tools/book/guide_links.py <paths> reports the
same for the paths given, plus a section sign that is not a public standard’s
and a /// line the formatter would break; --anchors <chapter.md> lists the
headings a link may name.