# gowaku: the full documentation
This file holds the English guides, the reference and the widget catalog of gowaku (github.com/bankai-tensei/gowaku) as one document. Relative links point into the repository at https://github.com/bankai-tensei/gowaku.
---
Beautiful, fast desktop apps in pure Go.
Drawn on the GPU. No cgo, no C compiler. Fluent in Japanese.
For example, you can build a screen like this. Every pixel of it, from the text to the colors of the diff, is drawn by the library on the GPU.
89 ms to the first frame · 0 % CPU when idle · 1/6 the CPU of Gio for 100 animations · 100+ widgets · onego build
---
### Why gowaku
#### It's just Go
No cgo. No C compiler. No SDK to install. gowaku calls Direct3D 11, Vulkan and Metal straight from Go, so `go build` gives you one binary, and `GOOS=linux go build` on your Windows laptop gives you the Linux one too.
#### Fast, and quiet when there's nothing to do
gowaku is declarative and Flutter-like: you describe the UI as a tree of widgets, and it rebuilds only what changed and batches the drawing for the GPU. When nothing moves, nothing runs. No frames, no timers, 0 % CPU. A hundred animations at once take a sixth of the CPU Gio needs ([benchmarks](#performance)).
Size does not slow it down either. Lists, tables and the editor lay out only what is in view, and scroll a pixel at a time a hundred million rows down. The editor takes its lines from a source you write, so a 10 GB log shows its first lines in 80 ms, with 84 MB of memory in all (see the `bigfile` example).
#### Japanese, done properly
Vertical text. Ruby. Line-break rules and punctuation spacing after the W3C's [JLReq](https://www.w3.org/TR/jlreq/). An IME that composes inline with the active clause highlighted, on Windows, macOS and Wayland. Color emoji, Arabic and Hebrew too. Most UI toolkits treat these as edge cases; gowaku was built around them.
#### Good-looking by default
A quiet desktop design of its own, light and dark following the OS, and a whole palette generated from one accent color. `control.Button{Label: "Save"}` already looks finished. Blur, shadows, gradients, custom shaders and SVG are there when you want more.
#### Built for real applications
Tables, trees, a code editor, a Markdown view, a dock layout, a command palette, date pickers and a hundred more, each with a picture in the [catalog](docs/catalog/en/README.md). Multiple windows, menus, custom title bars, tray icons, notifications, drag and drop, and accessibility for screen readers on all three operating systems.
#### Testable without a window
`gowakutest` runs your UI on the CPU with a fake clock: find a button by its label, tap it, type, advance time, take a screenshot, all in `go test`. It also flags overflow, unlabeled controls and low-contrast text. `gowaku-preview` redraws your widgets light and dark on every save, as a page and as PNG files that you, or an AI agent, can look at.
### Hello, counter
```go
package main
import (
"fmt"
"log"
"time"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/geom"
"github.com/bankai-tensei/gowaku/motion"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/control"
)
type counter struct{ gowaku.StatefulBase }
type counterState struct {
gowaku.StateBase
n int
}
func (counter) CreateState() gowaku.State { return &counterState{} }
func (s *counterState) Build(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Center{Child: basic.VStack(
basic.Text{Content: fmt.Sprintf("count: %d", s.n), Style: th.Text.LargeTitle},
// An implicit animation: change the value, and it glides there.
basic.AnimatedContainer{
Duration: 300 * time.Millisecond,
Curve: motion.EaseOutCubic,
Color: th.Color.AccentTint.WithAlpha(float32(s.n%10) / 10),
Padding: geom.All(16),
Radius: th.Radius.Group,
Child: control.Button{
Label: "Add one",
Style: control.ButtonPrimary,
OnPress: func() { s.SetState(func() { s.n++ }) },
},
},
)}
}
func main() {
err := gowaku.Run(gowaku.App{Title: "counter", Width: 400, Height: 300, Home: counter{}})
if err != nil {
log.Fatal(err)
}
}
```
Widgets are plain structs that work at their zero value. No builders, no reflection, no string IDs: the compiler checks your whole UI.
### A look around
A command palette in the notes example
The same note, set vertically, with ruby and emoji
A glass dialog: the list keeps moving behind the blur
Color emoji, right-to-left text, variable fonts, hyphenation
Every screenshot here is drawn by the examples themselves. Try them:
```bash
go run github.com/bankai-tensei/gowaku/examples/gallery@latest
```
| Example | What you'll see |
|---|---|
| `gallery` | Every widget, page by page |
| `notes` | A small but complete notes app: tabs, search, vertical writing, a command palette |
| `tategaki`, `jptext`, `scripts` | Japanese typesetting, vertical text, emoji and right-to-left text |
| `navigator`, `tabs` | Hero transitions between pages; documents in tabs that tear off into windows |
| `multiwindow`, `decorations`, `menus`, `dragdrop` | Windows, title bars, menus, drag and drop |
| `glass`, `shader`, `rotate`, `zoom`, `animated` | Blur, custom shaders, transforms, pinch zoom, animated images |
| `hello`, `counter`, `todo`, `form`, `listview` | Small programs to start from; a list of 10,000 rows |
| `bigfile` | A file of any size, opened at once and searched without stopping the window |
### Performance
The same scenarios written for three Go UI libraries, measured from outside the process on Windows 11 (i7-12700H, Iris Xe, 60 Hz). Medians; CPU is percent of one core. The losses are in the table too. [docs/BENCH.md](docs/BENCH.md) has the method, the macOS numbers and the details.
| | **gowaku** | Gio | Cogent Core |
|---|---:|---:|---:|
| Start to first frame | **89 ms** | 144 ms | 1217 ms |
| Idle CPU | **0.00 %** | 0.03 % | 2.40 % |
| 100 animations, CPU | **7.8 %** | 44.4 % | 69.4 % |
| 10,000-row scroll, CPU | **9.1 %** | 12.7 % | 28.7 % |
| Resize, CPU | **11.2 %** | 18.7 % | 44.1 % |
| Peak memory, scroll | 240 MB | **159 MB** | 434 MB |
| Binary, hello world | 7.7 MB | **6.4 MB** | 32.4 MB |
| Needs cgo | **no** | no on Windows | yes |
Large files, with the `bigfile` example on the same machine (the editor reads only the lines in view, from a source that indexes the file on a goroutine of its own; memory includes the 43 MB the window holds without a file):
| | 1 GB, 12.6 million lines | 10 GB, 125 million lines |
|---|---:|---:|
| Start to the first lines | 80 ms | 80 ms |
| Every line indexed, in the background | 0.4 s | 9 to 10 s |
| Memory | 51 MB | 84 MB |
### Get started
```bash
go get github.com/bankai-tensei/gowaku
```
| OS | Drawn with | Windows from |
|---|---|---|
| Windows (amd64, arm64) | Direct3D 11 | Win32 |
| Linux (amd64, arm64) | Vulkan | Wayland or X11 |
| macOS (Apple Silicon) | Metal | Cocoa |
Then read [Getting started](docs/guide/en/getting-started.md), and copy a complete program from [Recipes](docs/guide/en/recipes.md): a list and a detail, a settings window, a vertical reader, a background job. The [guides](docs/guide/en/README.md) go on to layout, theming, animation, text and IME, accessibility, windows, testing and shipping.
Working with a coding agent? Point it at [llms-full.txt](https://bankai-tensei.github.io/gowaku/llms-full.txt): the guides, the reference and the whole widget catalog in one file.
### Status
gowaku is young. The first release is v0.1.0, and the API may still change before v1.0. Linux has been checked under X11 and Wayland with a software Vulkan driver, but not yet on GNOME or KDE with a real GPU; under X11 the input method shows its own composition window. macOS needs Apple Silicon. See [ROADMAP.md](ROADMAP.md) for what's next, and [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for how it works inside.
Issues, ideas and pull requests are welcome: start with [CONTRIBUTING.md](CONTRIBUTING.md).
### License
[MIT](LICENSE). Third-party material is listed in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
---
## gowaku guides
[日本語](../ja/README.md)
These guides explain how to build a desktop application with gowaku, from the first window to packaging. Read them in order the first time; later, jump to the one you need. For each widget and its fields, see the [widget catalog](../../catalog/en/README.md) and the package documentation.
| Guide | Covers |
|---|---|
| [Getting started](getting-started.md) | Requirements, installing, the first window, a counter, and the samples. |
| [Concepts](concepts.md) | Widgets, elements and render objects; state and `SetState`; `BuildContext`, inherited data and keys; how a change reaches the screen, and why an idle window draws nothing. |
| [Layout](layout.md) | The constraints protocol; rows, columns, stacks, wraps, grids, scrolling and lists; writing a custom layout. |
| [Theme](theme.md) | One accent color, light and dark, changing the theme while running, text styles and tokens, tokens of your own. |
| [Motion](motion.md) | Implicit animations, switching children, curves, controllers, springs, page transitions and heroes. |
| [Text and input methods](text-and-ime.md) | Text styles, Japanese typesetting, ruby, vertical text, and input methods. |
| [Accessibility](accessibility.md) | Screen readers, semantics, focus and the keyboard. |
| [Windows and the OS](windows-and-os.md) | Windows, modal windows, menus, the title bar, the clipboard, file dialogs, drag and drop, the tray and notifications. |
| [Testing and previews](testing-and-preview.md) | Running a widget tree under `go test` without a window, and previews that redraw on save. |
| [Packaging](packaging.md) | The icon and metadata of an application. |
| [Platforms](platforms.md) | What each OS needs and supports, and the known limits. |
| [Recipes](recipes.md) | Complete programs for a list and a detail, a settings window with a confirmation, a long vertical text and a job in the background, and the common pitfalls. |
### Other references
- [Widget catalog](../../catalog/en/README.md): every public widget, with a picture and an example.
- [docs/DESIGN.md](../../DESIGN.md) (Japanese): the visual design.
- [docs/ADR/](../../ADR/) (Japanese): the design decisions, one file each.
- [`examples/`](../../../examples/): runnable samples.
---
## Getting started
[Guides](README.md) · [日本語](../ja/getting-started.md)
This guide installs gowaku, opens a window, adds a button that counts, and runs the samples in the repository.
### Requirements
- **Go 1.27.3 or later**, as `go.mod` asks.
- **No C compiler.** gowaku does not use cgo. It calls the OS and the GPU from pure Go, so `CGO_ENABLED=0` builds work, and each OS cross-compiles for the others.
- **One of these systems:**
| OS | GPU API | What must be installed |
|---|---|---|
| Windows | Direct3D 11 | A hardware GPU. The software adapter (WARP) is not used. |
| Linux | Vulkan | A Vulkan driver (`libvulkan.so.1` and Mesa or the vendor driver), and either X11 (`libX11.so.6`) or Wayland (`libwayland-client.so.0`, `libxkbcommon.so.0`). |
| macOS | Metal | Apple Silicon. On an Intel Mac, `gowaku.Run` returns `gowaku.ErrUnsupported`. |
On Linux, the libraries are opened when the program starts. You need the libraries a desktop already has, not their `-dev` packages. gowaku picks Wayland when `WAYLAND_DISPLAY` is set and X11 otherwise; `GOWAKU_BACKEND=x11` or `GOWAKU_BACKEND=wayland` forces one. See [Platforms](platforms.md) for the details and known limits of each system.
### Install
In your module:
```bash
go get github.com/bankai-tensei/gowaku
```
The Markdown view is a module of its own, so that the main module keeps its short list of dependencies. Add it when you need it:
```bash
go get github.com/bankai-tensei/gowaku/markdown
```
To try a local checkout of gowaku instead of a release, point your `go.mod` at it and let Go fill in the rest:
```bash
go mod edit -require=github.com/bankai-tensei/gowaku@v0.0.0 -replace=github.com/bankai-tensei/gowaku=../gowaku
go mod tidy
```
`go mod tidy` adds the modules gowaku depends on and their checksums; without it, the first build stops with "missing go.sum entry". It also drops the require of gowaku when no file of your module imports gowaku yet, so write the import first, as in the program below, and run it after.
### The first window
```go
package main
import (
"log"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/widgets/basic"
)
type hello struct{ gowaku.StatelessBase }
func (hello) Build(gowaku.BuildContext) gowaku.Widget {
return basic.Center{Child: basic.Text{Content: "Hello, gowaku"}}
}
func main() {
err := gowaku.Run(gowaku.App{Title: "hello", Width: 400, Height: 300, Home: hello{}})
if err != nil {
log.Fatal(err)
}
}
```
```bash
go run .
```
What happens here:
- `hello` is a widget: a plain struct. Embedding `gowaku.StatelessBase` gives it the `Key` method every widget has, and `Build` returns what it looks like.
- `basic.Center` and `basic.Text` are standard widgets from `widgets/basic`. They are struct literals too, and their zero values work.
- `gowaku.Run` opens the window, shows `Home`, and blocks until the last window closes. The goroutine that calls it becomes the UI goroutine. Its error reports only a failed start, such as no usable GPU.
The window follows the light or dark mode of the OS. Nothing runs while nothing changes: an idle window draws no frames.
### A counter
A widget that remembers something is stateful. The widget itself stays a value; what it remembers lives in a `State`, which survives rebuilds.
```go
package main
import (
"fmt"
"log"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/layout"
"github.com/bankai-tensei/gowaku/theme"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/control"
)
type counter struct{ gowaku.StatefulBase }
type counterState struct {
gowaku.StateBase
n int
}
func (counter) CreateState() gowaku.State { return &counterState{} }
func (s *counterState) Build(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Center{Child: basic.Column{
Size: layout.MainMin,
Spacing: theme.Space12,
Children: []gowaku.Widget{
basic.Text{Content: fmt.Sprintf("Count: %d", s.n), Style: th.Text.LargeTitle},
control.Button{
Label: "Add one",
Style: control.ButtonPrimary,
OnPress: func() { s.SetState(func() { s.n++ }) },
},
},
}}
}
func main() {
err := gowaku.Run(gowaku.App{Title: "counter", Width: 400, Height: 300, Home: counter{}})
if err != nil {
log.Fatal(err)
}
}
```
- `counter` embeds `gowaku.StatefulBase` and returns a new state from `CreateState`.
- `counterState` embeds `gowaku.StateBase`, which gives it `SetState`, `Context` and the lifecycle methods.
- `SetState` runs the function that changes the state and schedules a rebuild. On the next frame, that state's `Build` runs again, and the rest of the tree is left alone.
- `basic.ThemeOf(ctx)` reads the theme of the window. `th.Text.LargeTitle` is a text style of the type scale, and `theme.Space12` a spacing token.
- `Size: layout.MainMin` makes the column as tall as its children, so that `Center` can center it. A `Column` takes all the height it may by default.
`Button` is in `widgets/control`. The widgets are split into packages by layer: `basic`, `interact`, `control`, `overlay`, `field`, `nav`, `collection` and `editor`. The [widget catalog](../../catalog/en/README.md) lists them all, with a picture and the code of each.
The guides write `gowaku.Widget` and `gowaku.BuildContext`; the catalog and the godoc of the widget packages write `core.Widget` and `core.BuildContext`. They are the same types: package `gowaku` gives the common names of `core` aliases, so a UI file needs no import of `core`.
### See it without a window
You do not need to open a window to see what you built. Package `gowakutest` lays out a widget and draws it on the CPU, so an ordinary test can save a screenshot. Put this next to the counter, in `main_test.go`:
```go
package main
import (
"testing"
"github.com/bankai-tensei/gowaku/gowakutest"
)
func TestScreenshots(t *testing.T) {
for _, dark := range []bool{false, true} {
tt := gowakutest.New(t, counter{}, gowakutest.Options{Width: 400, Height: 300, Dark: dark})
tt.Tap("Add one") // press the button by its label, as a user would
name := "light.png"
if dark {
name = "dark.png"
}
tt.SaveScreenshot(name)
for _, w := range tt.Warnings() {
t.Error(w) // overflow, controls without a label, text of low contrast
}
}
}
```
`go test` writes `light.png` and `dark.png`. This is also the quickest way for a coding agent to look at its own work. [Testing and previews](testing-and-preview.md) explains the rest: typing, time, what each control reports, and live previews that redraw on every save.
The samples' `-png` flags use a helper inside the repository; your code uses `gowakutest` instead.
### Running the samples
The repository has small programs under [`examples/`](../../../examples/). Clone it and run them from its root:
```bash
git clone https://github.com/bankai-tensei/gowaku
cd gowaku
go run ./examples/hello
```
| Sample | Shows |
|---|---|
| `hello`, `counter` | The smallest programs. `counter` adds an implicit animation. |
| `todo` | A small application with a text field and a list. |
| `gallery` | Most widgets, as a settings window. |
| `form` | Text fields with Japanese input, a checkbox and buttons. Tab moves the focus. |
| `listview` | 10,000 rows in a list. `-measured` shows rows of wrapping text. |
| `jptext`, `tategaki`, `scripts` | Japanese typesetting and ruby, vertical text, emoji and right-to-left text. |
| `navigator` | Pages that slide in, with a Hero flight. |
| `menus`, `tabs`, `multiwindow` | A menu bar and shortcuts, tabs that tear off into windows, windows that share state. |
| `rotate`, `shader`, `glass` | Transforms with an animation controller, custom shaders, a blurred backdrop. |
| `dragdrop`, `zoom`, `decorations` | Drag and drop, tray and notifications; pinch and pen; window icon, size limits and transparency. |
| `notes` | A larger application: plain text notes with search, tabs, vertical writing and a command palette. |
### Where to go next
- [Concepts](concepts.md): widgets, elements and render objects, state, `BuildContext`, keys, and why an idle window draws nothing.
- [Layout](layout.md): how sizes are decided, and the layout widgets.
- [Theme](theme.md): the accent color, light and dark, text styles and tokens.
- [Motion](motion.md): implicit animations, controllers and springs.
- [Testing and previews](testing-and-preview.md): run a widget tree under `go test` without a window.
- The [widget catalog](../../catalog/en/README.md) for every widget.
---
## Concepts
[Guides](README.md) · [日本語](../ja/concepts.md)
gowaku is declarative, in a Flutter-like way: you describe the UI with widgets, and the library keeps the tree on the screen in step with that description. This guide explains the pieces and how a change reaches the screen.
### Three trees
| Tree | Lives | Does |
|---|---|---|
| **Widget** | One `Build`, then thrown away | Describes part of the UI. A plain value. |
| **Element** | As long as its place in the tree | Keeps the `State`, links a widget to its render object, and is what the diff compares. Internal to gowaku. |
| **RenderObject** | As long as its element | Does the layout, painting, hit testing and accessibility of a widget. |
You write widgets. Each `Build` returns new widget values. gowaku compares them with the elements that are already there: when an old and a new widget have the same type and the same key, the element stays, keeps its state and takes the new values. Otherwise the old element leaves and a new one is made.
Package `core` holds these types. The root package `gowaku` gives the ones every UI file writes another name, so a UI file rarely needs to import `core`: `gowaku.Widget`, `gowaku.BuildContext`, `gowaku.StatelessBase`, `gowaku.StatefulBase`, `gowaku.State`, `gowaku.StateBase`, `gowaku.StateOf`, `gowaku.Key` and `gowaku.Keyed`.
### Widgets are values
A widget is a struct, written as a literal. Its fields are its whole API:
```go
control.Button{Label: "Save", Style: control.ButtonPrimary, OnPress: save}
```
- **The zero value works.** `basic.Padding{}` draws its child without inset, `basic.Text{}` shows nothing, a `control.Button` without `OnPress` is disabled. Defaults are written in the doc comment of each field.
- **No builders, no options.** There are no `NewButton(...)` functions, functional options or method chains. A few one-line helpers exist for the most common shapes: `basic.VStack`, `basic.HStack`, `basic.Layers` and `basic.Pad`.
- **No reflection over your fields.** gowaku compares the type of a widget and its key, nothing else.
Widgets are cheap. Build them freely on every `Build`.
### Stateless widgets
A stateless widget builds its child from its own fields. Embed `gowaku.StatelessBase` and write `Build`:
```go
type greeting struct {
gowaku.StatelessBase
Name string
}
func (g greeting) Build(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Text{Content: "Hello, " + g.Name, Style: th.Text.Title}
}
```
Use it as `greeting{Name: "Hanako"}`.
### Stateful widgets
A stateful widget keeps a `State` that survives rebuilds. The widget embeds `gowaku.StatefulBase` and returns a new state from `CreateState`. The state embeds `gowaku.StateBase`, or `gowaku.StateOf[W]` to read the fields of its widget without a type assertion:
```go
type stepper struct {
gowaku.StatefulBase
Step int
}
type stepperState struct {
gowaku.StateOf[stepper]
n int
}
func (stepper) CreateState() gowaku.State { return &stepperState{} }
func (s *stepperState) Build(gowaku.BuildContext) gowaku.Widget {
step := s.Widget().Step // a stepper, no type assertion
return control.Button{
Label: fmt.Sprintf("%d (+%d)", s.n, step),
OnPress: func() { s.SetState(func() { s.n += step }) },
}
}
```
The lifecycle of a state:
| Method | Runs |
|---|---|
| `InitState()` | Once, before the first `Build`. Start tickers and controllers here. |
| `Build(ctx)` | Whenever the state is dirty or its parent rebuilt. |
| `DidUpdateWidget(old)` | When a parent rebuild gives the element a new widget value. `Widget()` returns the new one. |
| `Dispose()` | Once, when the state leaves the tree. Stop what `InitState` started. |
`StateBase` gives empty versions of all but `Build`, so write only the ones you need.
`SetState(fn)` runs `fn` and schedules a rebuild of this state. Two rules, both checked with a panic:
- Do not call `SetState` during `Build`. Call it from a callback, such as `OnPress`, or from a ticker.
- Do not call `SetState` on a state that has left the tree. Check `Mounted()` when a result may arrive late.
### Tickers
A ticker calls a function once per frame while it runs. A state makes one with `NewTicker`, or with `NewPeriodicTicker` for something that changes at a fixed rate:
```go
type clock struct{ gowaku.StatefulBase }
type clockState struct {
gowaku.StateBase
ticker *core.Ticker
now time.Time
}
func (clock) CreateState() gowaku.State { return &clockState{} }
func (s *clockState) InitState() {
s.now = time.Now()
s.ticker = s.NewPeriodicTicker(time.Second, func(time.Duration) {
s.SetState(func() { s.now = time.Now() })
})
s.ticker.Start()
}
func (s *clockState) Build(gowaku.BuildContext) gowaku.Widget {
return basic.Text{Content: s.now.Format("15:04:05")}
}
```
A periodic ticker lets the window sleep between calls. Its first call comes right away, on the frame after `Start`, not one period later. Tickers made by a state stop on their own after its `Dispose`. The animation types of `motion` run on tickers too; see [Motion](motion.md).
#### Running code after a delay
For a single call after a delay, as to take back a "Saved" message, a state calls `After`. It returns a function that cancels the call:
```go
type saveState struct {
gowaku.StateBase
saved bool
}
func (s *saveState) save() {
s.SetState(func() { s.saved = true })
s.After(1200*time.Millisecond, func() {
s.SetState(func() { s.saved = false })
})
}
```
`After` runs the function on the UI goroutine, so it may call `SetState`. It follows the clock of the tickers, so `gowakutest`'s `Advance` drives it like an animation (a tap's settle does not wait for it), and the window sleeps while it waits. When the state leaves the tree, the call is canceled with it. Use `After` rather than `time.AfterFunc` with `gowaku.Post`: that pair runs on the wall clock, which a test cannot move, and `Post` drops the function outside `Run`.
### BuildContext
A `BuildContext` is the place of a widget in the tree. `Build` gets one, and a state also has `Context()`. Functions that read what lies above a place take it:
- `basic.ThemeOf(ctx)`: the theme.
- `basic.MediaQueryOf(ctx)`: the scale, the brightness the OS asks for, reduced motion, the locale and the size of the window. `basic.WindowSizeOf`, `basic.ReduceMotionOf` and `basic.LocaleOf` read one of them, and rebuild the caller only when that one changes.
- `nav.NavigatorOf(ctx)`: the nearest `nav.Navigator`.
- `gowaku.WindowOf(ctx)`: the window.
A context sees only what is above it. To read something that a widget in the same `Build` provides, put the reading part in a `basic.Builder`, which builds with a context of its own at its place:
```go
basic.Builder{Content: func(ctx gowaku.BuildContext) gowaku.Widget {
return basic.Text{Content: "Hi", Style: basic.ThemeOf(ctx).Text.Title}
}}
```
### Inherited data
`core.Inherited[T]` makes a value available to everything below it. `core.DependOn[T]` finds the nearest one and rebuilds the caller when the value changes; `core.Lookup[T]` finds it without that, for callbacks. This is how `ThemeOf` and `MediaQueryOf` work.
```go
type user struct{ Name string }
func withUser(u user, child gowaku.Widget) gowaku.Widget {
return core.Inherited[user]{Value: u, Child: child}
}
type badge struct{ gowaku.StatelessBase }
func (badge) Build(ctx gowaku.BuildContext) gowaku.Widget {
u, ok := core.DependOn[user](ctx)
if !ok {
return basic.Text{Content: "Signed out"}
}
return basic.Text{Content: u.Name}
}
```
`T` must be comparable, and "changed" means `!=`. Use a type of your own, not a bare `string` or `int`, so that two packages do not find each other's values. For a large value, pass a pointer and replace the pointer when the data changes.
### Keys
The identity of a widget among its siblings is its type and its key. Without keys, children are matched by position. That is right for most trees, but not for a list whose items move: a removed row at the top would hand its state, such as hover, focus or text being typed, to the row below.
Give each item a key with `gowaku.Keyed`:
```go
type todo struct {
ID int
Title string
Done bool
}
func todoRows(items []todo, toggle func(id int, done bool)) []gowaku.Widget {
rows := make([]gowaku.Widget, len(items))
for i, it := range items {
rows[i] = gowaku.Keyed(it.ID, control.Checkbox{
Label: it.Title,
Value: it.Done,
OnChange: func(v bool) { toggle(it.ID, v) },
})
}
return rows
}
```
A key can be any comparable value, such as an ID or a string; `Keyed` panics on a value that is not comparable. Keys must be unique among siblings. `basic.AnimatedSwitcher` also uses keys: a child with a new key counts as new and is animated in.
### How a change reaches the screen
1. A callback calls `SetState`. The state is marked dirty. Nothing is built yet.
2. On the next frame, the dirty states build, parents first. A parent's new widgets update its children: render widgets copy their fields to their render objects, and stateful children get `DidUpdateWidget` and build again.
3. A render object whose layout changed is laid out again, starting from the nearest object whose size cannot affect its parent.
4. What changed is painted. A `basic.RepaintBoundary` keeps its child's picture apart, so that a change inside paints only the child and a change outside reuses its pixels. `collection.List` puts one around each row.
5. The GPU draws the frame.
Many `SetState` calls before a frame make one build. Keep state low in the tree: a `SetState` rebuilds that state and what its `Build` returns, so a small stateful widget near the change costs less than one at the root.
#### Idle draws nothing
A window draws a frame only when something asks for it: input, a `SetState`, a change of the window, or a running ticker. The ticker is the only way to ask for frames over time. When no ticker runs and no event comes, the UI goroutine sleeps in the event loop and uses no CPU. Animations stop their tickers when they arrive, so a window goes quiet by itself.
### The UI goroutine
The goroutine that calls `gowaku.Run` is the UI goroutine. `Build`, layout, paint, callbacks and `SetState` all run there, so state needs no locks. From another goroutine, hand work back with `gowaku.Post`:
```go
func (s *loaderState) InitState() {
go func() {
r := slowFetch() // runs on another goroutine
gowaku.Post(func() {
if s.Mounted() {
s.SetState(func() { s.result = r })
}
})
}()
}
```
`Post` is safe from any goroutine. Outside `Run` it drops the function, so code that only waits for time to pass uses `After` (see [Tickers](#running-code-after-a-delay)), which tests can drive.
### Render objects
Most applications never write one. Compose the standard widgets, draw with `control.CustomPaint`, and arrange children with `basic.CustomLayout` ([Layout](layout.md#a-custom-layout)).
When you do need one, a widget implements `core.RenderWidget` (`CreateRenderObject` and `UpdateRenderObject`), and `core.SingleChildWidget` or `core.MultiChildWidget` for children. The render object embeds `core.RenderBase` and implements `Layout` and `Paint`. `UpdateRenderObject` should mark the object dirty only for fields that changed: `MarkNeedsLayout` for a change of size, `MarkNeedsPaint` for a change of look. `Paint` must not allocate. The render objects of package `layout` are examples to read.
### Further reading
- [Layout](layout.md) for the constraints that `Layout` receives.
- [ADR 0006](../../ADR/0006-core-tree-api.md) (Japanese) on the API of the tree, and [ADR 0029](../../ADR/0029-typed-state-widget.md) on `StateOf`.
---
## Layout
[Guides](README.md) · [日本語](../ja/layout.md)
This guide explains how gowaku decides the size and place of each widget, walks through the layout widgets, and shows how to write a layout of your own. The widgets here are in `widgets/basic` unless another package is named; the alignment and axis constants are in `layout`, and the geometry types in `geom`.
### The constraints protocol
Layout is one pass down the tree and back:
- **Constraints go down.** A parent tells each child the sizes it may take, as a `geom.Constraints{MinW, MaxW, MinH, MaxH}`. A maximum of `geom.Inf` means unbounded.
- **Sizes go up.** The child picks a size within those limits and returns it.
- **The parent places the child.** Only after the child has its size does the parent decide where it goes.
A child cannot pick its own position, and it cannot be larger than its parent allows. Two kinds of constraints come up all the time:
- **Tight**: the minimum equals the maximum, so the child has exactly one size. The window gives its root widget tight constraints of the window's size.
- **Loose**: the minimum is zero, so the child may be smaller. `Center` and `Align` loosen what they get before they pass it on.
Lengths are in logical pixels. gowaku scales them to the display.
`layout.Constraints`, which a `layout.Delegate` and `basic.LayoutBuilder` receive, is the same type as `geom.Constraints`, so its helpers are in `geom`: `geom.Tight(size)` and `geom.Loose(size)` make constraints, and on a value `c`, `c.Biggest()` is the largest size allowed, `c.Constrain(size)` clamps a size into it, `c.Loosen()` drops the minimums, `c.Deflate(insets)` takes insets off, and `c.IsTight()` reports one allowed size. There is no `layout.Tight`.
### Boxes
| Widget | Does |
|---|---|
| `Padding{Insets, Child}` | Insets the child. `geom.All(16)` and `geom.Symmetric(16, 8)` make the insets; `basic.Pad(16, child)` is short for the first. |
| `Center{Child}` | Places the child in the middle of the space it gets. |
| `Align{Alignment, Child}` | Places the child at an alignment. |
| `SizedBox{Width, Height, Child}` | Forces a width, a height or both. A zero length leaves that axis free. |
| `ConstrainedBox{MinWidth, MaxWidth, MinHeight, MaxHeight, Child}` | Adds limits. A zero maximum means no limit. |
| `Container{...}` | Size, padding, color, gradient, border, corners and shadows in one widget. |
| `DecoratedBox{Decoration, Child}` | Paints a `layout.Decoration` behind the child. |
| `AspectRatio{Ratio, Child}` | Sizes the child to a width over height of `Ratio`, such as `16.0 / 9`: all the width allowed, or all the height where that is too tall. Zero is 1, a square. |
`AspectRatio` has no say under tight constraints, which fix both lengths: the window's, or those of `CrossStretch` and `Expanded`. Put it in a `Center` or an `Align` there, and it becomes the largest rectangle of that shape that fits:
```go
func player(video gowaku.Widget) gowaku.Widget {
return basic.Center{Child: basic.AspectRatio{Ratio: 16.0 / 9, Child: video}}
}
```
An `Alignment` runs from 0 to 1 on each axis: `{X: 0, Y: 0}` is the top left and `{X: 0.5, Y: 0.5}` the middle. This is **not** the -1..1 of Flutter. Use the named values, `layout.AlignTopLeft` through `layout.AlignBottomRight`, such as `layout.AlignCenterLeft`.
### Rows and columns
`Row` lays out its children from left to right, `Column` from top to bottom. Both have the same fields:
- `Main` places the children along the axis: `layout.MainStart`, `MainEnd`, `MainCenter`, `MainSpaceBetween`, `MainSpaceAround`, `MainSpaceEvenly`.
- `Cross` places each child across it: `layout.CrossStart`, `CrossEnd`, `CrossCenter`, `CrossStretch`.
- `Size` is the length along the axis. `layout.MainMax`, the zero value, takes all the length allowed. `layout.MainMin` shrinks to the children.
- `Spacing` is the gap between children.
Because a `Row` or `Column` takes all the room by default, one inside a `Center` fills it instead of sitting in its middle. Write `Size: layout.MainMin`, or use `basic.VStack(...)` and `basic.HStack(...)`, which do that for you. `Flex` is the same widget with an `Axis` field.
`VStack` and `HStack` also put `theme.Space8` between their children, the gap between controls in the design guide, as a stack of SwiftUI keeps its children apart. For any other gap, write the `Column` or `Row` with its `Spacing`: `theme.Space24` between the sections of a page, zero for none.
```go
basic.VStack(title, field, button) // 8 between them
basic.Column{Size: layout.MainMin, Spacing: theme.Space24, Children: []gowaku.Widget{general, advanced, reset}}
```
#### Sharing the free space
`Expanded` and `Flexible` give a child of a `Row` or `Column` a share of the room the other children leave. `Flex` is the weight, where zero counts as one. An `Expanded` child must fill its share; a `Flexible` child may stay smaller.
```go
func toolbar(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Row{Cross: layout.CrossCenter, Spacing: theme.Space8, Children: []gowaku.Widget{
basic.Expanded{Child: basic.Text{Content: "Title", Style: th.Text.Headline}},
basic.Flexible{Child: basic.Text{Content: "A note that may be cut short"}},
control.Button{Label: "Share"},
}}
}
```
A typical page puts a header and a footer around an `Expanded` body:
```go
func page(ctx gowaku.BuildContext, items []string) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Padding{Insets: geom.All(theme.Space16), Child: basic.Column{
Spacing: theme.Space12,
Children: []gowaku.Widget{
basic.Text{Content: "Inbox", Style: th.Text.LargeTitle},
basic.Expanded{Child: collection.List{
ItemCount: len(items),
ItemExtent: 36,
ItemBuilder: func(i int) gowaku.Widget {
return basic.Align{Alignment: layout.AlignCenterLeft, Child: basic.Text{Content: items[i]}}
},
}},
basic.Row{
Main: layout.MainEnd,
Spacing: theme.Space8,
Children: []gowaku.Widget{
control.Button{Label: "Cancel"},
control.Button{Label: "OK", Style: control.ButtonPrimary},
},
},
},
}}
}
```
### Stacks
`Stack` paints its children on top of each other, the last on top. Children that are not positioned are placed by `Alignment`, and the stack is as large as the largest of them, or as large as allowed with `Fit: layout.StackExpand`.
- `Positioned` puts a child at a fixed spot, measured from the top left, or from the right and bottom edges with `AnchorRight` and `AnchorBottom`. `Width` and `Height` force its size.
- `PositionedFill` stretches a child over the whole stack, less `Insets`. Use it for a background.
Positioned children do not count toward the size of the stack.
A press goes to the top child that is hit there. The layout widgets (`Align`, `Center`, `Padding`, `Row`, `Column`, `Stack`, `SizedBox`, `PositionedFill` and the like) are hit only where one of their children is, so the empty space of a full-size layer lets the pointer through to the layer under it. A `Container` with a `Color`, a `Gradient`, a `Border` or `Shadows` is hit over its whole box, as are text, images and the widgets that take the pointer (`GestureDetector`, `Pressable`, `Listener`). `IgnorePointer` lets the pointer through its whole child.
```go
func card(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.SizedBox{Width: 240, Height: 140, Child: basic.Stack{Children: []gowaku.Widget{
basic.PositionedFill{Child: basic.Container{Color: th.Color.Card, Radius: th.Radius.Group}},
basic.Positioned{Left: 16, Top: 16, Child: basic.Text{Content: "Album", Style: th.Text.Title}},
basic.Positioned{Right: 12, Bottom: 12, AnchorRight: true, AnchorBottom: true,
Child: control.Button{Label: "Play", Style: control.ButtonPrimary}},
}}}
}
```
### Wrap and grid
`Wrap` is a row that starts a new row when the next child does not fit. It suits tags and chips. `Spacing` is the gap within a run and `RunSpacing` the gap between runs.
```go
func tags(names []string) gowaku.Widget {
chips := make([]gowaku.Widget, len(names))
for i, n := range names {
chips[i] = control.Chip{Label: n}
}
return basic.Wrap{Spacing: theme.Space8, RunSpacing: theme.Space8, Children: chips}
}
```
`Grid` lays out tiles in columns of the same width. `Columns` fixes their number; when it is zero, the grid fits as many as `MinColumnWidth` allows, so it gains a column as the window grows. A tile is `TileHeight` tall, or the column width over `AspectRatio` plus `ExtraHeight`. A grid is as tall as its rows, so it goes inside a vertical `Scroll`:
```go
func covers(n int) gowaku.Widget {
tiles := make([]gowaku.Widget, n)
for i := range tiles {
tiles[i] = basic.Text{Content: fmt.Sprintf("Cover %d", i+1)}
}
return basic.Scroll{Child: basic.Padding{Insets: geom.All(theme.Space16), Child: basic.Grid{
MinColumnWidth: 160,
Spacing: theme.Space12,
RunSpacing: theme.Space12,
AspectRatio: 1,
ExtraHeight: 40,
Children: tiles,
}}}
}
```
`Grid` builds every child. For thousands of tiles, use `collection.GridView`, which builds only those in view.
### Scrolling
- `Scroll{Child}` shows a child taller than itself, moved with the wheel or the scroll bar that appears over its edge. `Horizontal: true` scrolls sideways. `Reverse: true` starts the scroll range at the right end, or the bottom: the view opens there and short content sits against that end, as for vertical Japanese text or a log. A `ScrollController` in `Controller` reads and sets the offset from code. Every child is built and laid out, so it suits a page of content, not ten thousand rows.
- `collection.List` is the list view. It builds only the rows near the view, so the number of rows does not matter. Rows have the same height, `ItemExtent` (48 by default), unless `ItemExtentOf` returns a height per row, or `MeasureItems` lets each row be as tall as it lays itself out. A `collection.ListController` in `Controller` moves the list to a row or to its end, and reads whether the view is at the end. `StickToEnd: true` keeps the view at the newest row of a log or a chat until the user scrolls up, and `OnScroll` reports each change of the position.
```go
collection.List{
ItemCount: 10000,
ItemExtent: 52,
ItemBuilder: func(i int) gowaku.Widget { return row(i) },
}
```
A header inside a list scrolls away with the rows. To keep it in place, put it above the list and the list in an `Expanded`, as in the page above. The [data widgets](../../catalog/en/data.md) of the catalog, such as `collection.Table` and `collection.Tree`, scroll the same way.
### Unbounded space
Some widgets need a bounded length to make sense, and panic with a message that says how to fix it when they do not get one:
- `Scroll`, `collection.List` and `Grid` take all the room they are given. Inside a `Column`, which offers unbounded height to children that are not flexible, wrap them in an `Expanded` or a `SizedBox`.
- An `Expanded` or `Flexible` in a `Row` or `Column` whose length is unbounded, as inside a `Scroll` along the same axis, has no free space to share.
- `CrossStretch` with an unbounded cross axis, as a `Row` inside a vertical `Scroll`, has nothing to stretch to.
The usual fix is an `Expanded` around the scrolling widget, or a `SizedBox` that gives it a length. See [ADR 0026](../../ADR/0026-unbounded-room.md) (Japanese).
### Building for the room you have
A widget builds before the layout, so it does not know its own size. There are two ways to make what you build depend on the room.
**The size of the window.** `basic.WindowSizeOf(ctx)` is the content area of the window in logical pixels, the `Size` of `basic.MediaQueryData`. Use it for decisions about the whole window, such as folding a sidebar away when the window is narrow. When the window is resized, only the widgets that read the size rebuild, and an idle window costs nothing:
```go
func shell(ctx gowaku.BuildContext, sidebar, content gowaku.Widget) gowaku.Widget {
if basic.WindowSizeOf(ctx).W < 700 {
return content
}
return basic.Row{Children: []gowaku.Widget{basic.SizedBox{Width: 220, Child: sidebar}, basic.Expanded{Child: content}}}
}
```
`basic.MediaQueryOf(ctx).Size` is the same value, but `MediaQueryOf` also rebuilds on a resize; a widget that needs only another field reads it with `basic.ReduceMotionOf` or `basic.LocaleOf`.
**The room of a widget.** When the room is a part of the window, such as a pane whose width the user drags, or a card that may be shown anywhere, use `LayoutBuilder`. Its `Content` gets the constraints its parent gives it:
```go
func panes(list, detail gowaku.Widget) gowaku.Widget {
return basic.LayoutBuilder{Content: func(ctx gowaku.BuildContext, c layout.Constraints) gowaku.Widget {
if c.MaxW < 600 {
return basic.Column{Children: []gowaku.Widget{basic.Expanded{Child: list}, basic.Expanded{Child: detail}}}
}
return basic.Row{Spacing: theme.Space16, Children: []gowaku.Widget{
basic.SizedBox{Width: 240, Child: list},
basic.Expanded{Child: detail},
}}
}}
}
```
- `Content` runs again only when the constraints change, when the parent rebuilds the `LayoutBuilder`, or when something it reads from `ctx`, such as the theme, changes. Frames that lay out with the same constraints build nothing.
- The `LayoutBuilder` is as large as what `Content` returns, within the constraints.
- It learns the constraints when the layout reaches it. The frame then builds `Content` and lays out again before it paints, as `collection.List` does when it learns its height. A `LayoutBuilder` inside the `Content` of another adds such a round, and a frame runs only a few, so deep nesting can show the inner content a frame late.
- To arrange children by their sizes, rather than to choose what to build, write a delegate as below.
### A custom layout
When no standard widget arranges children the way you want, write a `layout.Delegate` and hand it to `basic.CustomLayout`. The delegate gets the constraints and the render objects of the children. It lays out each child with `core.LayoutChild`, places it with `SetOffset`, and returns its own size:
```go
// diagonal places each child a step further right and down.
type diagonal struct{ step float32 }
func (d diagonal) Layout(c layout.Constraints, children []core.RenderObject) geom.Size {
var size geom.Size
for i, child := range children {
sz := core.LayoutChild(child, c.Loosen())
off := geom.Offset{X: float32(i) * d.step, Y: float32(i) * d.step}
child.SetOffset(off)
size.W = max(size.W, off.X+sz.W)
size.H = max(size.H, off.Y+sz.H)
}
return c.Constrain(size)
}
func staircase() gowaku.Widget {
return basic.CustomLayout{Delegate: diagonal{step: 24}, Children: []gowaku.Widget{
basic.Text{Content: "One"}, basic.Text{Content: "Two"}, basic.Text{Content: "Three"},
}}
}
```
Rules for a delegate:
- Lay out children only with `core.LayoutChild`, never by calling their `Layout`. It skips a child whose constraints did not change.
- Return a size within `c`. `c.Constrain` clamps one; `basic.CustomLayout` clamps the result as well.
- Layout runs on every frame that needs it. Do not allocate in `Layout`.
- Each rebuild hands the render object the new delegate and lays it out again, so a delegate can be a small value such as `diagonal{step: 24}`.
For full control over painting and hit testing as well, write a render object; see [Concepts](concepts.md#render-objects).
### Further reading
- The [layout page](../../catalog/en/layout.md) of the widget catalog, with a picture of each widget.
- [Theme](theme.md) for the spacing tokens such as `theme.Space16`.
---
## Theme
[Guides](README.md) · [日本語](../ja/theme.md)
gowaku has a design of its own: quiet neutral surfaces, one accent color, hairlines instead of heavy shadows, and a type scale set from Japanese. Package `theme` holds its tokens. This guide shows how to pick the accent, follow light and dark, change the theme while running, and read the tokens in your widgets. The design itself is described in [docs/DESIGN.md](../../DESIGN.md) (Japanese).
### Theme and Set
- A `*theme.Theme` is the full set of tokens for one brightness: `Color` (`theme.Colors`), `Text` (`theme.TextTheme`), `Radius` (`theme.Radii`) and `Brightness`.
- A `theme.Set` is a light and a dark `*theme.Theme`, so that the application can follow the OS.
`theme.Default()` is the set an application gets when it asks for nothing: an indigo accent, `#2f5fd0`. Its themes are shared, so treat them, and any theme, as read-only.
### One accent color
Every color follows from one accent. Give it to `theme.FromAccent` and put the set in `App.Theme`:
```go
func app() gowaku.App {
return gowaku.App{
Title: "notes",
Theme: theme.FromAccent(geom.Hex(0x2f8f5b)),
ThemeMode: gowaku.ThemeSystem,
Home: home,
}
}
```
`FromAccent` derives the accent fill, the text on it, the accent as text, and the tint of a selection, for both brightnesses, in the HCT color space. The surfaces stay neutral whatever the accent. Contrast is checked: `Ink` and `Ink2` read at 4.5:1 or more on every surface ([ADR 0041](../../ADR/0041-ink-contrast.md), Japanese).
`theme.New(accent, b)` makes a single `*theme.Theme` of one brightness, `theme.BrightnessLight` or `theme.BrightnessDark`.
### Light and dark
`App.ThemeMode` says which half of the set to use:
| Mode | Does |
|---|---|
| `gowaku.ThemeSystem` (zero value) | Follows the OS, also while running. |
| `gowaku.ThemeLight` | Stays light. |
| `gowaku.ThemeDark` | Stays dark. |
The title bars and backgrounds that the OS draws follow the theme too.
### Changing the theme while running
`gowaku.SetTheme(ctx, set, mode)` changes the look of every window, as `App.Theme` and `App.ThemeMode` set it at the start. `gowaku.CurrentTheme(ctx)` returns what is in use. Both go through the window of `ctx`, so under a `gowakutest.Tester` they change the theme of its tree instead. A settings page might offer the mode:
```go
func modeButtons(ctx gowaku.BuildContext) gowaku.Widget {
set := func(mode gowaku.ThemeMode) func() {
return func() {
s, _ := gowaku.CurrentTheme(ctx)
gowaku.SetTheme(ctx, s, mode)
}
}
return basic.Row{Spacing: theme.Space8, Children: []gowaku.Widget{
control.Button{Label: "System", OnPress: set(gowaku.ThemeSystem)},
control.Button{Label: "Light", OnPress: set(gowaku.ThemeLight)},
control.Button{Label: "Dark", OnPress: set(gowaku.ThemeDark)},
}}
}
```
and the accent:
```go
func accentButton(ctx gowaku.BuildContext, accent geom.Color) gowaku.Widget {
return control.Button{Label: "Use this color", OnPress: func() {
_, mode := gowaku.CurrentTheme(ctx)
gowaku.SetTheme(ctx, theme.FromAccent(accent), mode)
}}
}
```
Every widget that reads the theme rebuilds. Windows opened later take the new theme too. Call `SetTheme` on the UI goroutine, outside `Build`, as from a callback. See [ADR 0067](../../ADR/0067-runtime-theme.md) (Japanese).
### Reading the theme
`basic.ThemeOf(ctx)` returns the nearest theme above a widget and rebuilds the widget when it changes:
```go
func section(ctx gowaku.BuildContext, title, note string) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Container{
Color: th.Color.Card,
Radius: th.Radius.Group,
Border: paint.Stroke{Width: 1, Color: th.Color.Hair},
Padding: geom.Symmetric(theme.Space16, theme.Space12),
Child: basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space6, Children: []gowaku.Widget{
basic.Text{Content: title, Style: th.Text.Headline},
basic.Text{Content: note, Style: th.Text.Caption.WithColor(th.Color.Ink2)},
}},
}
}
```
#### The tokens at a glance
| Token | Names | Type |
|---|---|---|
| `theme.Space*` | `Space2`, `Space4`, `Space6`, `Space8`, `Space10`, `Space12`, `Space16`, `Space20`, `Space24`, `Space28` (the number is the size) | untyped constant, logical pixels |
| `theme.ControlHeight` | 30 | untyped constant, logical pixels |
| `theme.Lift*` | `LiftNone`, `LiftControl`, `LiftKnob`, `LiftFloat` | `theme.Lift`, for `th.Color.Shadows` |
| `th.Radius` | `Check` (4), `Control` (8), `Group` (12), `Dialog` (16) | `float32` fields of `theme.Radii` |
| `th.Text` | `LargeTitle`, `Title`, `Headline`, `Body`, `Control`, `Caption`, `Section`, `Reading`, `Code` | `text.Style` fields of `theme.TextTheme` |
| `th.Color` | the table under Colors | `geom.Color` fields of `theme.Colors` |
#### Colors
Colors are named for what they do, not for their hue:
| Field | Use |
|---|---|
| `Canvas`, `Sidebar`, `Card`, `Raised` | The ground of a window, a sidebar, a group, and what floats such as a dialog. |
| `Glass` | `Raised` made translucent, for a surface over a blurred backdrop. |
| `Field`, `Control` | The ground of an input and of an ordinary button. |
| `Ink`, `Ink2`, `Ink3` | Text, supporting text, and faint marks such as placeholders. `Ink3` is below 4.5:1 on purpose: do not use it for text that tells something. |
| `Hair` | A line. |
| `Fill`, `FillStrong` | Quiet grounds that work on any surface. |
| `Accent`, `OnAccent`, `AccentInk`, `AccentTint` | The accent fill, text on it, the accent as text or a thin line, and the mark of a selection. |
| `Danger`, `Success` | Destructive actions and errors; what went well. Both read as text on every surface, and in the light theme carry white text as a fill. |
| `Warning` | What needs attention before it goes wrong. A bright amber for icons, dots, borders and tints; it is not meant for text, so set the words in `Ink` beside it. |
| `Shadow`, `Scrim` | The color of shadows; what covers a page behind a dialog. |
#### Text styles
`th.Text` is the type scale. Each role sets the size, weight and line height:
| Role | Size | Weight | Line |
|---|---|---|---|
| `LargeTitle` | 24 | 600 | 32 |
| `Title` | 16 | 600 | 24 |
| `Headline` | 13 | 600 | 20 |
| `Body` | 13 | 400 | 20 |
| `Control` | 13 | 500 | 20 |
| `Caption` | 12 | 400 | 18 |
| `Section` | 12 | 500 | 18 |
| `Reading` | 15 | 400 | 26 |
| `Code` | 13 | 400 | 20 |
`Code` is monospaced: its `Family` is `theme.MonoFamilies`, a list of the monospaced fonts of Windows, macOS and Linux that each system reads in order, so `basic.Text{Content: id, Style: th.Text.Code}` needs no family of its own. `editor.Editor` and code in markdown use it unless told otherwise.
The roles leave the color unset. `basic.Text` fills an unset color with `Ink`, and an unset size with that of `Body`, so `basic.Text{Content: "..."}` already reads well. For another color, use `WithColor`, as `th.Text.Caption.WithColor(th.Color.Ink2)`. `WithSize`, `WithWeight` and `WithAlign` change the other parts. The [text guide](text-and-ime.md) covers the rest of `text.Style`.
#### Spacing, corners, heights and shadows
- **Spacing**: `theme.Space2`, `Space4`, `Space6`, `Space8`, `Space10`, `Space12`, `Space16`, `Space20`, `Space24`, `Space28`, in logical pixels. All are even, which lands them on whole physical pixels at 100, 150 and 200 percent. Prefer them to raw numbers.
- **Corners**: `th.Radius.Check` (4), `Control` (8, a button, an input or a row), `Group` (12, a card) and `Dialog` (16).
- **Height**: `theme.ControlHeight` (30) is the height of a regular control.
- **Shadows**: `th.Color.Shadows(lift)` returns the two layers of a shadow for a height above the page: `theme.LiftNone`, `LiftControl`, `LiftKnob` or `LiftFloat`. The layers are `paint.BoxShadow`, the type `basic.Container`, `layout.Decoration` and the controls take, so they go straight into `Shadows: th.Color.Shadows(theme.LiftFloat)`. Each call makes a new slice: keep it once per theme when it sits on a hot path.
### A part with a look of its own
`basic.Theme` gives the widgets below it another theme, such as a dark panel in a light window:
```go
var darkPanel = theme.New(geom.Hex(0x2f5fd0), theme.BrightnessDark)
func inspector(child gowaku.Widget) gowaku.Widget {
return basic.Theme{Data: darkPanel, Child: child}
}
```
A theme set this way stays put when `SetTheme` changes the application's theme.
`basic.MediaQueryOf(ctx).Brightness` is the brightness the OS asks for, whatever theme is in use. `basic.ThemeOf(ctx).Brightness` is the one in use. Read the second to draw in step with the theme.
### Tokens of your own
A theme can carry values of your own type, beside the standard tokens. `theme.WithExtensionPair` adds a light and a dark value to a set, and `theme.Extension` or `theme.ExtensionOr` reads it back:
```go
type Brand struct{ Highlight geom.Color }
func brandSet() theme.Set {
set := theme.FromAccent(geom.Hex(0x2f5fd0))
return theme.WithExtensionPair(set,
Brand{Highlight: geom.Hex(0xffd60a)},
Brand{Highlight: geom.Hex(0x806b05)})
}
func highlight(ctx gowaku.BuildContext) geom.Color {
b := theme.ExtensionOr(basic.ThemeOf(ctx), Brand{Highlight: geom.Hex(0xffd60a)})
return b.Highlight
}
```
`theme.WithExtension` does the same for a single `*theme.Theme`. Both return copies and leave the original as it was. Reading an extension does not allocate, so it is fine in `Build`.
### Icons
Package `icons` holds 24 common icons as `*paint.Path` on the 24 unit grid of `basic.Icon`: `Folder`, `File`, `Document`, `Image`, `Search`, `Plus`, `Minus`, `Close`, `Check`, the four chevrons, `Settings`, `Trash`, `Edit`, `Copy`, `Home`, `Star`, `Info`, `Warning`, `Error`, `Menu` and `More`. They are drawn with a line 1.75 units wide with round ends, like the icons the widgets draw themselves, and take the color they are given. The same paths go into `SidebarItem.Icon`, `BreadcrumbItem.Icon`, `Button.Icon` and the `Tree.IconOf` of a file tree.
```go
// The paths are made once and kept: basic.Icon scales a path again
// whenever it gets another pointer.
type fileIcons struct {
folder, search *paint.Path
}
func newFileIcons() fileIcons {
return fileIcons{folder: icons.Folder(), search: icons.Search()}
}
func (ic fileIcons) header(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Row{Size: layout.MainMin, Spacing: theme.Space8, Children: []gowaku.Widget{
basic.Icon{Path: ic.folder, Size: 16, Color: th.Color.AccentInk},
basic.Icon{Path: ic.search, Size: 16, Color: th.Color.Ink2, Label: "Search"},
}}
}
```
Each call builds a new path, so keep them in a State or a struct like this rather than calling them in every `Build`. For a shape the set lacks, parse the path data of an icon set with `paint.ParseSVGPath`.
### Further reading
- [docs/DESIGN.md](../../DESIGN.md) (Japanese): the colors, type, shapes and components of the design, with the reasons.
- [ADR 0011](../../ADR/0011-own-design.md) (Japanese): why gowaku has its own design.
- [ADR 0065](../../ADR/0065-theme-extensions-and-coverage.md) (Japanese): theme extensions.
- `examples/gallery` shows the design, and follows the mode of the OS.
---
## Motion
[Guides](README.md) · [日本語](../ja/motion.md)
gowaku has animation built in, from widgets that move to new values on their own, to controllers and springs that you drive. This guide goes from the simplest to the most hands-on. The curves, springs and controllers are in package `motion`; the animated widgets are in `widgets/basic`, and page transitions in `widgets/nav`.
### Where time comes from
Every animation runs on a `core.Ticker`, which asks for a frame while it runs. When the motion arrives, the ticker stops and the window goes back to drawing nothing. Package `motion` never reads the clock itself: time comes from the tickers, which is what lets `gowakutest` move a fake clock in tests ([Testing and previews](testing-and-preview.md)).
Two rules hold for everything below:
- A new target starts from the value of the moment, so interrupting a motion never makes a jump.
- When the user asks the OS for less motion, `basic.ReduceMotionOf(ctx)` is true. The standard widgets then jump instead of moving or resizing, and keep their fades. Do the same in your own animations.
### Implicit animations
An implicit animation is a widget that, when one of its fields changes, moves to the new value over time instead of jumping. You change the field in `SetState` as usual; the widget does the rest.
| Widget | Animates |
|---|---|
| `AnimatedContainer` | Size, padding, color, corners, border and shadows. A width or height of zero does not animate. |
| `AnimatedOpacity` | Opacity. At 0 the child is out of hit testing, semantics and focus. |
| `AnimatedAlign` | The alignment of its child. |
| `AnimatedPositioned` | The place of a child of a `Stack`. |
Each has `Duration` (zero selects 200 ms) and `Curve` (nil selects `motion.Standard`).
```go
type panel struct{ gowaku.StatefulBase }
type panelState struct {
gowaku.StateBase
open bool
}
func (panel) CreateState() gowaku.State { return &panelState{} }
func (s *panelState) Build(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
height, color := float32(48), th.Color.Fill
if s.open {
height, color = 160, th.Color.AccentTint
}
return basic.Column{Size: layout.MainMin, Spacing: theme.Space8, Children: []gowaku.Widget{
control.Button{Label: "Toggle", OnPress: func() { s.SetState(func() { s.open = !s.open }) }},
basic.AnimatedContainer{
Duration: 250 * time.Millisecond,
Curve: motion.EaseOutCubic,
Height: height,
Color: color,
Radius: th.Radius.Group,
},
basic.AnimatedOpacity{Opacity: boolTo1(s.open), Child: basic.Text{Content: "Details"}},
}}
}
func boolTo1(b bool) float32 {
if b {
return 1
}
return 0
}
```
The standard controls animate in the same way: a switch slides its knob, a button sinks when pressed, a dialog fades and scales in.
### Switching children
`AnimatedSwitcher` moves from its old child to a new one. A child counts as new when it has another type or another key, so give children of the same type a key with `gowaku.Keyed`:
```go
type tabsState struct {
gowaku.StateBase
page, dir int // the page shown, and +1 or -1 for the way it went
}
func (s *tabsState) Build(gowaku.BuildContext) gowaku.Widget {
return basic.AnimatedSwitcher{
Duration: 250 * time.Millisecond,
Transition: basic.SlideTransition(0.04*float32(s.dir), 0),
Child: gowaku.Keyed(s.page, s.body(s.page)),
}
}
```
`Transition` decides the motion:
- `basic.FadeTransition`, the default, crossfades.
- `basic.SlideTransition(dx, dy)` slides the new child in from `dx, dy`, in fractions of its size, while it fades in, and the old one out the other way. 0.03 to 0.06 is a quiet shift; a negative `dx` goes back.
- `basic.ScaleTransition(from)` grows the new child from `from` to its size, as a window opens. 0.96 is gentle.
A transition of your own is a `basic.SwitcherTransition`: a function of the child, the progress `t` and whether the child is entering, which returns the child wrapped for that frame. It must return the same widget types for every `t`, or the child loses its state mid-motion. Build it from the paint-only widgets below.
### Curves
A `motion.Curve` maps the progress of a motion, from 0 to 1, to the progress of its value.
| Curve | Shape |
|---|---|
| `Standard` | Motion that begins and ends on screen. The default of the implicit widgets. |
| `Enter`, `Leave` | What arrives: fast, then slow to settle. What goes away: slow to start. |
| `Linear` | Constant speed. |
| `EaseInCubic`, `EaseOutCubic`, `EaseInOutCubic` | The usual easings. |
| `EaseOutBack`, `SpringOut` | Overshoot the end a little and come back. |
| `ElasticOut`, `BounceOut` | Ring like a plucked string; bounce on the end. |
`motion.CubicBezier(x1, y1, x2, y2)` makes a curve from control points, as in CSS:
```go
var gentle = motion.CubicBezier(0.2, 0, 0, 1)
```
### Animation controllers
When a motion is not "move to the new value", such as something that pulses, spins or plays on command, drive it with a `motion.AnimationController`. It runs a value between 0 and 1 over time. Set its fields, `Attach` it in `InitState`, and `Dispose` it in `Dispose`:
```go
type pulse struct{ gowaku.StatefulBase }
type pulseState struct {
gowaku.StateBase
c motion.AnimationController
}
func (pulse) CreateState() gowaku.State { return &pulseState{} }
func (s *pulseState) InitState() {
s.c.Duration = 800 * time.Millisecond
s.c.Curve = motion.EaseInOutCubic
s.c.OnChange = func() { s.SetState(func() {}) }
s.c.Attach(&s.StateBase)
s.c.Repeat(true)
}
func (s *pulseState) Dispose() { s.c.Dispose() }
func (s *pulseState) Build(gowaku.BuildContext) gowaku.Widget {
scale := motion.LerpFloat(0.9, 1.1, s.c.Value())
return basic.Scale{Scale: scale, Origin: layout.AlignCenter, Child: basic.Text{Content: "Live"}}
}
```
- `Forward()` runs to 1, `Reverse()` to 0, `Restart()` from 0 to 1, `Repeat(bounce)` until `Stop()`. `SetValue(v)` jumps without animating.
- `Value()` is the progress with the curve applied, `Progress()` without it, and `Status()` one of `motion.Dismissed`, `Forwarding`, `Reversing` and `Completed`.
- `OnChange` runs on every step; `OnStatus` when the status changes. `ReverseDuration` and `ReverseCurve` replace the forward ones on the way back.
- `Attach` takes a `motion.TickerSource`: the `StateBase` of a state, or the `RenderBase` of a render object.
Turn the value into what you draw with the lerp functions, `motion.LerpFloat`, `LerpColor`, `LerpOffset`, `LerpSize`, `LerpRect`, `LerpRRect`, `LerpInsets` and `LerpAffine`, or with a `motion.Tween[T]{Begin, End, Lerp}` and its `At(t)`.
### Springs
A spring moves like a mass on a spring rather than along a curve of fixed length. A new target keeps the velocity of the moment, so a quick press and release flows instead of jumping. `motion.SpringValue` is a number that follows its target this way:
```go
type knob struct{ gowaku.StatefulBase }
type knobState struct {
gowaku.StateBase
x motion.SpringValue
on bool
}
func (knob) CreateState() gowaku.State { return &knobState{} }
func (s *knobState) InitState() {
s.x.Spring = motion.BouncySpring()
s.x.OnChange = func() { s.SetState(func() {}) }
s.x.Attach(&s.StateBase, 0)
}
func (s *knobState) Dispose() { s.x.Dispose() }
func (s *knobState) Build(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Column{Size: layout.MainMin, Children: []gowaku.Widget{
control.Button{Label: "Move", OnPress: func() {
s.on = !s.on
s.x.Set(boolTo1(s.on)) // starts the motion; OnChange rebuilds
}},
basic.SizedBox{Width: 240, Height: 32, Child: basic.Stack{Children: []gowaku.Widget{
basic.Positioned{Left: 200 * s.x.Value(), Child: basic.Container{
Width: 32, Height: 32, Radius: 16, Color: th.Color.Accent,
}},
}}},
}}
}
```
- `Set(target)` names where to go. It does not call `OnChange`, so it is safe during `Build`.
- `Jump(v)` goes there at once; `Kick(velocity)` strikes the value and lets it come back; `Moving()` reports whether it is on its way.
- `Spring` holds the physics as `motion.Spring{Mass, Stiffness, Damping}`. `motion.SnappySpring()`, the zero value's choice, settles fast without overshoot, for what the pointer presses. `motion.BouncySpring()` overshoots a little, for parts that travel. `motion.CriticalSpring(stiffness)` reaches the target fastest without overshoot.
`motion.SpringSimulation` is the exact motion underneath, from a position and velocity to a target, for code that keeps its own time.
### Your own implicit animation
`motion.Implicit` is what the implicit widgets are made of. A state attaches it, tracks one `motion.Value` per animated field, sets the targets in `DidUpdateWidget`, and calls `Commit`:
```go
type glow struct {
gowaku.StatefulBase
Level float32
Child gowaku.Widget
}
type glowState struct {
gowaku.StateOf[glow]
m motion.Implicit
level *motion.Value[float32]
}
func (glow) CreateState() gowaku.State { return &glowState{} }
func (s *glowState) InitState() {
s.m.Attach(&s.StateBase, func() { s.SetState(func() {}) })
s.level = motion.Track(&s.m, s.Widget().Level, motion.LerpFloat)
}
func (s *glowState) DidUpdateWidget(gowaku.Widget) {
s.level.Set(s.Widget().Level)
s.m.Commit(300*time.Millisecond, motion.Standard)
}
func (s *glowState) Dispose() { s.m.Dispose() }
func (s *glowState) Build(ctx gowaku.BuildContext) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Container{
Color: th.Color.Accent.WithAlpha(s.level.Get()),
Child: s.Widget().Child,
}
}
```
`motion.Track` compares values with `==`; `motion.TrackFunc` takes a comparison for types such as slices. `Commit` does nothing when no target changed.
### Paint-only transforms
These widgets move only the picture. Layout, and in most cases the pointer, see the child in place, so they suit motions that end at rest, and they cost no layout per frame:
- `basic.Opacity{Opacity, Child}`.
- `basic.Translate{X, Y, Child}`, in fractions of the child's size.
- `basic.Scale{Scale, Origin, Child}`.
- `basic.Transform` and `basic.Rotate(radians, child)`. A turned widget is hit only inside its turned shape (`examples/rotate`).
### Pages and heroes
`nav.Navigator` moves between pages. By default a page that comes in slides in from the trailing edge by a few pixels while it fades in. `nav.PageRoute.Transition` takes a `nav.PageTransition` of your own, and `Instant: true` turns the motion off.
`nav.Hero` makes a child fly from one page to the next: give the small icon in a list row and the big icon on the detail page the same `Tag`, and the icon lifts off one page and lands on the other while the page moves.
```go
func noteRow(ctx gowaku.BuildContext, id int, color geom.Color) gowaku.Widget {
return basic.Row{Cross: layout.CrossCenter, Spacing: theme.Space8, Children: []gowaku.Widget{
nav.Hero{Tag: id, Child: basic.Container{Width: 24, Height: 24, Radius: 6, Color: color}},
control.Button{Label: "Open", OnPress: func() {
nav.NavigatorOf(ctx).Push(nav.PageRoute{Page: notePage{id: id, color: color}})
}},
}}
}
type notePage struct {
gowaku.StatelessBase
id int
color geom.Color
}
func (p notePage) Build(gowaku.BuildContext) gowaku.Widget {
return basic.Column{Size: layout.MainMin, Children: []gowaku.Widget{
nav.BackButton{},
nav.Hero{Tag: p.id, Child: basic.Container{Width: 96, Height: 96, Radius: 16, Color: p.color}},
}}
}
```
Tags must be comparable and unique on a page. A window that asks for less motion has no flights. `examples/navigator` shows the whole thing.
### Further reading
- The [animation page](../../catalog/en/animation.md) of the widget catalog.
- [ADR 0010](../../ADR/0010-motion-and-theme.md) (Japanese) on the design of `motion`, and [ADR 0037](../../ADR/0037-switcher-transitions.md) on switcher transitions.
---
## Text and Japanese input
[日本語](../ja/text-and-ime.md)
gowaku sets text itself: it shapes with HarfBuzz (through go-text), breaks lines by the rules of the W3C "Requirements for Japanese Text Layout" (JLReq), and draws the glyphs on the GPU. The same rules apply on every OS, so a paragraph breaks at the same places on Windows, Linux and macOS when the fonts are the same.
This guide covers the widgets that show text, the fonts, the Japanese typesetting rules and how to switch them, vertical text, and text input with an IME.
### Showing text
`basic.Text` shows a string. `basic.RichText` shows spans of different looks in one paragraph, with ruby. Both take a `text.Style`.
```go
package main
import (
"log"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/text"
"github.com/bankai-tensei/gowaku/widgets/basic"
)
func main() {
body := text.Style{Size: 18}
page := basic.Pad(24, basic.Column{Spacing: 12, Children: []gowaku.Widget{
basic.Text{Content: "吾輩は猫である。名前はまだ無い。", Style: body},
basic.RichText{Style: body, Spans: []text.Span{
{Text: "吾輩", Ruby: "わがはい"},
{Text: "は"},
{Text: "猫", Ruby: "ねこ"},
{Text: "である。"},
{Text: "名前", Style: body.WithWeight(700)},
{Text: "はまだ無い。"},
}},
}})
err := gowaku.Run(gowaku.App{Title: "text", Width: 480, Height: 200, Home: page})
if err != nil {
log.Fatal(err)
}
}
```
The zero `text.Style` is regular black text of 14 logical pixels, set by the JLReq defaults. Zero fields of a span's `Style` take the paragraph's value. The theme has ready styles for each role (`th.Text.Body`, `th.Text.Title`, `th.Text.LargeTitle` and so on, from `basic.ThemeOf(ctx)`); the `With` methods (`WithSize`, `WithWeight`, `WithColor`, `WithAlign`, `WithMaxLines`) return a copy with one field changed.
Text is not selectable by default. Wrap it in `field.SelectionArea` to let the user select and copy across paragraphs; ruby copies as its base text.
#### Cutting text short
`Style.MaxLines` limits a text to that many lines and ends the last one with an ellipsis "…": a one-line preview in a list row, a two-line description on a card. Do not cut strings by guessing their width.
```go
package app
import (
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/layout"
"github.com/bankai-tensei/gowaku/theme"
"github.com/bankai-tensei/gowaku/widgets/basic"
)
// mailRow shows the subject on one line and two lines of the body.
func mailRow(ctx gowaku.BuildContext, subject, body string) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Column{Size: layout.MainMin, Spacing: theme.Space4, Children: []gowaku.Widget{
basic.Text{Content: subject, Style: th.Text.Headline.WithMaxLines(1)},
basic.Text{Content: body, Style: th.Text.Body.WithColor(th.Color.Ink2).WithMaxLines(2)},
}}
}
```
- The lines before the last break as usual. The last line is filled up to the width, cut at grapheme clusters, so an emoji or a letter with its accents never splits. With `MaxLines: 1`, text that does not fit is cut at the width.
- The ellipsis always fits inside the width: characters come off the end until it does. Spaces and opening brackets such as 「 do not stay in front of it.
- The ellipsis comes at the logical end of the text: on the right in a left-to-right paragraph, on the left in a right-to-left one. In vertical text it is the vertical ellipsis, at the foot of the last column.
- What a screen reader reads, and `gowakutest`'s `Find`, stay the whole text. `Layout.Truncated` reports whether anything was cut, for a tooltip with the rest.
The main fields of `text.Style`:
| Field | What it does |
|---|---|
| `Family` | A font family tried before the default Japanese families, or several separated by commas, tried in order as in CSS: `"Cascadia Mono, Menlo, monospace"`. Families the system lacks are skipped |
| `Size`, `Weight`, `Italic` | Size in logical pixels (zero is 14), CSS weight (zero is 400), italic |
| `LineHeight` | Distance between baselines as a multiple of `Size` (zero is 1.5). Fixed, so a fallback font cannot make lines uneven |
| `Color` | Glyph color. The zero value is opaque black |
| `Align` | `AlignStart`, `AlignCenter`, `AlignEnd`, `AlignJustify` |
| `Direction` | Base direction for BiDi; zero follows the first strong character |
| `Orientation` | `text.Horizontal` or `text.Vertical` |
| `MaxLines` | The most lines (columns in vertical text) to show; zero is unlimited. Text cut short ends with "…" |
| `Indent`, `HangingIndent`, `TabStop` | First-line indent, indent of the other lines, tab stops |
| `LineBreak`, `Kinsoku`, `Punctuation`, `WesternSpacing`, `Hanging` | The JLReq rules, below |
| `Hyphenate` | Break English words with a hyphen |
| `Variations` | Axes of a variable font |
| `RubyRoom` | Keep room for ruby even where no span has ruby |
### Fonts
gowaku ships no fonts. `gowaku.Run` reads the fonts installed on the system, on a goroutine of its own while the window and the GPU device are created. The index of the fonts is cached in the user cache directory, so later starts are faster.
For each piece of text, the families are tried in this order:
1. The families of `Style.Family`, if set, in order.
2. The default Japanese families: Yu Gothic (Windows), Noto Sans CJK JP (Linux), Hiragino Sans (macOS), Meiryo, then the system's sans-serif.
3. For text that shows as emoji: Segoe UI Emoji, Noto Color Emoji and Apple Color Emoji come first.
Yu Gothic UI is left out on purpose: its kana and punctuation are proportional, which leaves nothing for the punctuation rules to work with. On Linux, install Noto Sans CJK JP (in Debian and Ubuntu, the `fonts-noto-cjk` package) for Japanese text to look right.
Color emoji are drawn from COLRv0, COLRv1, CBDT and sbix fonts. Variable fonts take their axes from `Style.Variations`; `Weight` already sets `wght` and `Size` sets `opsz` on fonts that have them. A face without an italic, as Japanese fonts are, is slanted by about 12° when `Italic` is set, except in vertical lines, for color emoji and for right-to-left scripts.
There is no way to hand `gowaku.Run` font files of your own. Fonts given as bytes are for tests and previews (`gowakutest.Options.Fonts`, `gowakupreview.Item.Fonts`), where fixed fonts make screenshots match on every machine, and for `text.NewShaper` when you use the `text` package on its own.
### Japanese typesetting
The defaults follow JLReq. Each rule has a field in `text.Style` to change it. `examples/jptext` sets each sentence twice, with a rule on and off, side by side:
```bash
go run ./examples/jptext
```
#### Line start and line end prohibitions (kinsoku)
Closing brackets, small kana, the prolonged sound mark, commas and full stops do not start a line. Opening brackets do not end one. Dashes and ellipses stay together. `LineBreak` sets how many characters the line start rule covers, like the `strict`, `normal` and `loose` of CSS `line-break`:
| `jlreq.Strictness` | Characters that may start a line |
|---|---|
| `jlreq.Strict` (default) | None of the prohibited ones |
| `jlreq.Normal` | Small kana and the prolonged sound mark |
| `jlreq.Loose` | Also iteration marks, hyphens and wave dashes |
`Kinsoku` says how a prohibited character is kept off the line start:
- `jlreq.Oidashi` (default) pushes the end of the line to the next line.
- `jlreq.Oikomi` squeezes the line to take the character in, and falls back to `Oidashi` if the line has too little to give.
#### Punctuation compression
Full-width brackets and punctuation have a blank half. When two of them meet, as in `」「` or `。」`, `jlreq.PunctuationSqueeze` (default) removes the blanks that JLReq 3.1.5 removes. `jlreq.PunctuationFull` keeps every mark on its full em box. The rule applies per glyph, and only where the glyph is on a full em box, so a proportional font does not lose space it does not have.
#### Space between Japanese and Western text
`jlreq.WesternQuarterEm` (default) puts a quarter em between Japanese and Latin letters or digits, as JLReq 3.2.5 describes. `jlreq.WesternNone` puts nothing. The space is spacing, not a character: it is not in the text, it is not copied, and a screen reader does not hear it.
#### Hanging punctuation
With `Hanging: true`, a comma or full stop that falls just past the end of a line hangs outside the measure instead of moving to the next line with the character before it. It is off by default.
#### Justification and indents
`Align: text.AlignJustify` stretches every line of a block but the last to the full width, by JLReq 3.8: Western word spaces open up first, then the gaps between Japanese characters. A Japanese paragraph usually starts one em in, which `Indent` does:
```go
st := text.Style{
Size: 16,
Indent: 16, // one em
Align: text.AlignJustify,
Kinsoku: jlreq.Oikomi,
Hanging: true,
}
```
`HangingIndent` is the indent of the other lines. `TabStop` sets tab stops in logical pixels; zero sets a tab as a space.
#### Ruby
Give a span a `Ruby` and the ruby is set above it, or to its right in vertical text. A span with ruby stays on one line as a group. Ruby longer than its base overhangs neighboring kana where it may, but never past the head or the end of a line: there it lines up with its base. For mono ruby, one reading per character, make one span per base character:
```go
spans := []text.Span{
{Text: "東", Ruby: "とう"},
{Text: "京", Ruby: "きょう"},
{Text: "の"},
{Text: "日本語組版処理", Ruby: "にほんごくみはんしょり"}, // group ruby
}
```
Text with ruby has a line height of at least `text.RubyLineHeight` (1.75) times the size, and room above its first line. Set `RubyRoom` on text whose ruby comes and goes, so that its lines do not jump.
A span with `Emphasis` gets emphasis dots (傍点) beside each character, on the side of ruby, such as the sesame of `text.EmphasisSesame`. `text/aozora` reads them from notes such as `対象[#「対象」に傍点]`.
Package `text/aozora` reads the ruby notation of Aozora Bunko, `|漢字《かんじ》` or `漢字《かんじ》`. `aozora.Spans` turns such text into spans for `basic.RichText`, with the given style on every span (the zero style takes the paragraph's). `aozora.Marks` finds the marks, `aozora.Plain` strips them. A text field can show such ruby while the text keeps the notation; see [Ruby in a text field](#ruby-in-a-text-field).
```go
const opening = "吾輩《わがはい》は猫《ねこ》である。|名前《なまえ》はまだ無い。"
page := basic.RichText{Spans: aozora.Spans(opening, text.Style{}), Style: text.Style{Size: 18}}
```
#### Hyphenation
`Hyphenate: true` lets English words break across lines with a hyphen, by Liang's algorithm and the American English patterns of hyph-utf8. The hyphen is drawn at the line end and is not part of the text. Other languages are not built in: package `text/hyphen` can parse other TeX patterns (`hyphen.Parse`), but a paragraph cannot take them yet.
#### Bidirectional text
Arabic and Hebrew mixed with other scripts are ordered by UAX #9. `Direction` is the base direction of each block (a block ends at a line feed):
- `text.DirectionAuto` (default) takes the direction of the first strong character, so an Arabic paragraph runs right to left by itself.
- `text.DirectionLTR` and `text.DirectionRTL` force one.
Carets, hit tests and selection follow the visual order on screen. The layout of widgets is not mirrored for right-to-left languages: a `Row` still runs left to right. Vertical text is always in logical order.
### Vertical text (tategaki)
Set `Orientation: text.Vertical`. Lines become columns, set top to bottom and stacked right to left. Japanese stands upright, Western text turns 90° clockwise, and punctuation takes its vertical form through the `vert` and `vrt2` features of the font. In vertical text, the width of a `Layout` is the height of a column, and `LineHeight` is the distance between the centers of columns.
Two span fields only matter in vertical text:
- `TateChuYoko` sets two or three digits horizontally within one em of the column (JLReq 3.4.3). Longer text shrinks to fit.
- `Upright` stands Western text upright, one letter below the other, as for an abbreviation.
```go
vertical := text.Style{Size: 18, Orientation: text.Vertical, Family: "Yu Mincho"}
colophon := basic.RichText{Style: vertical, Spans: []text.Span{
{Text: "明治"},
{Text: "39", TateChuYoko: true},
{Text: "年、雑誌「ホトトギス」に発表。"},
{Text: "GPU", Upright: true},
{Text: "で縦書きを描く。"},
}}
```
Ruby goes to the right of the column. Justification, indents and the JLReq rules work as in horizontal text. A paragraph is one widget; to set several paragraphs side by side, put them in a `basic.Row` in reverse order, because vertical text starts on the right.
A long vertical text scrolls sideways in a `basic.Scroll` with `Horizontal` and `Reverse`. `Reverse` starts the scroll range at the right end: the text opens at its first column, a text narrower than the box sits against the right edge, and when the window is resized the right end stays where it is. The wheel and the scroll bar move the text the same way as in any horizontal Scroll. The Scroll takes all the room it is given, so give it a height, here with a `SizedBox`:
```go
paragraphs := []string{"親譲りの無鉄砲で小供の時から損ばかりしている。", "小学校に居る時分学校の二階から飛び降りて一週間ほど腰を抜かした事がある。"}
style := text.Style{Size: 18, Orientation: text.Vertical, Indent: 18}
columns := make([]gowaku.Widget, 0, len(paragraphs))
for i := len(paragraphs) - 1; i >= 0; i-- {
columns = append(columns, basic.Text{Content: paragraphs[i], Style: style})
}
page := basic.SizedBox{Height: 560, Child: basic.Scroll{
Horizontal: true, Reverse: true,
Child: basic.Row{Size: layout.MainMin, Spacing: 18, Cross: layout.CrossStart, Children: columns},
}}
```
To move the view from code, as to open a book where the reader left it, put a `basic.ScrollController` in `Scroll.Controller`. Its offset counts from the start of the scroll range, the right end here: `JumpTo(0)` goes back to the first column, `Offset` reads where the view is, and `MaxOffset` how far it can go.
`examples/tategaki` sets the opening of *Botchan* this way, next to the same text set horizontally, with a vertical text field:
```bash
go run ./examples/tategaki
```
### Text input
`field.Input` edits text: selection, the clipboard, undo, IME composition, ruby and vertical text. It keeps its own text, so the zero value works. Set `Value` to replace the text from outside, and use `OnChange` to learn about edits. Text the IME is still converting is not an edit: `OnChange` runs once the IME commits it.
```go
package main
import (
"log"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/field"
)
type form struct{ gowaku.StatefulBase }
type formState struct {
gowaku.StateBase
name string
}
func (form) CreateState() gowaku.State { return &formState{} }
func (s *formState) Build(ctx gowaku.BuildContext) gowaku.Widget {
return basic.Pad(24, basic.Column{Spacing: 12, Children: []gowaku.Widget{
field.Input{
Label: "名前",
Placeholder: "山田花子",
Value: s.name,
OnChange: func(v string) { s.SetState(func() { s.name = v }) },
},
basic.Text{Content: "こんにちは、" + s.name + "さん"},
}})
}
func main() {
if err := gowaku.Run(gowaku.App{Title: "input", Home: form{}}); err != nil {
log.Fatal(err)
}
}
```
Other fields of `field.Input`:
- `Multiline` lets Enter start a new line and wraps long lines. In a single-line field, Enter runs `OnSubmit`, or, inside a `field.FormItem`, submits the `field.Form` around it (see [Forms](#forms)); Shift+Enter does the same, as in browsers.
- `SubmitOnEnter` turns a multiline field into the box of a chat: Enter runs `OnSubmit` (or submits the form), and Shift+Enter starts a new line. Enter that confirms an IME conversion only confirms it, and text the IME commits keeps its line breaks.
- `Autofocus` gives the field the keyboard when it first appears, as for the field of a dialog. It wins over the dialog's own focus.
- `Obscure` makes a password field. It draws a bullet per character and keeps the IME off, so that no input method composes or learns the text. It also asks the window for secure input while it has the keyboard. Copy and cut do nothing, undo keeps no history, and a screen reader hears a password field.
- `Controller` takes an `*field.InputController`, which reads and sets the selection, edits as the user would (`Insert`, `Replace`, `Undo`, `Copy`, `Paste`) and gives the field the keyboard (`Focus`). Offsets are bytes of the text. `Focus` and `SelectAll` may come before the field exists: the field takes them when it is built, also inside a dialog.
- `Bare` leaves out the box, for a field that is the page.
A chat box, and a Rename dialog whose field opens with its text selected:
```go
field.Input{
Label: "Message", Multiline: true, SubmitOnEnter: true,
Value: s.draft,
OnChange: func(v string) { s.SetState(func() { s.draft = v }) },
OnSubmit: func(v string) { s.send(v); s.SetState(func() { s.draft = "" }) },
}
```
```go
func (s *filesState) rename(ctx gowaku.BuildContext) {
s.name.SelectAll() // s.name is a field.InputController in the State
s.name.Focus()
overlay.ShowDialog(ctx, func(dismiss func()) gowaku.Widget {
return overlay.Dialog{Title: "Rename", Content: field.Input{
Value: s.file, Controller: &s.name,
OnChange: func(v string) { s.SetState(func() { s.file = v }) },
OnSubmit: func(string) { dismiss() },
}}
})
}
```
For long documents, use `editor.Editor` of `widgets/editor`. It shapes only the lines in view, so a document of 100,000 lines scrolls and takes typing without delay, and it has IME composition, find and replace, line numbers and decorations. It sets text horizontally and has no ruby: for vertical text or ruby while editing, use a multiline `field.Input`.
#### Forms
`field.Form` checks and submits the `field.FormItem`s below it together. A `FormItem` holds one control and its value; it checks the value when the control loses the keyboard and on submit, shows the error below the control, and turns the border of the control red. Every field control behaves the same in a `FormItem`: `Input`, `Search`, `NumberField`, `Autocomplete`, `TokenField`, `DropdownMenu`, `DatePicker`, `TimePicker` and `ColorPicker`. A control of several parts, such as a `TimePicker`, or one that opens a popup, such as a `DatePicker`, counts as one field: moving between its parts or into its calendar is not leaving it.
The error of `Required` follows the control: 入力してください (Required) for a text field, 選択してください (Choose one) for a choice (`DropdownMenu`, `DatePicker`, `TimePicker`, `ColorPicker`, `RadioGroup`, `SegmentedControl`, a `Chip` that toggles), and チェックしてください (Check this box) for a `Checkbox` or another control of a bool. `RequiredMessage` replaces it.
Enter in a single-line field of a `FormItem` submits the form, unless the field has an `OnSubmit` of its own. A `NumberField` first takes the typed number, and the form is submitted with it; outside a `FormItem`, Enter in a `NumberField` only takes the number.
For a birth date, give the `DatePicker` an `InitialMonth` some thirty years back and a `Max` of today. Its calendar then opens near the date, and its title goes to the months of the year and the years of a decade, so another year is a few presses away. The keyboard reaches the title with Tab, and the grids of months and years take the arrows, Page Up and Page Down, and Enter.
A registration form:
```go
package main
import (
"log"
"time"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/control"
"github.com/bankai-tensei/gowaku/widgets/field"
)
type signup struct{ gowaku.StatefulBase }
type signupState struct {
gowaku.StateBase
form field.FormController
name string
people float64
born time.Time
agreed bool
}
func (signup) CreateState() gowaku.State { return &signupState{people: 1} }
func (s *signupState) Build(ctx gowaku.BuildContext) gowaku.Widget {
today := time.Now()
return basic.Pad(24, field.Form{Controller: &s.form, OnSubmit: s.save, Child: basic.Column{Spacing: 12, Children: []gowaku.Widget{
// 入力してください
field.FormItem[string]{Value: s.name, Required: true, Child: field.Input{
Label: "氏名", Value: s.name, OnChange: func(v string) { s.SetState(func() { s.name = v }) },
}},
// Enter here submits the form, with the number just typed.
field.FormItem[float64]{Value: s.people, Child: field.NumberField{
Label: "人数", Value: s.people, Min: 1, Max: 9,
OnChange: func(v float64) { s.SetState(func() { s.people = v }) },
}},
// 選択してください. The calendar opens on 1995; its title goes to
// the months and the years.
field.FormItem[time.Time]{Value: s.born, Required: true, Child: field.DatePicker{
Label: "生年月日", Value: s.born, Today: today, Max: today,
InitialMonth: today.AddDate(-30, 0, 0),
OnChange: func(d time.Time) { s.SetState(func() { s.born = d }) },
}},
// チェックしてください, unless RequiredMessage says otherwise.
field.FormItem[bool]{Value: s.agreed, Required: true, RequiredMessage: "利用規約への同意が必要です", Child: control.Checkbox{
Label: "利用規約に同意する", Value: s.agreed,
OnChange: func(v bool) { s.SetState(func() { s.agreed = v }) },
}},
control.Button{Label: "登録", Style: control.ButtonPrimary, OnPress: func() { s.form.Submit() }},
}}})
}
func (s *signupState) save() { log.Printf("%s, %v, %s", s.name, s.people, s.born.Format("2006-01-02")) }
func main() {
if err := gowaku.Run(gowaku.App{Title: "signup", Home: signup{}}); err != nil {
log.Fatal(err)
}
}
```
#### Vertical input
A field with a vertical `Style` edits in columns. The caret, the selection and the IME follow the columns: Down moves to the next character, Left to the next column, and the IME's candidate window opens beside the caret.
```go
field.Input{
Multiline: true,
Style: text.Style{Size: 16, Orientation: text.Vertical},
OnChange: func(v string) { s.SetState(func() { s.draft = v }) },
}
```
#### Ruby in a text field
`Ruby` takes a function that finds ruby notation in the text. `aozora.Marks` has the right signature:
```go
field.Input{
Multiline: true,
Ruby: aozora.Marks,
Value: "|吾輩《わがはい》は猫である。",
OnChange: func(v string) { s.SetState(func() { s.text = v }) },
}
```
The field draws the ruby over its base and hides the notation, except in a mark that an end of the selection is in: that one shows as written, to be edited. Everything else (the value, `OnChange`, the selection, copy and undo, what a screen reader gets) works on the text as written, with the notation. Saved files keep the readings. Other notations work too: `Ruby` is any function that appends `text.RubyMark` values.
### The IME
While the user converts with an IME, the field draws the composition inline, at the caret, in the field's own font:
- Each clause has a thin underline of its own.
- The clause the candidates apply to (the target clause) gets a tinted background and a thick underline.
- The candidate window opens next to the target clause, or the caret, and keeps clear of the line; in vertical text it opens beside the column.
The IME is on only while a text field has the keyboard, so typing on a button does not start a conversion. When the field loses focus during a conversion, the field commits the composition itself, so nothing is lost. A password field (`Obscure`) keeps the IME off.
What each OS gives:
| OS | Through | Inline composition | Clauses and target clause | Candidate window at the caret |
|---|---|---|---|---|
| Windows | IMM32. IMEs built on TSF work through the system's compatibility layer | Yes | Yes | Yes |
| macOS | `NSTextInputClient` | Yes | Yes, from the underline thickness of the marked text | Yes |
| Linux, Wayland | `text-input-v3` | Yes | Target clause only (see below) | Yes |
| Linux, X11 | XIM | No: the input method draws the composition in its own window | No | No |
Notes:
- **Wayland.** The `text-input-v3` protocol carries the composition text and a cursor range, but no clauses. When the input method selects a range, as Mozc does with the clause it converts, gowaku highlights that range as the target clause and treats the rest as converted. Without a range, the whole composition is shown as unconverted. Verified with fcitx5 and Mozc on sway. ibus on GNOME has been tried only in part.
- **X11.** gowaku takes what the input method commits. The input method shows the composition and the candidates in its own windows, which gowaku cannot place at the caret.
- **macOS.** Inline composition, clauses and the candidate window are tested by code, not yet by hand.
- **Linux in general.** Text from an input method has not been verified end to end on a real desktop.
Wayland is used when `WAYLAND_DISPLAY` is set; `GOWAKU_BACKEND=x11` forces X11. See [Platforms](platforms.md).
### Using the text package directly
The `text` package works without widgets: shape a string once, then lay it out at any width. This is what the `-lines` mode of `examples/jptext` and `examples/tategaki` uses to print line breaks for comparing with other typesetting programs.
```go
package main
import (
"fmt"
"log"
"github.com/bankai-tensei/gowaku/text"
)
func main() {
shaper, err := text.NewSystemShaper()
if err != nil {
log.Fatal(err)
}
s := "「ほら、見て。」と彼は言った。行頭に句点が来ないように組む。"
l := shaper.Shape(s, text.Style{Size: 16}).Layout(16 * 10) // ten ems
for i := range l.LineCount() {
start, end := l.LineRange(i)
fmt.Println(s[start:end])
}
}
```
A `text.Shaper` and everything made from it belong to one goroutine. Inside an application, the widgets share the one that `Run` made; create your own only outside the widget tree, as above. A widget or a `layout.Painter` of your own gets the shared one with `core.DependOn[*text.Shaper](ctx)` in Build; the painter then draws a label at a point with `paint.Canvas.DrawText`, and `text.Labels` keeps the labels it picks while painting. Package `text/jlreq` holds the line breaking rules alone, on made-up metrics, with no fonts.
### See also
- [Accessibility](accessibility.md): what a screen reader gets from text and fields
- [Testing and previews](testing-and-preview.md): `gowakutest.Type` sends committed text to a field
- [ADR 0007](../../ADR/0007-text-architecture.md), [ADR 0023](../../ADR/0023-vertical-text.md), [ADR 0074](../../ADR/0074-inline-ruby.md) (Japanese): design decisions
---
## Accessibility
[日本語](../ja/accessibility.md)
Every gowaku window keeps an accessibility tree next to its widget tree: what each control is, what it is called, its value and state, and what a screen reader may do with it. gowaku hands that tree to the screen reader of the OS: UI Automation on Windows, AT-SPI2 on Linux, NSAccessibility on macOS. The standard widgets describe themselves. Your part is to give controls their labels, to describe what you build from smaller parts, and to keep the keyboard working.
The same tree is what `gowakutest` searches when a test calls `Find` or `Tap`, so a well-labeled application is also easy to test.
### Labels
A control without a name is read as "button" and nothing more. Give every control a label:
- `control.Button` reads its `Label`. A button whose label is not enough, such as the same 削除 on every row of a list, adds a `Hint`, which a screen reader says after the label.
- `field.Input` reads its `Label`, or its `Placeholder` when it has no label. A field in a group row that has its name there needs neither.
- `basic.Icon` and `basic.Image` read their `Label`. Leave it empty for pictures that are only decoration.
- `interact.Pressable` reads its `Label`, `Role`, `Value` and `State`. A pressable without a label is named by all of its texts joined with spaces.
A text inside a control that says the same as the control's label is left out of the tree, so a button is not read twice.
A `basic.Text` is always read. Wrap text that only decorates, such as the initial in an avatar next to the name, in `interact.ExcludeSemantics`. It leaves its subtree out of the tree, as `aria-hidden` does, and keeps drawing it and letting it take the pointer. Do not put controls inside: Tab still reaches them, but a screen reader cannot see them.
```go
package app
import (
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/layout"
"github.com/bankai-tensei/gowaku/theme"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/interact"
)
// person shows an avatar with an initial; only the name is read.
func person(ctx gowaku.BuildContext, initial, name string) gowaku.Widget {
th := basic.ThemeOf(ctx)
return basic.Row{Size: layout.MainMin, Cross: layout.CrossCenter, Spacing: theme.Space8, Children: []gowaku.Widget{
interact.ExcludeSemantics{Child: basic.Container{
Width: 32, Height: 32, Radius: 16, Color: th.Color.AccentTint,
Child: basic.Center{Child: basic.Text{Content: initial, Style: th.Text.Headline}},
}},
basic.Text{Content: name},
}}
}
```
```go
control.Button{Label: "削除", Hint: "請求書 2026-10", OnPress: remove}
```
### Describing your own widgets
`interact.Semantics` describes its child: a role, a label, a value, a hint, states, a live region, and the callbacks that do what a screen reader asks.
```go
package app
import (
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/semantics"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/interact"
)
// heading marks a title as a heading of level 1.
func heading(title string) gowaku.Widget {
return interact.Semantics{
Role: semantics.RoleHeading,
Level: 1,
Label: title,
Child: basic.Text{Content: title},
}
}
// status announces its text whenever it changes, once the reader is idle.
func status(msg string) gowaku.Widget {
return interact.Semantics{
Live: semantics.LivePolite,
Label: msg,
Child: basic.Text{Content: msg},
}
}
// volume is a range that the screen reader can step up and down.
func volume(v float64, up, down func()) gowaku.Widget {
return interact.Semantics{
Role: semantics.RoleSlider,
Label: "音量",
Range: semantics.Range{Min: 0, Max: 100, Value: v},
OnIncrease: up,
OnDecrease: down,
Child: basic.SizedBox{Width: 200, Height: 24},
}
}
```
The roles are in package `semantics`: buttons, checkboxes, switches, radios and groups, tabs, lists, trees, grids, menus, dialogs, headings, links, sliders, steppers, progress indicators, combo boxes, tooltips and more (`semantics.Role`). The states are bits of `semantics.State`: `Checked`, `Mixed`, `Selected`, `Expanded`, `Collapsed`, `Disabled`, `ReadOnly`, `Multiline`, `Multiselectable`, `Invalid`, `Required`, `Obscured`. `Focusable` and `Focused` are set by gowaku; leave them alone.
The callbacks are `OnTap`, `OnIncrease`, `OnDecrease`, `OnSetValue`, `OnExpand` and `OnCollapse`. A nil one leaves its action out, and none runs while `State` has `Disabled`. They run on the UI goroutine, like a click.
Live regions (`LivePolite`, `LiveAssertive`) are read when their label or value changes, not when they first appear.
Package `semantics` also has the tree itself (`semantics.Node`) and the difference between two trees (`semantics.Compare`, `semantics.Diff`). Applications rarely need them; tests read the tree through `gowakutest`.
### Focus and the keyboard
Tab and Shift+Tab move the focus between the controls of a window, in the order they are painted. Space and Enter press a focused button. Arrow keys move within a group, a list, a menu or a grid.
- Clicking a control gives it the focus, as native Windows controls do. Clicking where nothing takes focus clears it, but dragging a scroll bar leaves the focus where it was.
- `interact.FocusTraversalOrder{Order: n}` changes the Tab order, as `tabindex` does in HTML: controls with an order above zero come first, lowest first, and the rest follow in painting order.
- `interact.Focus` lets any widget take the keyboard: `OnKey` gets the key presses, `Autofocus` takes the focus when the widget first appears.
- `Pressable` takes `SkipTab` for an area that only the pointer should reach.
- A modal dialog keeps the focus inside itself while it is open.
```go
interact.FocusTraversalOrder{Order: 1, Child: field.Search{OnChange: s.search}}
```
#### The focus ring
The standard controls show a pale ring when they have the focus, but only when the keyboard gave it (like `:focus-visible` on the web): a mouse click does not light the ring. For your own controls, draw the same ring with `interact.FocusRing` and the `FocusVisible` flag of `Pressable`:
```go
interact.Pressable{Label: "Album", OnPress: open, Build: func(s interact.PressState) gowaku.Widget {
return interact.FocusRing{Visible: s.FocusVisible, Radius: 8, Child: cover}
}}
```
`interact.Focus` reports the same flag through `OnShowFocus`. The ring is drawn outside the child and takes no room, so leave a few pixels around it.
### Reduced motion
When the user asks the OS for less animation, `basic.ReduceMotionOf(ctx)` is true. The standard widgets then jump instead of moving or resizing, and keep their short fades. Explicit tickers, such as a spinning progress ring, keep running. gowaku reads the setting on each OS and follows its changes:
- Windows: Settings > Accessibility > Visual effects > Animation effects.
- macOS: Reduce motion in the accessibility settings.
- Linux: `enable-animations` of `org.gnome.desktop.interface`, read through xdg-desktop-portal. Without a portal, and on KDE, motion is not reduced.
### Checking in tests
`gowakutest.Tester.Warnings` checks the current frame and reports, among other things:
- `WarnUnlabeled`: a button, checkbox, slider or text field that tells assistive technology nothing.
- `WarnContrast`: text whose color is too close to what is behind it, below 4.5:1, or 3:1 for large text, as WCAG 2 asks.
```go
package app
import (
"testing"
"github.com/bankai-tensei/gowaku/gowakutest"
"github.com/bankai-tensei/gowaku/widgets/control"
)
func TestLabels(t *testing.T) {
tt := gowakutest.New(t, control.Button{Label: "保存", OnPress: func() {}}, gowakutest.Options{})
for _, w := range tt.Warnings() {
t.Error(w)
}
if _, ok := tt.Find("保存"); !ok {
t.Errorf("no button named 保存:\n%s", tt.Dump())
}
}
```
`Dump` prints the accessibility tree as a screen reader would see it, and `Options.ReduceMotion` stands for the OS setting. `gowaku-preview` runs the same checks on every preview. See [Testing and previews](testing-and-preview.md).
### Per OS
| | Windows | Linux | macOS |
|---|---|---|---|
| Bridge | UI Automation provider | AT-SPI2 over D-Bus (X11 and Wayland) | NSAccessibility |
| Screen readers verified | Narrator by hand, NVDA by its speech log | Orca by its debug log | VoiceOver tested by code only |
| Text fields | Text pattern: document, selection, caret; moves by character, word, line | Text and EditableText: the same range | Text, selection, lines, ranges |
The bridge does nothing until a screen reader asks, so an application without one pays nothing for the tree.
**Windows.** The provider answers the patterns Invoke, Toggle, Value, RangeValue, SelectionItem, ExpandCollapse, ScrollItem and Text. It raises focus, property, structure and live region events. Automated tests drive the windows through a UI Automation client written in Go.
**Linux.** The bridge connects to the accessibility bus when the desktop says a screen reader is on (`org.a11y.Status`), and otherwise waits for one to start. `GOWAKU_A11Y=1` forces the connection, and `NO_AT_BRIDGE=1` turns it off, as in GTK. Without a session bus there is no bridge. The tree was checked on X11 and on Wayland, and Orca was driven by keyboard under Xvfb and on a headless sway. On Wayland a node's position is relative to its window, as the protocol gives no screen coordinates. Live regions use `Object:Announcement`, which Orca 45 and later read.
**macOS.** Each node becomes an `NSAccessibilityElement`. Tests query the elements and their actions directly; reading with VoiceOver has not been done by hand yet.
Design notes, in Japanese: [ADR 0042](../../ADR/0042-accessibility-windows.md) (Windows, focus, reduced motion), [ADR 0043](../../ADR/0043-accessibility-linux.md) (Linux), [ADR 0085](../../ADR/0085-accessibility-macos.md) (macOS).
---
## Windows and the OS
[日本語](../ja/windows-and-os.md)
This guide covers what lies outside the widget tree: the application and its windows, title bars, menus, the tray and notifications, the clipboard, file dialogs, drag and drop, opening URLs, and the rules for goroutines.
### The application and the UI goroutine
`gowaku.Run` opens the first window and blocks until the last window is closed. The goroutine that calls it becomes the UI goroutine. Build, layout, paint, every callback of a widget, and `SetState` run on it, and nowhere else. Because of that, the state of an application needs no locks.
```go
func main() {
err := gowaku.Run(gowaku.App{
Title: "Notes",
Width: 900,
Height: 600,
Home: notes{},
})
if err != nil {
log.Fatal(err)
}
}
```
`Run` returns an error only when it cannot start: no GPU, no window system, or an OS gowaku does not support (`gowaku.ErrUnsupported`). A broken contract during a frame panics. On macOS the UI goroutine must be the main goroutine, so call `Run` from `main` itself, not from a goroutine.
`App` also takes the theme (`Theme`, `ThemeMode`), the locale and word tables of the standard widgets (`Locale`, `Strings`), the Linux application id (`AppID`), and the options of the first window: `OnClose`, `OnCloseRequest`, `CustomFrame`, `Icon`, `MinSize`, `MaxSize`, `AlwaysOnTop`, `Fullscreen` and `Transparent`, which work as the fields of `WindowOptions` below.
#### Work on other goroutines
Do slow work, such as reading files or the network, on a goroutine of its own, and bring the result back with `gowaku.Post`. `Post` is safe from any goroutine and runs its function on the UI goroutine. The state may be gone by then, so check `Mounted` first:
```go
func (s *pageState) load(path string) {
go func() {
data, err := os.ReadFile(path)
gowaku.Post(func() {
if !s.Mounted() {
return
}
s.SetState(func() { s.data, s.err = data, err })
})
}()
}
```
Outside `Run`, `Post` drops its function, so a worker can outlive the application. `gowaku.Quit` is also safe from any goroutine: it closes every window, which ends `Run`. It does not ask the windows (`OnCloseRequest` does not run), but `OnClose` does.
Calling `SetState` during a Build, or on a state that is no longer in the tree, panics.
### Multiple windows
`gowaku.OpenWindow` opens another window with a tree of its own. All windows share one GPU device and run on the one UI goroutine, so they can share state directly; `examples/multiwindow` shows this.
```go
h, err := gowaku.OpenWindow(gowaku.WindowOptions{Title: "Inspector", Width: 360, Height: 480}, inspector{})
if err != nil {
return err
}
// later, on the UI goroutine:
h.Close()
```
`WindowOptions` has `Title`, `Width`, `Height`, `Background`, and:
| Field | What it does |
|---|---|
| `OnClose` | Runs when the window closes, by the user, by `Close`, by `Quit` or because the last window went. The tree is still whole, so save here |
| `OnCloseRequest` | Runs when the user asks to close the window. Return false to keep it open |
| `OnDrawError` | Reports what the GPU could not draw, such as a custom shader it refused |
| `CustomFrame` | Removes the OS title bar (see below) |
| `Icon` | The window icon: one image, best 256 pixels square, or the same picture in several sizes |
| `MinSize`, `MaxSize` | Bounds of the client area in logical pixels |
| `AlwaysOnTop`, `Fullscreen` | As named. Wayland ignores `AlwaysOnTop` |
| `Transparent` | Shows the desktop through the alpha of what the window draws. On X11 it needs a compositing manager |
`gowaku.WindowOf(ctx)` returns the `*WindowHandle` of the window a widget is in. The handle can `SetTitle`, `SetIcon`, `SetFullscreen`, `SetAlwaysOnTop`, `SetSizeLimits`, `Activate`, `Hide`, `Show`, `Close` and `RequestClose`, and tell `Fullscreen()`, `Transparent()` and `Hidden()`. All handle methods run on the UI goroutine.
#### Asking before closing
`OnCloseRequest` runs when the user closes the window: the close button, Alt+F4, the taskbar, the window manager, or a screen reader. It must not block. To ask about unsaved work, return false, show a dialog, and call `Close` once you have the answer. A widget that knows what the window holds can set the callback itself:
```go
func (s *docState) Build(ctx gowaku.BuildContext) gowaku.Widget {
win := gowaku.WindowOf(ctx)
win.SetOnCloseRequest(func() bool {
if !s.dirty {
return true
}
overlay.ShowDialog(ctx, func(dismiss func()) gowaku.Widget {
return overlay.Dialog{
Title: "保存されていない変更があります",
Message: "閉じる前に保存しますか。",
Actions: []gowaku.Widget{
control.Button{Label: "保存しない", OnPress: func() { dismiss(); win.Close() }},
control.Button{Label: "保存", Style: control.ButtonPrimary, OnPress: func() { s.save(); dismiss(); win.Close() }},
},
}
})
return false
})
return s.page()
}
```
Closing from the program asks nothing: `Close`, `Quit`, and closing the owner of a modal window. `RequestClose` asks as the close button does.
On macOS the OS can also ask the whole application to quit: Cmd+Q, Quit in the Dock, logging out. `App.OnQuitRequest` answers that request: true quits as `Quit` does, false keeps running. Without it, every window gets a close request, as before, and the application ends once they have all closed. Windows and Linux send no such request, and never call it.
#### Staying in the tray
An application that lives in the tray, such as one that reminds of due tasks, hides its window when the user closes it, and quits only when asked to quit:
```go
var win *gowaku.WindowHandle // WindowOf(ctx), kept from InitState of Home
gowaku.Run(gowaku.App{
Home: home{},
OnCloseRequest: func() bool { win.Hide(); return false }, // close button, Cmd+W
OnQuitRequest: func() bool { return true }, // Cmd+Q, Dock, log out
})
// The tray: OnActivate: func() { win.Show() }, and an item that calls gowaku.Quit.
```
`WindowHandle.Hide` takes the window off the screen and the task bar, with its modal windows, without closing it: its tree and state stay, it draws nothing, and `Run` goes on. `Show` puts it back and brings it to the front; `Hidden` tells. On macOS a click on the icon in the Dock shows the hidden windows again. Wayland has no way to hide a window, so there `Hide` minimizes it and `Show` cannot bring it back; the user does, from the task bar.
#### Modal windows
`gowaku.ShowModal` opens a window that belongs to the window of `ctx` and blocks input to it until the new one closes, as a dialog of the OS does. It returns at once; the result comes back through `OnClose`. Call it from a callback, not from a Build.
```go
var h *gowaku.WindowHandle
h, err := gowaku.ShowModal(ctx, gowaku.WindowOptions{Title: "設定", Width: 420, Height: 300, OnClose: s.reload},
settings{onDone: func() { h.Close() }})
```
For a dialog inside the window, use `overlay.ShowDialog` with an `overlay.Dialog` instead.
#### Tabs that become windows
A `nav.TabBar` reports a tab dropped away from every bar of its group through `OnTearOff`, with a `nav.TabTearOff`. Take the tab out of its bar and open a window for it with `gowaku.TearOffWindow`, which places the new window so the tab comes out under the pointer. If the tab was alone in its bar, move the window instead with `WindowHandle.MoveTo`. On Wayland, which does not let applications place windows, the window opens where the compositor puts it.
```go
OnTearOff: func(e nav.TabTearOff) {
if e.Alone {
gowaku.WindowOf(ctx).MoveTo(e)
return
}
s.remove(e.Index)
gowaku.TearOffWindow(e, gowaku.WindowOptions{Title: "文書"}, docWindow{tab: e.Key})
},
```
### Title bars
By default the OS draws the title bar. On Wayland compositors without server-side decorations (GNOME, Weston), gowaku draws a small one itself.
`CustomFrame: true` takes the OS title bar off so the application draws its own. Put a `gowaku.TitleBar` at the top of the root with what it should hold, such as a menu bar or a search field. It draws the minimize, maximize and close buttons, moves the window when dragged where nothing takes the pointer, maximizes on a double click, and opens the window menu on a secondary click. Windows 11 shows its snap layouts over the maximize button. The edges still resize the window.
```go
gowaku.App{
Title: "Editor",
CustomFrame: true,
Home: basic.Column{Children: []gowaku.Widget{
gowaku.TitleBar{Child: menuBar},
basic.Expanded{Child: page},
}},
}
```
A nil `Child` shows the window title. The bar is 36 logical pixels high and takes no room in fullscreen. `examples/decorations` shows custom frames, icons, size limits, always on top, fullscreen and transparent windows.
### Menus and shortcuts
An `interact.Action` is a command: a label, a shortcut, whether it can run now, and an optional check mark. Build it once and hand the same value to the menu bar, context menus and toolbars. An action without `OnInvoke` is disabled: its menu items are grayed out and its shortcut does nothing.
```go
save := interact.Action{
Label: "保存(&S)",
Shortcut: interact.Shortcut{Key: input.KeyS, Modifiers: input.ModControl},
OnInvoke: s.save,
}
bar := overlay.MenuBar{Items: []overlay.MenuItem{
{Action: interact.Action{Label: "ファイル(&F)"}, Items: []overlay.MenuItem{
{Action: save},
{Separator: true},
{Action: interact.Action{Label: "終了(&X)", OnInvoke: gowaku.Quit}},
}},
}}
```
- `&` marks the mnemonic; Japanese labels put it in parentheses, as in `ファイル(&F)`.
- `overlay.MenuBar` is an ordinary widget: put it at the top of a column or in a `TitleBar`. Alt alone or F10 moves the focus to it, and the arrow keys, Enter and Escape work as in Windows. The shortcuts of its items work anywhere in the window.
- On macOS the menu bar becomes the system menu bar (`NSMenu`), with the application menu and the Window menu added. Mnemonics are dropped there, and `Ctrl` in a shortcut is the Command key.
- `interact.Actions` runs the shortcuts of actions that are in no menu, when nothing in focus uses the key. A focused text field uses the keys that type, alone or with Shift, and Enter and Shift+Enter, so a shortcut of bare Space, a letter or Enter does not run while the user types; Ctrl and Alt shortcuts the field does not use still do, Ctrl+Enter among them (Command counts as Ctrl on macOS).
- `overlay.ContextMenu` opens a menu on a secondary click on its child, on a long press with a finger or pen, or with the menu key or Shift+F10. `overlay.ShowPopupMenu` opens one at a position from code.
```go
overlay.ContextMenu{
Items: []overlay.MenuItem{{Action: copyAction}, {Action: pasteAction}},
Child: row,
}
```
gowaku draws its menus itself, the same on every OS. The exceptions are the macOS menu bar and the menu of a tray icon, which the OS draws.
### Tray icons and notifications
`gowaku.ShowTray` puts an icon in the tray of the desktop. The OS draws its menu, which takes the same `overlay.MenuItem` values as a menu bar. Call it on the UI goroutine during `Run`, for example from `InitState`.
```go
tray, err := gowaku.ShowTray(ctx, gowaku.TrayOptions{
Icon: icon, // image.Image, drawn at 16 to 32 pixels
Tooltip: "Notes",
OnActivate: func() { gowaku.WindowOf(ctx).Activate() },
Menu: []overlay.MenuItem{{Action: interact.Action{Label: "終了", OnInvoke: gowaku.Quit}}},
})
if errors.Is(err, gowaku.ErrNoTray) {
// GNOME without the AppIndicator extension has no tray.
}
```
`tray.Update` replaces what it shows, and `tray.Close` removes it.
`gowaku.Notify(ctx, title, body)` shows a notification: a toast on Windows, the notification service on Linux, the notification center on macOS. It shows also while the application is in front. A click on it runs `OnNotificationClick` of the first tray. Where the desktop shows no notifications, or the user has not allowed them, it returns `gowaku.ErrNoNotifications`. On macOS that includes every program that does not run from an .app bundle; see [Building and shipping](packaging.md).
macOS asks the user before the first notification. `gowaku.RequestNotifications` asks ahead, as at start-up, and tells the answer:
```go
gowaku.RequestNotifications(ctx, func(err error) {
// On the UI goroutine, after the call returned.
s.SetState(func() { s.canNotify = err == nil })
})
```
Notifications sent before the answer wait for it, and are dropped if the user refuses; after that `Notify` returns `ErrNoNotifications`. A later change in System Settings applies to the next `Notify` or `RequestNotifications`. Windows asks nothing and answers nil; Linux answers whether a notification service runs. Under a `gowakutest.Tester`, `SetNotificationsAllowed` decides the answer.
| | Tray | Notifications |
|---|---|---|
| Windows | `Shell_NotifyIcon` | Balloon of the tray icon, shown as a toast |
| Linux | StatusNotifierItem over D-Bus | `org.freedesktop.Notifications` |
| macOS | `NSStatusItem` | `UNUserNotificationCenter`, only inside an .app bundle |
### Clipboard
Text fields handle copy and paste on their own. For other data, the clipboard holds text, an HTML fragment, an image and a list of files, each there or not. Read and write it on the UI goroutine, outside a Build:
```go
// What can be pasted?
if gowaku.ClipboardHas(ctx)&gowaku.ClipboardImage != 0 {
c := gowaku.ReadClipboard(ctx, gowaku.ClipboardImage)
s.SetState(func() { s.picture = c.Image })
}
gowaku.WriteClipboard(ctx, gowaku.ClipboardContent{Text: "gowaku", HTML: "gowaku"})
```
Another program owns the data, so a read waits for it, up to a fraction of a second on Linux. These functions go through the window of the tree, so in a `gowakutest.Tester` they reach its own clipboard.
### File dialogs
`gowaku.ShowFileDialog` shows the file dialog of the system in front of the window of `ctx`, and later calls `done` on the UI goroutine with the chosen paths, or nil if the user canceled. The zero `FileDialog` opens one existing file; `Save`, `Multiple`, `Directory`, `Name`, `Folder` and `Filters` change that.
```go
gowaku.ShowFileDialog(ctx, gowaku.FileDialog{
Title: "画像を開く",
Filters: []gowaku.FileFilter{{Name: "Images", Patterns: []string{"*.png", "*.jpg"}}},
}, func(paths []string, err error) {
if err != nil || paths == nil {
return // gowaku.ErrNoFileDialog where the system has none
}
s.open(paths[0])
})
```
`WindowHandle.ShowFileDialog` does the same for code that holds a window and no context of it. Under a `gowakutest.Tester` the dialog is a fake one that the test answers with `tt.FileDialog().Choose(paths...)`. On Windows the dialog is modal. On Linux it comes from xdg-desktop-portal and the application goes on meanwhile; without a portal the result is `gowaku.ErrNoFileDialog`, and the application has to ask for a path another way. gowaku has no file dialog widget of its own. On macOS it is `NSOpenPanel` / `NSSavePanel`.
### Drag and drop
`interact.DragTarget` takes text or files dropped on its child: from the same window, from another gowaku window, or from another program such as Explorer, Finder, Nautilus or a browser. `interact.Draggable` drags data out of its child to any of those.
```go
interact.DragTarget{
Kinds: input.DataFiles,
OnHover: func(over bool) { s.SetState(func() { s.lit = over }) },
OnDrop: func(d input.DragData, pos geom.Offset) {
s.SetState(func() { s.files = append(s.files, d.Files...) })
},
Child: dropArea,
}
```
```go
interact.Draggable{
Data: input.DragData{Files: []string{path}},
Allowed: input.DropCopy,
OnDragEnd: func(effect input.DropEffect) {},
Child: row,
}
```
The data is text, a list of absolute file paths, or both. A move is the application's to carry out in `OnDragEnd`. Under the hood it is OLE on Windows, XDND on X11, `wl_data_device` on Wayland and `NSDraggingDestination` on macOS. `examples/dragdrop` shows both directions and a tray icon.
### Opening URLs
`gowaku.OpenURL` opens a URL with the application the system has for its scheme: a web page in the browser, `mailto:` in the mail program. It may be called from any goroutine, with or without `Run`, and returns once the system has the request. Anything but an absolute URL is `gowaku.ErrInvalidURL`.
OpenURL does not restrict the scheme, and some schemes run programs. For links you did not write, such as those in a document, allow only the schemes you mean to:
```go
if p, err := url.Parse(link); err == nil && (p.Scheme == "https" || p.Scheme == "http" || p.Scheme == "mailto") {
err = gowaku.OpenURL(link)
}
```
It uses ShellExecute on Windows, NSWorkspace on macOS, and on Linux the OpenURI portal, then `xdg-open`. No shell sees the URL.
### Theme at run time
`gowaku.SetTheme(ctx, set, mode)` replaces the theme of every window, and `gowaku.CurrentTheme(ctx)` returns the current one. `ThemeSystem` follows the light and dark modes of the OS while running.
### Summary of goroutine rules
| Safe from any goroutine | UI goroutine only |
|---|---|
| `Post`, `Quit`, `OpenURL`, `OpenInspector` | `SetState`, `OpenWindow`, `ShowModal`, `TearOffWindow`, `WindowOf` and all `WindowHandle` methods, `ShowTray` and `Tray` methods, `Notify`, `RequestNotifications`, `ShowFileDialog`, the clipboard functions, `SetTheme`, `CurrentTheme` |
Design notes, in Japanese: [ADR 0046](../../ADR/0046-menus-and-shortcuts.md) (menus), [ADR 0047](../../ADR/0047-modal-windows.md) (modal windows), [ADR 0048](../../ADR/0048-custom-title-bar.md) (title bar), [ADR 0049](../../ADR/0049-clipboard.md) (clipboard), [ADR 0050](../../ADR/0050-drag-and-drop.md) (drag and drop), [ADR 0051](../../ADR/0051-tray-and-notifications.md) (tray), [ADR 0076](../../ADR/0076-close-request.md) (close requests), [ADR 0161](../../ADR/0161-quit-request-hidden-windows-notification-permission.md) (quit requests, hidden windows, leave to notify).
---
## Testing and previews
[日本語](../ja/testing-and-preview.md)
A gowaku tree runs without a window. Package `gowakutest` mounts it in a test, draws it on the CPU, and moves a fake clock, so UI tests are ordinary `go test` tests that need no GPU and no display. Package `gowakupreview` and the command `gowaku-preview` draw small functions of your test files to PNG files on every save. A debug build adds an Inspector window to a running application.
### gowakutest
`gowakutest.New` mounts a widget and lays it out. The test then finds widgets by what they say to assistive technology, taps and types like a user, and checks the result.
```go
package app
import (
"testing"
"github.com/bankai-tensei/gowaku/gowakutest"
)
func TestCounter(t *testing.T) {
tt := gowakutest.New(t, counter{}, gowakutest.Options{})
tt.Tap("Add one")
if _, ok := tt.Find("count: 1"); !ok {
t.Errorf("the count did not change:\n%s", tt.Dump())
}
}
```
What a `Tester` does:
| Method | Returns | What it does |
|---|---|---|
| `Find(label)`, `FindAll(label)` | `(*Node, bool)`; `[]*Node` | The node with that label: a button, field or slider by its `Label`, a text by its content. The label must match whole. Of nodes that share it, one that can act (a tap or focus action, a text field) wins over plain text, so the caption a field draws above itself finds the field; then reading order |
| `FindRole(role, label)`, `FindAllRole(role, label)` | `(*Node, bool)`; `[]*Node` | The node of that role with that label, to tell apart nodes that share a label |
| `FindFunc(match)`, `FindAllFunc(match)` | `(*Node, bool)`; `[]*Node` | The nodes for which `match(*Node) bool` is true, in reading order: every button, a role with any label |
| `Tap(label)`, `TapAt(pos)` | — | Press and release the primary button over the node, or at a point |
| `SecondaryTap(label)`, `SecondaryTapAt(pos)` | — | Click the secondary (right) button, as to open a context menu |
| `MiddleTap(label)`, `MiddleTapAt(pos)` | — | Click the middle button (the wheel) |
| `DoubleTap(label)`, `DoubleTapAt(pos)` | — | Double-click the primary button, as to open a row of a `Tree` or select a word |
| `Hover(label)`, `HoverAt(pos)`, `Unhover()` | — | Move the pointer over the node or to a point without pressing, or out of the window |
| `Scroll(label, dx, dy, mods)`, `ScrollAt(pos, dx, dy, mods)` | — | Turn the wheel by notches, with the signs of `core.PointerEvent.Scroll`: positive `dy` is the wheel turned away from you, toward the top of a list, negative `dy` toward the bottom, positive `dx` to the right; with `input.ModControl`, a zoom |
| `Drag(label, by)`, `DragAt(from, to)` | — | Press, move in steps, one a frame, and release, as on a slider or a divider |
| `Press(label)`, `PressAt(pos)`, `MoveTo(pos)`, `Release()` | — | Hold a drag in progress: press the primary button and keep it down, move one step a frame, and let go, to take a screenshot or `Find` on the way |
| `DropFiles(label, paths...)`, `DropText(label, s)` and their `At` forms | `input.DropEffect` | Drop files or text from another program; they return what the drop did |
| `Type(s)` | — | Send `s` to the focused widget, as committed text from the keyboard or an IME |
| `Key(k, mods)` | — | Send a key press to the focused widget. It types nothing: `Key(input.KeySpace, 0)` presses a button, `Type(" ")` puts a space in a field |
| `Hold(mods)` | — | Keep modifier keys down for the taps, drags, hovers, drops, `Scroll` and `Key` that follow, until `Hold(0)`: a Shift-click, a Ctrl-click or a Ctrl-drag |
| `Advance(d)` | — | Move the clock by `d`, drawing the frames on the way |
| `Settle()` | — | Draw frames until nothing animates |
| `Pump()` | — | Run one frame at the current time |
| `Screenshot()`, `SaveScreenshot(path)` | `*image.NRGBA`; — | Draw the frame on the CPU; `SaveScreenshot` writes it as PNG |
| `Warnings()` | `[]Warning` | Check the frame for likely problems: overflow, including a child laid out past the edge of its parent, unlabeled controls and low contrast, among others. It looks where things are painted, through the zoom of a viewer and other transforms |
| `Semantics()`, `Dump()` | `*Node`; `string` | The accessibility tree, as a value or as text. Its rects, like those of `Find`, are in window coordinates, and it holds the rows a list builds just outside its view |
| `Clipboard()`, `SetClipboard(s)`, `ClipboardContent()`, `SetClipboardContent(c)` | `string`; —; `gowaku.ClipboardContent`; — | The Tester's own clipboard, which the copy and paste of fields and `gowaku.WriteClipboard` and `ReadClipboard` use |
| `FileDialogs()`, `FileDialog()` | `[]*FileDialog`; `*FileDialog` | The file dialogs that `gowaku.ShowFileDialog` showed and the test has not answered; a `FileDialog` has `Options()`, `Choose(paths...)`, `Cancel()` and `Fail(err)` |
| `Trays()`, `Notifications()`, `ClickNotification()` | `[]*Tray`; `[]Notification`; — | What `gowaku.ShowTray` and `gowaku.Notify` showed; a `Tray` has `Options()`, `Activate()` and `Choose(label)` |
| `Tree()` | `*core.Tree` | The `core.Tree`, for what the Tester does not offer |
A method that cannot do what it is asked, such as a tap on a label that is not there or a screenshot that cannot be written, fails the test, so none of them returns an error. An action on a label also fails when a user could not reach the node: outside the window, clipped away, as a row scrolled out of a list, or covered by something drawn above it; of a node that shows in part, it uses the part that shows. Like the clipboard, the tray, the notifications and the file dialogs are the Tester's own: `gowaku.ShowTray` and `gowaku.Notify` record into `Trays()` and `Notifications()`, where a test reads a menu, chooses an item or clicks a notification, and `gowaku.ShowFileDialog` waits in `FileDialogs()` for the test to answer. `gowaku.SetTheme` changes the theme of the tree; `ThemeSystem` follows `Options.Dark`.
The methods that act (the taps, hovers, scrolls, drags and drops, `Type` and `Key`) settle after they act, so a test reads the state after the transitions have ended. Two `Tap`s in a row are two single clicks, however near; use `DoubleTap` for a double click. What nobody can see is not in the tree: an `Opacity` of 0, the pages under the top of a `Navigator`, a collapsed pane. A text inside a control that says the same as the control is not in the tree either, so `Find` returns the control.
#### Typing into a field
Tap the field by its label to focus it, then type:
```go
func TestRename(t *testing.T) {
tt := gowakutest.New(t, renameForm{}, gowakutest.Options{})
tt.Tap("名前")
tt.Type("山田")
tt.Key(input.KeyEnter, 0)
if _, ok := tt.Find("保存しました"); !ok {
t.Error(tt.Dump())
}
}
```
`Type` sends committed text, as an IME does when the user confirms a conversion. The composition before that is not simulated.
#### What a control reports
`Find` returns a `gowakutest.Node` (the same type as `semantics.Node`). Its `Role`, `Value`, `State` and `Range` are what a screen reader hears, so a test reads the state of a control from them:
| Widget | `Role` | `Value` | Also |
|---|---|---|---|
| `control.Switch` | `RoleSwitch` | `"on"` or `"off"` | `State&semantics.Checked != 0` when on |
| `control.Checkbox`, a toggling `control.Chip` | `RoleCheckbox` | `"checked"` or `"unchecked"` | `State&semantics.Checked` |
| `control.Slider` | `RoleSlider` | what `Format` spells, or the value with two decimals: `"50.00"` | `Range.Value` is the number, `Range.Min`, `Range.Max` the limits |
| `control.NumberStepper` | `RoleStepper` | the value as shown | `Range.Value` |
| `control.SegmentedControl`, `control.RadioGroup` | `RoleRadioGroup` | the label of the selected option | |
| `field.DropdownMenu` | `RoleComboBox` | the label of the selected option | tap it, then tap an option by its label to choose |
| `field.Input`, `field.Search` | `RoleTextField` | the text | `Text` holds the text, selection and lines; a tap puts the caret in and selects nothing, so to replace the text send `Key(input.KeyA, input.ModControl)` before `Type` |
| `control.ProgressBar`, `control.ProgressRing` | `RoleProgress` | a percentage: `"40%"` | `Range.Value` from 0 to 100 |
| `collection.Table` | `RoleGrid`, named by its `Label` | | its rows are `RoleRow` children, named by all their cells; a selected row has `State&semantics.Selected`; each cell is a `RoleGridCell` named by its text, so `Tap("budget.xlsx")` taps that cell |
| `collection.Tree` | `RoleTree` | | its items are `RoleTreeItem`s with `Level`, `State&semantics.Expanded` and `Selected` |
| `collection.SidebarItem` | `RoleListItem` | the `Count`, if any | `Hint` holds the `Detail`; `State&semantics.Selected` |
Compare numbers through `Range.Value` rather than the string. When unsure, print `tt.Dump()`: it shows every node with its role, label and value.
#### Testing a dialog
While a dialog or a sheet is open, the page under it is out of the accessibility tree, as a screen reader sees it. `Find` and `Tap` then look only inside the dialog, so a confirm button may share its label with the button that opened it:
```go
func TestResetAsksFirst(t *testing.T) {
tt := gowakutest.New(t, settings{}, gowakutest.Options{})
tt.Tap("Notifications") // turn a switch off
tt.Tap("Reset") // the page's button opens the dialog
tt.Tap("Reset") // the dialog's button: the page is hidden now
if n, _ := tt.Find("Notifications"); n.Value != "on" {
t.Errorf("Reset did not restore the switch:\n%s", tt.Dump())
}
}
```
`gowakutest.New` and `gowaku.Run` both provide the `Overlay` that `overlay.ShowDialog` needs; open a dialog from a callback with the `BuildContext` of the State, `s.Context()`. Menus, dropdown lists and other popups do not hide the page: the control that opened them stays in the tree, marked expanded. A closed dialog fades out on a timer of about 120 ms, and leaves the screen and the overlay only when that ends; a tap that closes it settles through the fade, but where the dialog closes from an `After`, from code the test calls, or under a short `Options.Settle`, call `tt.Advance(200 * time.Millisecond)` before checking that it is gone.
#### Toasts and context menus
A toast is in the accessibility tree like any other text, so `Find("Saved")` finds it while it shows; `Advance` past its `Duration` closes it. A context menu opens with `SecondaryTap` on the row or control that has it, and its items are tapped by their labels:
```go
tt.SecondaryTap("report.pdf") // the row of a Table with OnContextMenu
tt.Tap("Delete") // an item of the menu
tt.Tap("Delete") // the confirm button of the dialog it opened
```
#### Hovering, scrolling, dragging and dropping
The pointer methods take a label, as `Tap` does, or a point with their `At` form:
```go
tt.Hover("Now playing") // pauses a carousel while the pointer rests on it
tt.Unhover() // the pointer leaves the window
tt.Scroll("Messages", 0, -3, 0) // three notches down
tt.Scroll("Map", 0, 1, input.ModControl) // Ctrl and the wheel away: zoom in
tt.Drag("Volume", geom.Offset{X: 60}) // the thumb of a slider, 60 px to the right
if tt.DropFiles("Attachments", "/tmp/report.pdf") == input.DropNone {
t.Error("the drop was refused")
}
```
`interact.Draggable` starts a drag through the OS, which a `Tester` has no host for, so dragging it does nothing; a test drops onto the `interact.DragTarget` with `DropText`, `DropFiles` or their `At` forms instead.
When two nodes share a label, `FindRole` picks one by its role, and `TapAt` presses it:
```go
tab, _ := tt.FindRole(semantics.RoleTab, "Settings") // not the heading of the page
tt.TapAt(tab.Rect.Center())
```
#### Another language
The standard widgets speak English in a test, whatever the OS. `Options.Locale` sets the language, as `App.Locale` does in an application, so that a calendar shows Japanese month names:
```go
tt := gowakutest.New(t, field.Calendar{}, gowakutest.Options{Locale: language.Japanese})
```
`language` is `golang.org/x/text/language`. `Options.Strings` adds the tables of words the application gives `App.Strings`.
#### Time
The clock starts at zero and stands still unless the test moves it. Animations and tickers run exactly as far as the test says:
```go
tt := gowakutest.New(t, timer{}, gowakutest.Options{})
tt.Advance(3 * time.Second) // a periodic ticker fires three times
if _, ok := tt.Find("3 秒"); !ok {
t.Error(tt.Dump())
}
```
`Advance` draws one frame every `gowakutest.FrameTime` (16 ms) while something animates, and one at each wake of a sleeping ticker. `Settle` fails the test if the tree is still moving after a minute of fake time.
The rule for what settles:
- `Settle`, and the methods that act, draw frames only while something animates, and stop as soon as nothing does. They never move the clock ahead to a sleeping ticker: a periodic ticker, the delay of a state's `After`, or that of a tooltip.
- `Advance(d)` moves the clock by `d` and runs every wake that comes due on the way.
So a tap that starts `s.After(16*time.Millisecond, ...)` needs `tt.Advance(16 * time.Millisecond)` after it. A wake that comes due while a tap's own animation runs does fire during the settle, but a test must not count on that: the animation may get shorter. A tooltip likewise opens after `Hover` and an `Advance` past its delay of half a second. A tree that never comes to rest, such as a spinner that stays, sets `Options.Settle` (500 ms suits the usual transitions); the taps, `Type`, `Key` and `Settle` then move the clock by that much instead.
`gowaku.Post` drops its function outside `Run`, and a `Tester` is not `Run`. Drive such code with tickers instead, or call what `Post` would have run directly. A delay belongs in a state's `After`, which `Advance` drives like a ticker (see [Concepts](concepts.md#running-code-after-a-delay)). A `Tester` belongs to the goroutine of its test.
#### Options
| Field | What it does |
|---|---|
| `Width`, `Height` | The window in logical pixels. Zero is 800 by 600 |
| `Scale` | Physical pixels per logical pixel in screenshots. Zero is 1 |
| `Theme`, `Dark` | The look. The light half is the default, so results do not depend on the OS |
| `Fonts` | Font files to set text in. Nil uses the system fonts, which Japanese text needs |
| `ReduceMotion` | Stands for the OS setting that asks for less animation |
| `Locale` | The language and region, as `App.Locale`: the words, month and day names and first day of the week of the standard widgets. Zero is English, whatever the OS |
| `Strings` | Tables of words the application adds, as `App.Strings` |
| `Settle` | How far the acting methods move the clock, for trees that never rest |
#### Warnings
`Warnings` checks the current frame and returns what it found, in painting order:
- `WarnOverflow`: content that does not fit its box, such as children past the end of a `Row` or text taller than its box.
- `WarnUnlabeled`: a button, checkbox, slider or text field that tells assistive technology nothing.
- `WarnContrast`: text below 4.5:1 against what is behind it, or 3:1 for large text. The text of a disabled control is not checked, as WCAG exempts inactive components.
- `WarnShader`: a custom shader without a `Fallback`, which the CPU renderer cannot draw.
```go
for _, w := range tt.Warnings() {
t.Error(w)
}
```
Each `Warning` has its `Kind`, `Rect`, `Text`, `Detail` and `Amount` (the overflow in pixels, or the contrast ratio). It draws a screenshot to measure contrast, so it costs about as much as one.
What is out of the accessibility tree because nobody can see or reach it is not checked: an `Opacity` of 0, and the page under an open dialog or sheet, which the scrim dims on purpose. The dialog, and what opens over it, are checked. Nor is what an ancestor clips away whole, such as a row scrolled out of the viewport of a `Scroll`, and text cut in part is measured against what shows of its background.
### Golden images
`Screenshot` draws with the same shader code as the GPU backends, so the picture matches a window to within rounding. To compare screenshots with stored files across machines, give the test fixed fonts: with the system fonts, text depends on what is installed. The Go fonts in `golang.org/x/image` have no Japanese glyphs, so pick a font with the glyphs you need and keep it in `testdata`.
gowaku has no golden helper of its own for applications; a few lines do it:
```go
var update = flag.Bool("update", false, "rewrite the golden files")
func TestCardGolden(t *testing.T) {
tt := gowakutest.New(t, card{}, gowakutest.Options{Width: 320, Height: 200, Fonts: [][]byte{goregular.TTF}})
const path = "testdata/card.png"
if *update {
tt.SaveScreenshot(path)
return
}
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
want, err := png.Decode(f)
if err != nil {
t.Fatal(err)
}
got := tt.Screenshot()
if !got.Bounds().Eq(want.Bounds()) {
t.Fatalf("size %v, want %v", got.Bounds(), want.Bounds())
}
for y := got.Rect.Min.Y; y < got.Rect.Max.Y; y++ {
for x := got.Rect.Min.X; x < got.Rect.Max.X; x++ {
if !near(got.At(x, y), want.At(x, y)) {
t.Fatalf("pixel %d,%d differs; run with -update and look at the PNG", x, y)
}
}
}
}
// near allows a difference of 2 per channel, for rounding.
func near(a, b color.Color) bool {
ar, ag, ab, aa := a.RGBA()
br, bg, bb, ba := b.RGBA()
d := func(p, q uint32) bool { return p>>8 <= q>>8+2 && q>>8 <= p>>8+2 }
return d(ar, br) && d(ag, bg) && d(ab, bb) && d(aa, ba)
}
```
Run `go test -update` to write the files, look at the PNGs, and commit them.
### Previews
A preview is a function in a `_test.go` file whose name begins with `Preview`, with no parameters, returning a widget or a `gowakupreview.Item`. Being in a test file, it reaches the package's unexported functions and stays out of the binary.
```go
package app
import (
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/gowakupreview"
"github.com/bankai-tensei/gowaku/widgets/basic"
)
func PreviewAlbumTile() gowaku.Widget {
return basic.SizedBox{Width: 180, Child: albumTile(demoAlbum)}
}
func PreviewSongs() gowakupreview.Item {
return gowakupreview.Item{Widget: songs(demoList), Width: 900, Height: 600}
}
```
Then run the command in the package directory:
```bash
go run github.com/bankai-tensei/gowaku/cmd/gowaku-preview .
```
Each preview is drawn light and dark, settled, and checked with `Warnings`. The command prints a report and where the files are, and exits with status 1 if the build or a preview failed. It writes one PNG per variant, a `.diff.png` where the picture changed since the last run, and `report.json` and `report.txt` for the package, which also hold the warnings and the accessibility tree. The files are meant to be read by people and by tools, AI agents included.
Flags:
| Flag | What it does |
|---|---|
| `-http localhost:7878` | Serve a page of the pictures that updates itself on every save (implies `-watch`) |
| `-watch` | Draw again whenever a `.go` file of the packages changes |
| `-run regexp` | Draw only the previews whose name matches |
| `-at 0,70ms,150ms` | Also draw the frames at these times, to see an animation part way |
| `-live Name` | Open the preview of this name in a window instead of drawing |
| `-out dir` | Where the pictures and reports go. The default is `gowaku-preview` in the temporary directory |
`gowakupreview.Item` sets the window (`Width`, `Height`, or several `Widths` for layouts that adapt), `Scale`, `Themes` (`LightAndDark`, `LightOnly`, `DarkOnly`), `Theme`, `At` and `Fonts`. A zero `Width` or `Height` leaves that length to the content, up to 1600 by 1200. A function named `PreviewTheme` returning a `theme.Set` gives the theme of every preview of the package.
The command writes nothing into your packages: it adds the test that draws the previews through `go test -overlay`. A package with its own `TestMain` must call `m.Run` when `gowakupreview.Active()` reports true, and may skip its own setup then.
### The Inspector
Build with `-tags gowakudebug` and press F12 in any window, or call `gowaku.OpenInspector()`:
```bash
go run -tags gowakudebug .
```
The Inspector is a separate window in the same process. It shows, for the other windows:
- the Widget, Element and RenderObject trees, and a picker that selects what is under the pointer;
- layout bounds, and the layers that were painted again, tinted for a moment;
- a graph of frame times by stage (build, layout, paint, batch, present), with GPU time and allocations, and what was rebuilt in a slow frame;
- the display list and the accessibility tree.
It only reads; it does not change values. Without the tag, `OpenInspector` does nothing and no code of the Inspector is linked in.
### See also
- [Accessibility](accessibility.md): labels, which the tests and the screen readers use alike
- [ADR 0040](../../ADR/0040-preview.md) (previews), [ADR 0068](../../ADR/0068-gowakutest-settle-option.md) (`Options.Settle`), [ADR 0128](../../ADR/0128-tester-pointer-locale-settle-mono.md) (pointer methods, `Locale`, the settle rule), [ADR 0132](../../ADR/0132-tester-clip-and-held-modifiers.md) (clipped warnings, `Hold`), [ADR 0073](../../ADR/0073-inspector.md) (Inspector), in Japanese
---
## Building and shipping
[日本語](../ja/packaging.md)
A gowaku application is one Go binary. It needs no C compiler to build and no runtime to install beside it: gowaku calls the OS and the GPU from pure Go, loading the system libraries at start. gowaku itself ships no installer, signing or updater; this guide covers the build, icons and the files each OS expects around the binary.
### Release builds
```bash
go build -trimpath -ldflags "-s -w" -o notes .
```
`-s -w` drops the symbol table and debug information, which makes the binary smaller (`examples/hello` is about 6 to 9 MB, depending on the OS). `-trimpath` keeps the paths of your machine out of it.
On Windows, add `-H windowsgui` so that the program opens no console window:
```bash
go build -trimpath -ldflags "-s -w -H windowsgui" -o notes.exe .
```
With `-H windowsgui`, the standard output and error go nowhere. Log to a file if you need the messages.
### Cross compiling
Every target builds from every host with `CGO_ENABLED=0`:
```bash
GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "-s -w -H windowsgui" -o notes.exe .
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags "-s -w" -o notes .
GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build -ldflags "-s -w" -o notes .
```
In PowerShell, set the variables first: `$env:GOOS = "linux"; $env:CGO_ENABLED = "0"`.
| Target | Runs |
|---|---|
| `windows/amd64`, `windows/arm64` | Yes, Direct3D 11 |
| `linux/amd64`, `linux/arm64` | Yes, Vulkan on Wayland or X11 |
| `darwin/arm64` | Yes, Metal |
| `darwin/amd64` (Intel Mac) and other systems | Builds, but `gowaku.Run` returns `gowaku.ErrUnsupported` |
See [Platforms](platforms.md) for what each target supports.
### Icons
The window icon is set at run time. Embed the pictures with `go:embed` and give them to `App.Icon` (the first window), `WindowOptions.Icon` (other windows) or `WindowHandle.SetIcon`:
```go
//go:embed icon.png
var iconPNG []byte
func appIcon() []image.Image {
img, err := png.Decode(bytes.NewReader(iconPNG))
if err != nil {
return nil // the default icon of the OS
}
return []image.Image{img}
}
```
One image, best 256 pixels square, is scaled down to every size the system wants. Give the same picture in several sizes to choose the smaller ones yourself. Where the icon shows:
- **Windows**: the title bar, the taskbar and the window switcher. The icon of the `.exe` file in Explorer is a resource compiled into the binary, which gowaku does not make; a resource compiler that writes a `.syso` file for the Go linker can add one.
- **macOS**: there is no icon per window. The last icon given shows in the Dock for the whole application. Inside an .app bundle, Finder shows the icon of the bundle (below).
- **Linux**: X11 shows the icon given. Wayland shows it only where the compositor has `xdg-toplevel-icon-v1`; elsewhere the compositor takes the icon of the desktop file that `App.AppID` names (below).
A tray icon is separate: `gowaku.TrayOptions.Icon`, drawn at 16 to 32 pixels.
### macOS: the .app bundle
A bare executable runs on macOS, but some things need a bundle. Notifications (`gowaku.Notify`) work only in an application with a bundle identifier, and return `gowaku.ErrNoNotifications` otherwise. A bundle also gives the application its name and icon in Finder and the Dock.
The layout:
```
Notes.app/
Contents/
Info.plist
MacOS/
notes the binary from GOOS=darwin GOARCH=arm64
Resources/
notes.icns optional
```
A minimal `Info.plist`:
```xml
CFBundleExecutablenotesCFBundleIdentifiercom.example.notesCFBundleNameNotesCFBundlePackageTypeAPPLCFBundleShortVersionString1.0.0CFBundleIconFilenotesNSHighResolutionCapable
```
`CFBundleIdentifier` is what notifications need. The first notification asks the user for permission. The Go linker signs `darwin/arm64` executables ad hoc, which lets them run on Apple Silicon. To give the application to other people, sign and notarize the bundle with Apple's tools.
### Linux: the desktop file
On Linux the desktop matches a window with its desktop file by the application id: the `app_id` on Wayland and the class of `WM_CLASS` on X11. Set `App.AppID` to the name of the desktop file without `.desktop`. Empty is `"gowaku"`.
```go
gowaku.Run(gowaku.App{Title: "Notes", AppID: "com.example.Notes", Home: notes{}})
```
Install `com.example.Notes.desktop` in `~/.local/share/applications` (or `/usr/share/applications`):
```ini
[Desktop Entry]
Type=Application
Name=Notes
Exec=/opt/notes/notes %F
Icon=com.example.Notes
Categories=Utility;
StartupWMClass=com.example.Notes
```
Put the icon under the icon theme, for example `~/.local/share/icons/hicolor/256x256/apps/com.example.Notes.png`. On Wayland this is where the title bar and the task switcher take the icon from.
What the binary loads at run time:
- Always: the Vulkan loader `libvulkan.so.1` and a Vulkan driver.
- Wayland: `libwayland-client.so.0`, `libwayland-cursor.so.0` and `libxkbcommon.so.0`.
- X11: `libX11.so.6`, and `libXi.so.6` if present, for pinches.
- Optional, through D-Bus: file dialogs (xdg-desktop-portal), the theme of the desktop, the tray, notifications and the screen reader bridge. Without a session bus these are off, and the application still runs.
Japanese text needs a Japanese font on the system, such as Noto Sans CJK JP; gowaku ships no fonts.
### Windows
Nothing to install beside the `.exe`. gowaku needs a GPU that runs Direct3D 11 (feature level 11.0 or later); it does not fall back to the software renderer WARP, and `Run` returns an error on a machine without a hardware GPU. Japanese text uses Yu Gothic, which Windows has.
---
## Platforms
[日本語](../ja/platforms.md)
gowaku runs on Windows, Linux and macOS (Apple Silicon), with no cgo on any of them. This page lists what each OS uses, what has been verified and where, and the known limits. "Verified" means checked on a running system; "tested by code" means automated tests drive the OS API, but nobody has yet checked the result by hand.
### Overview
| | Windows | Linux | macOS |
|---|---|---|---|
| Architectures | amd64, arm64 | amd64, arm64 | arm64 only |
| GPU | Direct3D 11 | Vulkan 1.0 | Metal |
| Window system | Win32 | Wayland, or X11 | AppKit |
| IME, inline with clauses | Yes (IMM32) | Wayland: yes, target clause only. X11: no | Yes (tested by code) |
| Screen reader | UI Automation | AT-SPI2 | NSAccessibility (tested by code) |
| Menu bar | Drawn by gowaku | Drawn by gowaku | System menu bar (`NSMenu`) |
| File dialog | `IFileOpenDialog`, `IFileSaveDialog` | xdg-desktop-portal | `NSOpenPanel`, `NSSavePanel` |
| Tray, notifications | `Shell_NotifyIcon`, toast | StatusNotifierItem, `org.freedesktop.Notifications` | `NSStatusItem`, `UNUserNotificationCenter` (bundle only) |
| Drag and drop with other programs | OLE | XDND, `wl_data_device` | Finder (tested by code) |
| Pinch, touch, pen | DirectManipulation, `WM_POINTER` | XInput 2, `wl_touch`, tablet-v2 (Wayland only for pens) | Trackpad pinch |
Other systems, and Intel Macs, build but `gowaku.Run` returns `gowaku.ErrUnsupported`.
### Windows
- **GPU**: Direct3D 11, feature level 11.0 or 11.1. A hardware GPU is required: the software renderer WARP is skipped, and without a GPU `Run` fails. On machines with several GPUs gowaku asks DXGI for the power-saving one, usually the integrated GPU, since a UI is idle most of the time (Windows 10 1803 and later; earlier versions take the OS default). Windows uses Direct3D 11 only; gowaku's Vulkan backend is not used on Windows except in its own comparison tests.
- **Window system**: Win32, with the standard title bar or a custom one (`CustomFrame`), where Windows 11 shows its snap layouts over the maximize button.
- **IME**: IMM32. IMEs built on TSF, such as the Microsoft IME of Windows 11 and Mozc, work through the system's compatibility layer. The composition shows inline with its clauses and the target clause, and the candidate window follows the caret, also in vertical text.
- **Accessibility**: a UI Automation provider. Verified with Narrator by hand and with NVDA through its speech log, and with automated tests through a UI Automation client.
- **Verified on**: Windows 11, on an Intel Core i7-12700H with Iris Xe graphics and on an NVIDIA RTX 3050 Ti. The benchmarks in the README were measured there.
### Linux
gowaku picks the window system at start: Wayland if `WAYLAND_DISPLAY` is set, X11 otherwise. If Wayland fails and `DISPLAY` is set, it falls back to X11 (XWayland usually runs). `GOWAKU_BACKEND=wayland` or `GOWAKU_BACKEND=x11` forces one. Drawing is Vulkan in both cases.
The libraries are loaded at start with purego: `libvulkan.so.1`; `libwayland-client.so.0`, `libwayland-cursor.so.0` and `libxkbcommon.so.0` for Wayland; `libX11.so.6` (and `libXi.so.6` if present) for X11. File dialogs, the desktop theme, the tray, notifications and the screen reader bridge go through D-Bus with a pure-Go client; without a session bus they are off and the application still runs.
#### Wayland
- **Title bar**: when the compositor offers `xdg-decoration`, it draws the title bar. Otherwise, as on GNOME and Weston, gowaku draws a small one (minimize, maximize, close, move, resize) in the theme of the application. `GOWAKU_WAYLAND_DECORATIONS=client` makes gowaku draw it anyway, for trying it out.
- **Scaling**: `fractional-scale-v1` with `viewporter`, else the integer scale of the output.
- **IME**: `text-input-v3`. The composition shows inline and the candidate window is placed at the caret. The protocol has no clauses: when the input method selects a range, as Mozc does, that range shows as the target clause. Verified with fcitx5 and Mozc on sway. With ibus on GNOME, the protocol exchange was correct but the keys did not reach ibus in the test setup; this is not resolved.
- **Limits of the protocol**: applications cannot place windows, so a torn-off tab opens where the compositor puts it; `AlwaysOnTop` is ignored; the window icon shows only where the compositor has `xdg-toplevel-icon-v1`, and otherwise comes from the desktop file named by `App.AppID`. A screen reader gets positions relative to the window, not the screen.
#### X11
- **IME**: XIM. gowaku takes the committed text; the input method draws the composition and the candidates in its own windows, which gowaku cannot place at the caret. There is no inline composition on X11.
- **Transparent windows** need a compositing manager.
- **Custom title bar**: dragging and resizing through `_NET_WM_MOVERESIZE` has not been checked with a real pointer.
#### Verified environments
gowaku has been run on:
- X11 through XWayland and through Xvfb.
- Wayland on WSLg's Weston and on a headless sway.
- Vulkan through Mesa's software driver (lavapipe) in all of these.
It has **not yet** been verified on a real Ubuntu desktop with a real GPU, nor on GNOME or KDE sessions. Screen reader support was checked with Orca through its debug log, on Xvfb and on the headless sway. Text from an input method has been verified on headless sway only, not end to end on a real desktop.
Notes on desktop services:
- The tray needs a StatusNotifierItem host. GNOME has one only with the AppIndicator extension; without it, `ShowTray` returns `gowaku.ErrNoTray`.
- File dialogs need xdg-desktop-portal; without it, the result is `gowaku.ErrNoFileDialog`. With the GTK 3 portal backend, the dialog may not stay in front of its window.
- The light and dark theme follows the portal's `color-scheme`, with the GNOME setting as a fallback. Reduced motion follows GNOME's `enable-animations`; there is none on KDE.
### macOS
- **Apple Silicon only.** `darwin/arm64` builds and runs; on Intel Macs `Run` returns `gowaku.ErrUnsupported`.
- **GPU**: Metal. The shaders are kept as source in the binary and compiled when the GPU device is created, so no Xcode is needed to build.
- **Threads**: AppKit runs only on the main thread, so `Run` must be called from the main goroutine.
- **Keys**: the Command key arrives as `input.ModControl`, so shortcuts written as Ctrl+C or Ctrl+S work as Cmd+C and Cmd+S. The Control key is `ModControl` too.
- **Menu bar**: `overlay.MenuBar` becomes the system menu bar, with the application menu and the Window menu at its ends. Shortcuts with Command go to the menu; others still reach the application.
- **Notifications** need the application inside an .app bundle with a bundle identifier; see [Building and shipping](packaging.md).
- **Tested by code, not yet by hand**: VoiceOver, drag and drop with Finder, and the IME (inline composition with clauses from the marked text, candidate window at the caret).
- **Verified on**: an Apple M5 Mac, where the macOS benchmarks were measured.
### Choosing at run time
| Variable | Effect |
|---|---|
| `GOWAKU_BACKEND=wayland` / `x11` | Linux: force the window system |
| `GOWAKU_WAYLAND_DECORATIONS=client` | Wayland: draw the title bar in gowaku even when the compositor offers one |
| `GOWAKU_A11Y=1` | Linux: connect to the accessibility bus even when the desktop says no screen reader runs |
| `NO_AT_BRIDGE=1` | Linux: never connect to the accessibility bus |
Design notes, in Japanese: [ADR 0013](../../ADR/0013-vulkan-backend.md) (Vulkan), [ADR 0014](../../ADR/0014-x11-platform.md) (X11), [ADR 0021](../../ADR/0021-wayland-platform.md) (Wayland), [ADR 0022](../../ADR/0022-linux-ime-dbus-file-dialog.md) (Linux IME and D-Bus), [ADR 0082](../../ADR/0082-macos-cocoa-metal.md) (macOS).
---
## Recipes
[Guide index](README.md) · [日本語](../ja/recipes.md)
Four shapes that most desktop applications take, each as a complete program. Copy one and change it. The last section lists the mistakes that are easy to make. Every program here compiles, and a `gowakutest` test can take its screenshot (see [Getting started](getting-started.md#see-it-without-a-window)).
### A list and a detail
A sidebar of notes with a search field above it and buttons below it, and the selected note in an editor that fills the rest of the window.
```go
package main
import (
"log"
"strconv"
"strings"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/geom"
"github.com/bankai-tensei/gowaku/layout"
"github.com/bankai-tensei/gowaku/theme"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/collection"
"github.com/bankai-tensei/gowaku/widgets/control"
"github.com/bankai-tensei/gowaku/widgets/field"
)
type note struct {
id int
body string
ctl field.InputController // one per note, so that a new note can take the focus
}
func (n *note) title() string {
t, _, _ := strings.Cut(n.body, "\n")
if t == "" {
return "New note"
}
return t
}
// preview is the start of the text under the title.
func (n *note) preview() string {
_, rest, _ := strings.Cut(n.body, "\n")
return strings.ReplaceAll(rest, "\n", " ")
}
type notes struct{ gowaku.StatefulBase }
type notesState struct {
gowaku.StateBase
all []*note
selected int // index into all, -1 for none
query string
next int
}
func (notes) CreateState() gowaku.State {
return ¬esState{all: []*note{{id: 1, body: "Groceries\nmilk, eggs"}, {id: 2, body: "Ideas\na quiet app"}}, next: 3}
}
func (s *notesState) add() {
s.SetState(func() {
n := ¬e{id: s.next}
s.next++
s.all = append(s.all, n)
s.selected = len(s.all) - 1
s.query = ""
n.ctl.Focus() // waits for the field that the next build creates
})
}
func (s *notesState) remove() {
s.SetState(func() {
if s.selected < 0 {
return
}
s.all = append(s.all[:s.selected], s.all[s.selected+1:]...)
s.selected = min(s.selected, len(s.all)-1)
})
}
func (s *notesState) Build(ctx gowaku.BuildContext) gowaku.Widget {
var rows []gowaku.Widget
for i, n := range s.all {
if s.query != "" && !strings.Contains(strings.ToLower(n.body), strings.ToLower(s.query)) {
continue
}
rows = append(rows, gowaku.Keyed(n.id, collection.SidebarItem{
Label: n.title(), Detail: n.preview(), Selected: i == s.selected,
OnPress: func() { s.SetState(func() { s.selected = i }) },
}))
}
sidebar := collection.Sidebar{
Title: "Notes",
Header: field.Search{Value: s.query, OnChange: func(q string) { s.SetState(func() { s.query = q }) }},
Children: rows,
Footer: basic.Row{Spacing: theme.Space8, Children: []gowaku.Widget{
control.Button{Label: "Add", Style: control.ButtonPrimary, OnPress: s.add},
control.Button{Label: "Delete", Style: control.ButtonQuiet, OnPress: s.remove},
}},
}
var detail gowaku.Widget = basic.Center{Child: basic.Text{Content: "No note selected"}}
if s.selected >= 0 {
n := s.all[s.selected]
// Keyed by the note, so that each note gets a field of its own: Input
// keeps its text and follows Value only when Value changes.
detail = gowaku.Keyed(n.id, field.Input{
Label: "Note " + strconv.Itoa(n.id), Multiline: true, Value: n.body, Controller: &n.ctl,
OnChange: func(v string) { s.SetState(func() { n.body = v }) },
})
}
return basic.Row{Cross: layout.CrossStretch, Children: []gowaku.Widget{
sidebar,
basic.Expanded{Child: basic.Padding{Insets: geom.All(theme.Space16), Child: detail}},
}}
}
func main() {
if err := gowaku.Run(gowaku.App{Title: "Notes", Width: 900, Height: 600, Home: notes{}}); err != nil {
log.Fatal(err)
}
}
```
What makes it work:
- `collection.Sidebar` is a whole panel: it draws its background and divider, scrolls its rows when they do not fit, and keeps `Header` and `Footer` in place. Put it first in a `Row` with `CrossStretch`, and the content in an `Expanded`.
- `SidebarItem.Detail` is the smaller second line of a row, here the start of the note. It is cut to one line with an ellipsis, and a screen reader hears it whole, once.
- A multiline `field.Input` fills the height it is given, label or not; the `Expanded` around the `Padding` gives it the rest of the window.
- `field.Input` keeps its own text. `gowaku.Keyed(n.id, ...)` gives each note its own field, so switching notes shows the right text.
- To focus a field that the next build creates, keep an `InputController` per item and call `Focus` before the field exists: it waits for the field, and wins over the focus of a dialog the field opens in.
### A settings window with a confirmation
Grouped rows of switches, a slider, a dropdown and a segmented control, and a Reset button that asks first.
```go
package main
import (
"log"
"strconv"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/geom"
"github.com/bankai-tensei/gowaku/layout"
"github.com/bankai-tensei/gowaku/theme"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/collection"
"github.com/bankai-tensei/gowaku/widgets/control"
"github.com/bankai-tensei/gowaku/widgets/field"
"github.com/bankai-tensei/gowaku/widgets/overlay"
)
type prefs struct {
notify bool
volume float32
quality string
theme int
}
var defaults = prefs{notify: true, volume: 50, quality: "medium"}
type settings struct{ gowaku.StatefulBase }
type settingsState struct {
gowaku.StateBase
p prefs
}
func (settings) CreateState() gowaku.State { return &settingsState{p: defaults} }
func (s *settingsState) set(f func(*prefs)) { s.SetState(func() { f(&s.p) }) }
func (s *settingsState) confirmReset() {
overlay.ShowDialog(s.Context(), func(dismiss func()) gowaku.Widget {
return overlay.Dialog{
Title: "Reset all settings?",
Message: "Every setting goes back to its default.",
Actions: []gowaku.Widget{
control.Button{Label: "Cancel", OnPress: dismiss},
control.Button{Label: "Reset", Style: control.ButtonDanger, OnPress: func() {
s.set(func(p *prefs) { *p = defaults })
dismiss()
}},
},
}
})
}
func (s *settingsState) Build(ctx gowaku.BuildContext) gowaku.Widget {
p := s.p
return basic.Scroll{Child: basic.Padding{Insets: geom.All(theme.Space24), Child: basic.Column{
Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space24, Children: []gowaku.Widget{
collection.Group{Title: "General", Children: []gowaku.Widget{
collection.GroupRow{Label: "Notifications", Child: control.Switch{Label: "Notifications", Value: p.notify,
OnChange: func(v bool) { s.set(func(p *prefs) { p.notify = v }) }}},
collection.GroupRow{Label: "Volume", Detail: strconv.Itoa(int(p.volume)), Child: basic.SizedBox{Width: 200,
Child: control.Slider{Label: "Volume", Value: p.volume, Max: 100,
OnChange: func(v float32) { s.set(func(p *prefs) { p.volume = v }) }}}},
// GroupRow names the dropdown; a Label on it would show a caption above it.
collection.GroupRow{Label: "Quality", Child: field.DropdownMenu[string]{Value: p.quality,
Options: []field.DropdownOption[string]{{Value: "low", Label: "Low"}, {Value: "medium", Label: "Medium"}, {Value: "high", Label: "High"}},
OnChange: func(v string) { s.set(func(p *prefs) { p.quality = v }) }}},
collection.GroupRow{Label: "Theme", Child: control.SegmentedControl{Label: "Theme", Options: []string{"Light", "Dark", "Auto"}, Selected: p.theme,
OnChange: func(i int) { s.set(func(p *prefs) { p.theme = i }) }}},
}},
control.Button{Label: "Reset", OnPress: s.confirmReset},
}}}}
}
func main() {
if err := gowaku.Run(gowaku.App{Title: "Settings", Width: 560, Height: 480, Home: settings{}}); err != nil {
log.Fatal(err)
}
}
```
What makes it work:
- `collection.Group` and `GroupRow` lay out a settings page: a label on the left, the control on the right. The row's label also names a control that has none of its own.
- The page is a `Column` with `theme.Space24` between its parts, the gap between sections. `basic.VStack` would put only `theme.Space8` between them, the gap between controls.
- `overlay.ShowDialog` takes the `BuildContext` of the State, `s.Context()`; call it from a callback. `gowaku.Run` and `gowakutest.New` already provide the `Overlay` it needs. It returns the same `dismiss` that `build` gets, to close the dialog from outside it, as when a save it waits for ends; once the dialog is closing or gone, calling `dismiss` does nothing.
- While the dialog is open, the page is out of the accessibility tree, so a test can press the dialog's Reset with `tt.Tap("Reset")`: see [Testing a dialog](testing-and-preview.md#testing-a-dialog).
### A long vertical text
Japanese set in columns from right to left, with ruby written in Aozora Bunko notation, a size slider, and a scroll that starts at the first column on the right.
```go
package main
import (
"log"
"strings"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/geom"
"github.com/bankai-tensei/gowaku/layout"
"github.com/bankai-tensei/gowaku/text"
"github.com/bankai-tensei/gowaku/text/aozora"
"github.com/bankai-tensei/gowaku/theme"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/control"
)
const book = `吾輩《わがはい》は猫である。名前はまだ無い。
どこで生れたかとんと見当《けんとう》がつかぬ。何でも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。`
type reader struct{ gowaku.StatefulBase }
type readerState struct {
gowaku.StateBase
size float32
}
func (reader) CreateState() gowaku.State { return &readerState{size: 20} }
func (s *readerState) Build(ctx gowaku.BuildContext) gowaku.Widget {
style := text.Style{Family: "Yu Mincho", Size: s.size, Orientation: text.Vertical, Align: text.AlignJustify, Indent: s.size} // one em
// Vertical paragraphs run right to left: put them in a Row in reverse order.
paras := strings.Split(book, "\n")
cols := make([]gowaku.Widget, 0, len(paras))
for i := len(paras) - 1; i >= 0; i-- {
cols = append(cols, basic.RichText{Spans: aozora.Spans(paras[i], text.Style{}), Style: style})
}
return basic.Column{Children: []gowaku.Widget{
basic.Padding{Insets: geom.All(theme.Space16), Child: control.Slider{Label: "Size", Value: s.size, Min: 14, Max: 36,
OnChange: func(v float32) { s.SetState(func() { s.size = v }) }}},
// Reverse: the scroll starts at the right end, at the first column, and
// a short text sits against the right edge.
basic.Expanded{Child: basic.Scroll{Horizontal: true, Reverse: true, Child: basic.Padding{Insets: geom.All(theme.Space24),
Child: basic.Row{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: s.size, Children: cols}}}},
}}
}
func main() {
if err := gowaku.Run(gowaku.App{Title: "Reader", Width: 900, Height: 600, Home: reader{}}); err != nil {
log.Fatal(err)
}
}
```
What makes it work:
- `text.Style{Orientation: text.Vertical}` sets a paragraph in columns; the paragraphs go into a `Row` in reverse order, because vertical text runs right to left.
- `aozora.Spans` turns `漢字《かんじ》` notation into spans with ruby for `basic.RichText`. Ruby never goes past the head or end of a line.
- `basic.Scroll{Horizontal: true, Reverse: true}` starts at the right end and keeps it in place when the window is resized. A `basic.ScrollController` in `Controller` reads and sets the position, to reopen a book where the reader left it.
- The font family falls back to the system default when the machine lacks it; see [Text and Japanese input](text-and-ime.md) for fonts per OS.
### Work in the background
A slow job on a goroutine that reports its progress, and a toast when it is done.
```go
package main
import (
"fmt"
"log"
"time"
"github.com/bankai-tensei/gowaku"
"github.com/bankai-tensei/gowaku/geom"
"github.com/bankai-tensei/gowaku/layout"
"github.com/bankai-tensei/gowaku/theme"
"github.com/bankai-tensei/gowaku/widgets/basic"
"github.com/bankai-tensei/gowaku/widgets/control"
"github.com/bankai-tensei/gowaku/widgets/overlay"
)
// worker runs the slow part. The app passes gowaku.Post and time.Sleep; a test
// passes functions it controls, because Post drops its function outside Run.
type worker struct {
Post func(func())
Sleep func(time.Duration)
}
type exporter struct {
gowaku.StatefulBase
Work worker
}
type exporterState struct {
gowaku.StateOf[exporter] // Widget() returns the exporter, with its Work
running bool
progress float32 // 0 to 1
runs int
}
func (exporter) CreateState() gowaku.State { return &exporterState{} }
func (s *exporterState) start() {
w := s.Widget().Work
s.SetState(func() { s.running, s.progress = true, 0 })
go func() { // never touch the State here: only through Post
for i := 1; i <= 10; i++ {
w.Sleep(300 * time.Millisecond)
p := float32(i) / 10
w.Post(func() {
if s.Mounted() { // the window may have closed meanwhile
s.SetState(func() { s.progress = p })
}
})
}
w.Post(func() {
if !s.Mounted() {
return
}
s.SetState(func() { s.running = false; s.runs++ })
overlay.ShowToast(s.Context(), overlay.Toast{Message: fmt.Sprintf("Export %d finished", s.runs)})
})
}()
}
func (s *exporterState) Build(ctx gowaku.BuildContext) gowaku.Widget {
var onPress func()
if !s.running {
onPress = s.start // a Button without OnPress is disabled
}
return basic.Center{Child: basic.SizedBox{Width: 320, Child: basic.Column{
Size: layout.MainMin, Spacing: theme.Space16, Children: []gowaku.Widget{
control.ProgressBar{Label: "Progress", Value: s.progress},
control.Button{Label: "Export", Style: control.ButtonPrimary, OnPress: onPress},
}}}}
}
func main() {
app := exporter{Work: worker{Post: gowaku.Post, Sleep: time.Sleep}}
if err := gowaku.Run(gowaku.App{Title: "Export", Width: 480, Height: 320, Home: basic.Padding{Insets: geom.All(theme.Space24), Child: app}}); err != nil {
log.Fatal(err)
}
}
```
What makes it work:
- Only the UI goroutine may call `SetState`. The goroutine hands each change to `gowaku.Post`, and the posted function checks `Mounted()`, because the window may have closed while the job ran.
- `overlay.ShowToast` takes the State's `BuildContext`, `s.Context()`, like a dialog. A toast sits at the bottom center of the window, over the content, and is announced by screen readers.
- `gowaku.Post` drops its function outside `Run`, so a test cannot rely on it. Passing the scheduling in, as `worker` does, lets the test step the job by hand:
```go
func TestExport(t *testing.T) {
steps := make(chan struct{})
posts := make(chan func(), 1)
w := worker{
Sleep: func(time.Duration) { <-steps }, // each sleep waits for the test
Post: func(fn func()) { posts <- fn }, // posted work waits for the test too
}
tt := gowakutest.New(t, exporter{Work: w}, gowakutest.Options{})
tt.Tap("Export")
for i := 0; i < 10; i++ {
steps <- struct{}{}
(<-posts)() // run it on the test's goroutine, which is the UI goroutine of tt
}
(<-posts)() // the end: the toast
tt.Settle()
if n, _ := tt.Find("Progress"); n.Range.Value != 100 {
t.Errorf("progress = %v", n.Range.Value)
}
if _, ok := tt.Find("Export 1 finished"); !ok {
t.Errorf("no toast:\n%s", tt.Dump())
}
}
```
`Find` finds a toast like any other text.
### Pitfalls
- **A field keeps its own text.** `field.Input` takes `Value` when it first appears and again only when `Value` changes. So keep `Value` in step: set it from `OnChange` inside `SetState`, and clear the field by setting `Value` to `""`. To show a different item in the same place, key the field by the item: `gowaku.Keyed(id, field.Input{...})`.
- **One controller per keyed field.** An `InputController` is attached to one field. If the field is keyed by item, keep a controller per item; a shared controller still points at the field that is about to go away when you call `Focus`.
- **A field is named by its Label, or else its Placeholder.** That name is what a screen reader says and what `tt.Tap` and `tt.Find` match. Labels match whole.
- **Labels should differ.** When two controls say the same, `Find` and `Tap` take the first in reading order: a progress bar labelled "Export" next to an "Export" button takes the tap.
- **Rows and columns take all the room they may.** Use `Size: layout.MainMin` to make a `Row` or `Column` as small as its children, and `basic.Expanded` to give one child the rest.
- **A Scroll needs bounded lengths.** Inside a `Column`, give it an `Expanded` or a `SizedBox`.
- **An image viewer leaves the arrows to the app.** `interact.InteractiveViewer` with the focus pans with the arrow keys while there is room to pan, and passes them on otherwise. `Keys: interact.ViewerKeysZoom` always passes them on, so that Left and Right can show the previous and next image; `ViewerKeysNone` keeps the viewer out of the focus. `WheelZooms: true` zooms with the plain wheel. An `interact.Listener` inside it takes the presses, so dragging there does not pan unless its `OnPointer` clears `e.Handled` on the `PointerDown`.
- **Dialogs and toasts take the State's context.** Call `overlay.ShowDialog(s.Context(), ...)` from a callback, not during `Build`.
- **`gowaku.Post` does nothing outside `Run`.** In tests, pass the scheduling in (see [Work in the background](#work-in-the-background)) or drive time with a ticker and `tt.Advance`.
---
## Architecture
[日本語](ARCHITECTURE.ja.md)
This document describes how gowaku is built: the layers, what each package does, how a frame runs, and which package may import which. It describes the code as it is. The reasons behind individual decisions are in [docs/ADR/](ADR/) (Japanese); the links below marked "background" point there.
### What gowaku is
gowaku is a desktop UI library for Go. Its design is declarative and Flutter-like, with three trees (Widget, Element, RenderObject) written as Go types; it draws shapes, text and shadows on the GPU, and does no work at all when nothing changes. It calls Direct3D 11 and Win32 on Windows, Vulkan with X11 or Wayland on Linux, and Metal with AppKit on macOS (Apple Silicon), all from pure Go: no cgo and no C compiler on any OS. Japanese text is a first-class case: line breaking follows JLReq, ruby and vertical writing are built in, and the IME composes inline with clause highlighting.
### Layers
```
┌──────────────────────────────────────────────────────────────────┐
│ application Widget / State / Build │
├──────────────────────────────────────────────────────────────────┤
│ gowaku (root) Run, App, windows, Post; ties the layers below │
├──────────────────────────────────────────────────────────────────┤
│ widgets/* standard widgets, in layers │
│ motion theme animation; design tokens │
├──────────────────────────────────────────────────────────────────┤
│ layout standard render objects │
│ core Widget → Element → RenderObject, reconcile, │
│ scheduling, focus, semantics tree │
├──────────────────────────────────────────────────────────────────┤
│ text fonts, shaping, JLReq line breaking, atlas │
│ paint icons Canvas records a DisplayList; stock icons │
├──────────────────────────────────────────────────────────────────┤
│ render DisplayList → gpu.Batch │
│ gpu Backend interface; d3d11, vulkan, metal, soft │
├──────────────────────────────────────────────────────────────────┤
│ platform Platform / Window interfaces; │
│ win32, x11, wayland, cocoa, dbus │
├──────────────────────────────────────────────────────────────────┤
│ semantics input geom shared value types at the bottom │
└──────────────────────────────────────────────────────────────────┘
```
`core` knows nothing of the GPU. It emits drawing commands into a `paint.Canvas`, and only `render` turns them into GPU work. As a result `core`, `layout`, `paint`, `text`, `theme`, `motion` and the widgets run under plain `go test`, with no GPU and no window.
### core: the three trees
| Tree | Lifetime | Role | Go form |
|---|---|---|---|
| Widget | Made on every Build, then dropped | Immutable description of part of the UI | A value-type struct |
| Element | As long as it stays in the tree | Links a widget to its render object, holds State, unit of diffing | Unexported type |
| RenderObject | Same as its element | Layout, painting, hit testing, semantics | `core.RenderObject` interface |
```go
type Widget interface{ Key() Key }
type StatelessWidget interface { Widget; Build(ctx BuildContext) Widget }
type StatefulWidget interface { Widget; CreateState() State }
type RenderWidget interface { Widget; CreateRenderObject() RenderObject; UpdateRenderObject(RenderObject) }
type State interface {
Build(ctx BuildContext) Widget
InitState(); DidUpdateWidget(old Widget); Dispose()
// unexported methods: implementations embed StateBase
}
```
- A widget embeds `StatelessBase` or `StatefulBase`, and a state embeds `StateBase` (or `StateOf[W]`, whose `Widget()` returns the typed widget). `RenderObject` implementations embed `RenderBase`. The unexported methods make the embedding mandatory, so that methods can be added to the interfaces later without breaking user code. Background: [ADR 0006](ADR/0006-core-tree-api.md), [ADR 0029](ADR/0029-typed-state-widget.md).
- **Reconcile** is the common keyed reconciliation of declarative UI toolkits. Two widgets match when their dynamic types and keys are equal. The type comparison looks at the interface's type word; it never walks struct fields with reflect. Lists of children are matched from the front, then from the back, then by key, in O(n).
- `type Key = any`. `Keyed(key, widget)` gives a widget a key. A key that is not comparable panics.
- **Scheduling.** `SetState` runs its function and marks the element dirty. At the start of a frame, dirty elements are sorted by depth and rebuilt from the parent down. `SetState` during Build panics.
- `BuildContext` gives access to inherited values: `core.DependOn[T]` subscribes to an `Inherited[T]` above, `core.Lookup[T]` reads one without subscribing.
- `core.Tree` holds the element and render trees of one window. A frame calls `Build`, `Layout` and `Paint` (or `Repaint`) in that order. The tree also dispatches pointer, key, text, composition and drag events, owns focus, and runs tickers.
- `core.Ticker` is the only way to ask for frames. Tickers follow the display's refresh, and the tree sleeps when none is active.
reflect is used only for the type identity of widgets and for resolving the type parameter of `DependOn`. No struct fields or tags are read.
#### API conventions
- Struct literals are the primary way to build a tree. For the common "just children" case, `widgets/basic` has one-line helpers: `VStack`, `HStack`, `Layers`, `Pad`.
- Every widget is a value type whose zero value works. Its fields are its whole API: no functional options, no builder chains.
- UI files import the widget layers they use (`widgets/basic`, `widgets/control`, ...). The root package `gowaku` keeps only the entry points for applications and windows, plus aliases of the types every widget writes: `Widget`, `BuildContext`, `State`, `StateBase`, `StateOf`, `StatelessBase`, `StatefulBase`, `Key`. It does not re-export widgets or lower-layer types. Background: [ADR 0081](ADR/0081-widget-layers.md).
- Initialization failures return `error`. Contract violations at run time panic with a message starting `gowaku:` that says how to fix the call. The library never recovers.
### layout: the constraint protocol
```go
type Constraints struct{ MinW, MaxW, MinH, MaxH float32 } // geom.Constraints; geom.Inf is unbounded
type RenderObject interface {
Layout(c geom.Constraints) geom.Size
Paint(cv *paint.Canvas, off geom.Offset)
HitTest(pos geom.Offset, r *HitTestResult) bool
Semantics(sb *SemanticsBuilder)
Parent() RenderObject; ChildCount() int; ChildAt(i int) RenderObject
Size() geom.Size; Offset() geom.Offset; SetOffset(off geom.Offset)
MarkNeedsLayout(); MarkNeedsPaint()
}
```
- Constraints go down, sizes come up, and the parent sets each child's offset. Children are laid out with `core.LayoutChild`.
- Layout restarts from the nearest relayout boundary (an object with tight constraints). A change of color only calls `MarkNeedsPaint` and does not lay out.
- `layout` holds the standard render objects: `RenderPadding`, `RenderAlign`, `RenderConstrainedBox`, `RenderFlex`, `RenderStack`, `RenderWrap`, `RenderGrid`, `RenderViewport`, `RenderList`, `RenderCustomLayout` (with a `Delegate`), `RenderDecoratedBox`, the effect objects, and so on. `layout` implements `core.RenderObject`; `core` does not know `layout`.
- `Scroll`, lists and `Grid` placed where their length is unbounded, `CrossStretch` with unbounded cross size, and `Expanded` without bounded room panic with a message that says how to fix the tree. Background: [ADR 0026](ADR/0026-unbounded-room.md).
- `Alignment` runs from 0 to 1 and has named values such as `AlignCenter`. Background: [ADR 0031](ADR/0031-style-copy-and-named-alignments.md).
### paint: recording drawing commands
`paint.Canvas` records calls into a `DisplayList`. It does not draw.
```go
func (c *Canvas) DrawRRect(rr geom.RRect, p Paint)
func (c *Canvas) DrawPath(p *Path, pt Paint)
func (c *Canvas) DrawImage(img *Image, dst geom.Rect, opacity float32)
func (c *Canvas) DrawGlyphs(run *GlyphRun, off geom.Offset, color geom.Color)
func (c *Canvas) DrawShadow(rr geom.RRect, blur float32, color geom.Color, offset geom.Offset)
func (c *Canvas) DrawBackdrop(rr geom.RRect, sigma float32)
func (c *Canvas) DrawShader(dst geom.Rect, call ShaderCall)
func (c *Canvas) DrawLayer(l *Layer, off geom.Offset)
func (c *Canvas) ClipRect / ClipRRect / ClipPath, Save / Restore
func (c *Canvas) Translate / Scale / Transform(geom.Affine), PushOpacity, PushBlend, PushGroup / PopGroup
type Paint struct {
Color geom.Color
Gradient *Gradient // linear, radial, focal or sweep, with stops
Stroke *Stroke // nil fills
Blend BlendMode // zero is source-over
}
```
- A border, a gradient and a shadow are parameters of one rounded rectangle, so one rectangle is one GPU instance.
- Blend modes cover the Porter-Duff operators and the W3C separable and non-separable modes. Modes that read the backdrop cost a copy of the pixels below. Background: [ADR 0044](ADR/0044-drawing-extensions.md).
- `PushGroup` draws a subtree into an offscreen picture with masks and filters. `GroupCache` keeps that picture across frames. Background: [ADR 0114](ADR/0114-gpu-layers-masks-filters.md), [ADR 0115](ADR/0115-cached-groups.md).
- `paint.SVG` parses a static SVG subset (shapes, paths, groups, transforms, paint, clips, masks, a set of filters, text) into drawing commands. Background: [ADR 0112](ADR/0112-svg-structure-paint-clip.md), [ADR 0113](ADR/0113-svg-filters-text.md).
- `paint.Shader` carries a user shader compiled ahead of time by `cmd/gowaku-shader`. Background: [ADR 0045](ADR/0045-shaders-svg-animated-images.md).
- Colors are `geom.Color{R, G, B, A float32}`, not premultiplied, in sRGB. Compositing happens on sRGB values.
#### Layers
`basic.RepaintBoundary` puts a `core.RenderRepaintBoundary` in the tree. It records its subtree into a `paint.Layer`, a display list of its own with a version number. `MarkNeedsPaint` climbs to the nearest boundary and stops there, so only dirty boundaries record again. `render` rasterizes a layer into a texture page and composites the pages over the full frame every time. Layers that cannot be cached (under scale or opacity, with paths or shaped clips, larger than a page, or changing every frame) are drawn inline, so the picture is the same either way. Presenting only dirty rectangles was measured and rejected. Background: [ADR 0019](ADR/0019-layers.md).
### render and gpu: batching
A desktop UI is many small rectangles and glyphs, with the occasional image or path. gowaku draws them with one large instance buffer and a few pipelines.
| Pipeline | Input | Use |
|---|---|---|
| P1 quad + SDF | Instanced quads | Rounded rectangles, borders, gradients, shadows, glyphs, images, blurred backdrops, all in one pixel shader that branches on `gpu.InstanceKind` |
| P2 path + stencil | Triangle fans | Marks the coverage of a path (no color output) |
| P3 quad + cover | Bounding quad | Fills where the stencil is set |
Custom shaders and the passes of group effects run as further pipelines on the same quads (`InstanceShader`, `InstanceEffect`).
```go
type Backend interface {
CreateSurface(h platform.NativeHandle, physicalWidth, physicalHeight int, scale float32) (Surface, error)
BeginFrame(s Surface, background geom.Color) error
Draw(s Surface, batch *Batch) error
EndFrame(s Surface) error // presents
CreateTexture(width, height int, format TextureFormat) (Texture, error)
UpdateTexture(t Texture, region image.Rectangle, pix []byte, stride int) error
CreateTarget(width, height int) (Texture, error)
DrawToTarget(t Texture, batch *Batch, scale float32) error
PrepareShader(s *Shader) error
Destroy()
}
```
- `render.Encode` turns a `paint.DisplayList` into a `gpu.Batch`: instances plus a list of `DrawCall`s (`DrawQuads`, `DrawFill`, `DrawClipPush`, `DrawClipPop`). Each draw call binds at most one texture. `render.Resources` owns the glyph atlas pages, images and layer pages shared by every window.
- **Shadows** are the SDF approximation of a Gaussian-blurred rounded rectangle, drawn in P1. There is no separate blur pass for them. Real blurs (`BackdropFilter`, `ImageFiltered`) use separable passes over a downsampled copy.
- **Antialiasing.** SDF shapes resolve their edges in the shader. Paths and shaped clips need 4x MSAA, which is used only on frames whose batch contains them (`Batch.Multisampled`). Background: [ADR 0009](ADR/0009-paths-and-clips.md), [ADR 0017](ADR/0017-multisample-on-demand.md).
- **Clips.** Axis-aligned rectangles use the scissor. Rounded rectangles and paths use levels in the depth buffer. The stencil is only for filling paths.
- **Coordinates.** A constant buffer carries viewport and scale, so the batch is in logical pixels. HiDPI changes only the scale.
- **Paths** are flattened on the CPU, then filled with stencil and cover (non-zero or even-odd). Small paths such as icons are rasterized on the CPU with `golang.org/x/image/vector` into the atlas instead.
- **Shaders.** One HLSL source in `gpu/shaders` is compiled ahead of time to DXBC for D3D11 (fxc) and SPIR-V for Vulkan (dxc), embedded with `go:embed`; `go generate ./gpu/...` regenerates them. Metal has an MSL port that the driver compiles when the device is created, so nothing is generated for macOS.
- **Backends.** `gpu/d3d11` calls COM vtables with `syscall.SyscallN`. `gpu/vulkan` opens the loader with purego on Linux (and `LoadLibrary` on Windows, for comparison tests only) and resolves functions through `vkGetInstanceProcAddr`. `gpu/metal` calls the Objective-C runtime through purego and builds on darwin/arm64 only. `gpu/soft` is a CPU reference that mirrors the shader math; it serves tests, headless screenshots and the catalog, not applications. Background: [ADR 0013](ADR/0013-vulkan-backend.md), [ADR 0020](ADR/0020-pixel-goldens.md), [ADR 0082](ADR/0082-macos-cocoa-metal.md).
- Pixel goldens drawn with `gpu/soft` run in CI. `go test -tags gpu ./internal/golden` compares D3D11 and Vulkan against the same goldens on a local machine.
### text: shaping and Japanese typesetting
```
string + text.Style
→ font lookup with fontscan, split into runs by script, with fallback
→ shaping with go-text/typesetting (glyph IDs, advances, offsets)
→ break opportunities by UAX #14
→ Japanese rules from text/jlreq
→ BiDi reordering (UAX #9), line wrapping → text.Layout (cached)
→ at paint time: glyphs → atlas coordinates (rasterized and uploaded on first use)
```
`text/jlreq` works on units of a rune and a measured advance, and knows nothing about fonts, so every rule is testable with made-up metrics.
| Rule | Behavior |
|---|---|
| Line start prohibition | Closing brackets, small kana, 。、ー々 etc. do not start a line. Strength is `Style.LineBreak` (`Strict`, normal, loose). |
| Line end prohibition | Opening brackets do not end a line. |
| Unbreakable sequences | —, …, ‥ runs and numbers with their units stay together. |
| Resolution | `Style.Kinsoku`: `Oidashi` (push out) or `Oikomi` (squeeze in). |
| Punctuation squeezing | Adjacent punctuation loses its half-width space (`Style.Punctuation`). |
| Hanging punctuation | Commas and full stops may stick past the line end (`Style.Hanging`, off by default). |
| Japanese–Western spacing | A quarter em between Japanese and Latin text (`Style.WesternSpacing`). |
| Ruby | Mono and group ruby, with control of overhang onto neighbors. `text/aozora` reads Aozora Bunko notation. |
- **Vertical writing**: `Style.Orientation`. Layout works on an inline and a cross axis, so carets, selections and the IME candidate position all go through the same transform. `vert`/`vrt2` substitution, tate-chu-yoko and vertical ruby are supported. Background: [ADR 0023](ADR/0023-vertical-text.md).
- Also in `text.Style`: alignment including justification, `Indent`, `HangingIndent`, `TabStop`, `Hyphenate` (Liang's algorithm in `text/hyphen`), variable font `Variations`, and base `Direction`. Faces without an italic get a synthetic slant. Background: [ADR 0024](ADR/0024-color-emoji-bidi-variable-hyphen-incremental.md), [ADR 0101](ADR/0101-synthetic-italic.md).
- **Fonts**: system fonts found with fontscan. The default families are Yu Gothic, Noto Sans CJK JP, Hiragino Sans and Meiryo. Yu Gothic UI is left out because its kana and punctuation are proportional, which JLReq does not assume. Background: [ADR 0007](ADR/0007-text-architecture.md).
- **Color emoji**: COLRv0, COLRv1, CBDT and sbix, on RGBA pages of the atlas.
- **Glyph atlas**: 2048² pages, R8 for outlines and RGBA8 for color, quarter-pixel horizontal positions, no hinting. Least recently used glyphs make room when the pages are full. Background: [ADR 0079](ADR/0079-atlas-lru.md).
- **Editing**: `Layout.HitTest`, `CaretRect`, `SelectionRects` and word and line motions work on grapheme clusters. Edits re-shape only the paragraphs they touch.
- The typesetting library stays behind `text`. The result of a layout is a list of `paint.GlyphRun`, so `paint` needs no fonts.
### Widgets
The standard widgets live in eight packages under `widgets/`, in layers. A package imports only layers below it, never one beside it. `widgets` itself holds no code.
| Layer | Package | Contents |
|---|---|---|
| 1 | `widgets/basic` | Theme, MediaQuery, localized strings; boxes and flex (`Container`, `Padding`, `SizedBox`, `Align`, `Row`, `Column`, `Stack`, `Wrap`, `Grid`, `AspectRatio`, `CustomLayout`, `LayoutBuilder`); effects (`Opacity`, `Blend`, `BackdropFilter`, `ShaderMask`, `Transform`); implicit animations; `Text`, `RichText`, `Icon`, `Image`, `SVG`; `Scroll`; `RepaintBoundary` |
| 2 | `widgets/interact` | `GestureDetector`, `MouseRegion`, `Listener`, `Focus`, `FocusRing`, `Pressable`, `Shortcut`/`Actions`, `Draggable`/`DragTarget`, `Semantics`, `InteractiveViewer` |
| 3 | `widgets/control` | `Button`, `Checkbox`, `Switch`, `Slider`, `RangeSlider`, `SegmentedControl`, `Radio`, `Chip`, `Card`, `NumberStepper`, `Tabs`, `SplitPane`, `Badge`, progress, `Disclosure`, `Link`, `InfoBar`, `Skeleton`, `Sparkline`, `CustomPaint` |
| 4 | `widgets/overlay` | `Overlay`, `Dialog`, `Sheet`, `Toast`, `Tooltip`, `MenuBar`, `ContextMenu`, popup menus |
| 5 | `widgets/field` | `Input` (single and multi-line, IME, selection, undo), `Search`, `Form`, `Autocomplete`, `DropdownMenu`, `NumberField`, `TokenField`, `ColorPicker`, `Calendar`, date and time pickers, `SelectionArea`, `CommandPalette` |
| 5 | `widgets/nav` | `Navigator` and routes, `Hero`, `BackButton`, `Breadcrumb`, `Steps`, `TabBar`, `Toolbar`, `StatusBar`, `DockLayout` |
| 6 | `widgets/collection` | `List`, `GridView`, `ReorderableList`, `Tree`, `Table`, `PropertyGrid`, `Group`, `Sidebar` |
| 6 | `widgets/editor` | `Editor`, a long-document editing surface with search, line styles and decorations |
Shared internals stay internal: `widgets/internal/kit` (below `basic`) holds small helpers, and `widgets/internal/behavior` (between `interact` and `control`) holds the hover, focus and press behavior that controls share. The full list, with pictures, is in the [widget catalog](catalog/en/README.md).
`markdown` is a separate module (`github.com/bankai-tensei/gowaku/markdown`) with its own CommonMark parser, so the main module keeps its short list of dependencies. Nothing in gowaku imports it. Background: [ADR 0099](ADR/0099-markdown-module.md).
### theme
The design itself is in [DESIGN.md](DESIGN.md) (Japanese). `theme` holds its tokens.
- `theme.Theme` has `Color` (roles derived from one accent, for light and dark), `Text` (a type scale of eight roles set for Japanese), and `Radius`. `Lift` gives two-layer shadows, as the `paint.BoxShadow` that `basic.Container` takes.
- `theme.Set` is a light and dark pair. `FromAccent` builds one from a color; `Default` is the built-in one. The application follows the OS brightness unless `App.ThemeMode` fixes it.
- Colors come from the HCT color space (CAM16 and L*), ported from material-color-utilities and checked against its test vectors.
- `theme.Extension[T]` lets applications add their own tokens.
- `basic.ThemeOf(ctx)` lives in `widgets/basic`, so that `theme` does not know `core`.
### motion
- `motion.AnimationController` runs a value from 0 to 1 over a duration, with a `Curve`: forward, reverse, repeat, stop.
- Curves: `Linear`, `EaseInCubic`, `EaseOutCubic`, `EaseInOutCubic`, `EaseOutBack`, `ElasticOut`, `BounceOut`, `Standard`, `CubicBezier`, and others.
- `SpringSimulation` carries velocity over, for returns after a drag and for scroll physics.
- `Tween[T]` and the `Lerp*` functions interpolate floats, colors, offsets, sizes, rects, rounded rects, insets and affines.
- `motion.Implicit` is the machinery behind implicit animations: a state keeps the previous widget values and re-targets them in `DidUpdateWidget`. The `Animated*` widgets of `widgets/basic` (`AnimatedContainer`, `AnimatedOpacity`, `AnimatedPositioned`, `AnimatedAlign`, `AnimatedSwitcher`) use it.
- Any number of tickers produce at most one build, layout and paint per frame. When the OS asks for reduced motion, `MediaQueryData.ReduceMotion` is set, and the standard widgets jump instead of moving or resizing, while keeping their fades.
- `motion` never reads the clock. Time comes from `core` tickers, so tests inject it and compare value sequences.
### Semantics and accessibility
- `RenderObject.Semantics(sb)` adds nodes to the accessibility tree through `core.SemanticsBuilder`. A `semantics.Node` has a role, label, value, hint, state, actions, live region, range, and text information for fields. The default walks the children.
- Standard widgets always report a role and a label.
- A subtree whose `core.Hider` reports hidden (such as `Opacity` at zero) is left out of semantics, hit testing and Tab traversal. It cannot be heard, pressed or focused. Background: [ADR 0027](ADR/0027-hidden-subtrees.md).
- After each frame, and only while a screen reader listens, the root package compares the new tree with the last one (`semantics.Compare`) and hands the difference to the window's `platform.Accessibility` bridge: UI Automation on Windows (COM objects implemented in Go in `platform/win32/com`), AT-SPI2 over D-Bus on Linux (`platform/dbus`), and NSAccessibility on macOS. Background: [ADR 0042](ADR/0042-accessibility-windows.md), [ADR 0043](ADR/0043-accessibility-linux.md), [ADR 0085](ADR/0085-accessibility-macos.md).
- `semantics` sits below both `core` and `platform` and imports only `geom`, so the platform layer knows the tree without knowing `core`.
### Frames and threads
```
event loop:
for windows remain {
ev := platform.WaitEvent(timeout) // blocks; an idle app uses no CPU
handle(ev) // hit test → handler → SetState
pump() // runs posted functions, then a frame
} // for every window that needs one
frame():
1. build dirty elements, by depth, with reconcile
2. layout from relayout boundaries (build and layout repeat at most 3 times
if layout asked for a rebuild)
3. paint record into the canvas; only dirty repaint boundaries record again
4. render DisplayList → Batch → Backend: BeginFrame, Draw, EndFrame (present)
5. speak semantics difference to the screen reader, if one listens
```
- Frames run only while something is dirty or a ticker is active. Present waits for vsync (D3D11 sync interval 1, Vulkan FIFO), which paces animation. Otherwise the loop sleeps in `WaitEvent`.
- During an OS modal loop, such as a window drag-resize on Windows, the platform calls back into the same pump so frames keep coming. Background: [ADR 0001](ADR/0001-win32-modal-loop.md).
- At start, the GPU device is created while fonts load, in parallel. Background: [ADR 0018](ADR/0018-parallel-startup.md), [ADR 0080](ADR/0080-startup.md).
#### Thread model
- The goroutine that calls `gowaku.Run` becomes the UI goroutine. The platform locks it to its OS thread (Win32 message queues, the D3D11 immediate context and AppKit all have thread affinity). On macOS it must be the main goroutine.
- Build, layout, paint, `SetState` and every callback run on the UI goroutine. Other goroutines call `gowaku.Post(fn)`, which queues `fn` and wakes the loop: `PostMessageW` on Windows, a self-pipe on X11 and Wayland, a posted event on macOS.
- `Run` returns an error only for failed initialization. A lost device during a frame panics.
- Building with `-tags gowakudebug` adds the Inspector (F12 or `gowaku.OpenInspector`), a separate window that shows the trees, layout bounds, repaints, frame times and the semantics tree. Without the tag none of it is linked. Background: [ADR 0073](ADR/0073-inspector.md).
#### Multiple windows
- One process has one GPU device. Each window has its own surface (swap chain and render targets), its own `core.Tree` and its own scheduling. The shaper, glyph atlas, pipelines and images are shared.
- There is one event loop. Every event carries a window ID.
- `gowaku.OpenWindow(opts, root)` opens a window and returns a `*WindowHandle`. `gowaku.ShowModal(ctx, opts, root)` opens a modal window that blocks input to its owner. `overlay.ShowDialog` is an overlay inside the same window. Background: [ADR 0047](ADR/0047-modal-windows.md).
### platform: the window layer
```go
type Platform interface {
CreateWindow(opts WindowOptions) (Window, error)
WaitEvent(timeout time.Duration) Event
Brightness() Brightness
ReduceMotion() bool
Locale() string
Wake() // from any goroutine
SetModalHandler(fn func())
Trays
Destroy()
}
type Window interface {
ID() WindowID
PhysicalSize() (w, h int); Scale() float32
NativeHandle() NativeHandle // what gpu needs for a surface
SetIMEEnabled(bool); SetIMECursorRect(x, y, w, h int); SetIMEVertical(bool); CancelComposition()
SetCursor(input.Cursor); ClipboardText() string; SetClipboardText(string)
Clipboard; Dragging; Placement
ShowFileDialog(opts FileDialogOptions, done func(paths []string, err error))
Accessibility() Accessibility
// title, decorations, icon, size limits, full screen, ...
}
```
| | Windows `platform/win32` | X11 `platform/x11` | Wayland `platform/wayland` | macOS `platform/cocoa` |
|---|---|---|---|---|
| Calls | Win32 through `syscall` and `x/sys/windows` | libX11 through purego | libwayland-client and libxkbcommon through purego; bindings generated by `cmd/gowaku-bindgen` | AppKit through purego/objc |
| GPU surface | D3D11 swap chain on the HWND | `VK_KHR_xlib_surface` | `VK_KHR_wayland_surface` | `CAMetalLayer` |
| IME | `WM_IME_COMPOSITION` with clauses and attributes; candidate window at the caret | XIM; commits only, the input method draws its own composition | `text-input-v3`; inline composition with a cursor range, no clause attributes | `NSTextInputClient`; clauses and the focused clause |
| HiDPI | Per-monitor v2, `WM_DPICHANGED` | `Xft.dpi` | `fractional-scale-v1` with `viewporter` | `backingScaleFactor` |
| Title bar | OS, or custom (`WM_NCCALCSIZE`, `WM_NCHITTEST`) | OS, or custom (`_MOTIF_WM_HINTS`) | `xdg-decoration`, or drawn by gowaku | OS, or transparent |
| Accessibility | UI Automation | AT-SPI2 over D-Bus | AT-SPI2 over D-Bus | NSAccessibility |
| File dialog | `IFileOpenDialog` / `IFileSaveDialog` | xdg-desktop-portal | xdg-desktop-portal | `NSOpenPanel` / `NSSavePanel` |
- On Linux, `Run` picks Wayland when `WAYLAND_DISPLAY` is set and X11 otherwise. `GOWAKU_BACKEND=x11` or `wayland` forces one. Background: [ADR 0014](ADR/0014-x11-platform.md), [ADR 0021](ADR/0021-wayland-platform.md).
- `platform/dbus` holds what both Linux platforms ask over D-Bus (with godbus, pure Go): the portal's color scheme and animation setting, the file chooser, AT-SPI2, tray and notifications. Without a session bus each feature reports that it cannot, and the reason goes to `slog.Debug`. Background: [ADR 0022](ADR/0022-linux-ime-dbus-file-dialog.md).
- The platform layer also covers menus (`NSMenu` for the macOS menu bar, drawn by gowaku elsewhere), the clipboard beyond text (images, files, HTML), drag and drop with the OS, tray icons and notifications, touch, pen and touchpad pinch, and window decorations. Background: [ADR 0046](ADR/0046-menus-and-shortcuts.md)–[ADR 0052](ADR/0052-pinch-touch-and-pen.md), [ADR 0111](ADR/0111-window-decorations.md).
- `platform/internal/*` holds code that several platforms share: key symbols, the event queue, clipboard formats, icons, desktop settings.
### Packages
```
gowaku/ Run, App, windows, Post, tray, clipboard, file dialog, Inspector
├── geom/ Offset, Size, Rect, RRect, Affine, Color, Constraints, Insets
├── input/ keys, modifiers, pointer buttons, cursors, IME compositions
├── semantics/ accessibility tree nodes, roles, actions, tree difference
├── paint/ Canvas, DisplayList, Path, Paint, Gradient, Layer, SVG, Shader
├── text/ Shaper, Layout, Style, Atlas
│ ├── jlreq/ JLReq line breaking
│ ├── hyphen/ Liang hyphenation
│ └── aozora/ Aozora Bunko ruby notation
├── core/ Widget, Element, State, RenderObject, reconcile, Tree, Ticker
├── layout/ standard render objects
├── theme/ tokens, HCT
├── motion/ controllers, curves, springs, tweens, implicit animation
├── widgets/ basic, interact, control, overlay, field, nav, collection, editor
├── render/ DisplayList → gpu.Batch
├── gpu/ Backend interface, shared shaders
│ └── d3d11/ vulkan/ metal/ soft/
├── platform/ Platform, Window, Event, NativeHandle
│ └── win32/ (com/) x11/ wayland/ cocoa/ dbus/
├── gowakutest/ run a tree in a test: find, tap, type, advance time, screenshot
├── gowakupreview/ draw Preview functions to PNG with a report
├── cmd/ gowaku-preview, gowaku-shader, gowaku-bindgen
├── markdown/ separate module: Markdown as widgets
├── internal/ goldens, test helpers, shader tools, catalog generator
└── examples/
```
The public API is `gowaku`, `gowakutest`, `gowakupreview`, `core`, `layout`, `paint`, `icons`, `text`, `theme`, `motion`, `widgets/*`, `geom` and `input`. Packages under `gpu`, `platform` and `render` are exported only so the root package can reach them; they make no compatibility promise. Background: [ADR 0016](ADR/0016-public-api.md).
### Dependency rule
Imports go down only. A package never imports a package beside it; shared code moves down a layer.
```mermaid
graph TD
root[gowaku] --> widgets[widgets/*]
root --> render
root --> platform
widgets --> motion
widgets --> theme
widgets --> layout
motion --> core
theme --> text
layout --> core
core --> text
core --> paint
core --> semantics
core --> input
text --> paint
render --> gpu
render --> paint
render --> text
gpu -->|NativeHandle only| platform
platform --> semantics
platform --> input
icons --> paint
paint --> geom
semantics --> geom
```
`geom` is at the bottom and imports only the standard library; `input` imports nothing. Arrows to `geom` from the other packages are left out.
| Package | May import |
|---|---|
| `widgets/*` | core, layout, paint, icons, text, theme, motion, input, semantics, geom, and lower widget layers |
| `motion` | core, geom |
| `theme` | text, geom |
| `layout` | core, paint, input, semantics, geom |
| `core` | paint, text, input, semantics, geom |
| `text` | paint (types only), geom |
| `icons` | paint, geom |
| `paint` | geom |
| `render` | paint, text, gpu, geom |
| `gpu` | platform (NativeHandle only), geom |
| `platform` | input, semantics, geom |
| `semantics` | geom |
| `input`, `geom` | standard library only |
| `gowaku` (root) | everything |
- `core` does not know `layout`. The standard render objects live in `layout` and implement `core.RenderObject`.
- `core`, `layout`, `paint`, `text`, `theme`, `motion` and `widgets` never import `gpu`, `platform` or `render`. That is what lets them run without a GPU.
- Within `widgets`, the order is `internal/kit` → `basic` → `interact` → `internal/behavior` → `control` → `overlay` → `field`, `nav` → `collection`, `editor`.
- `unsafe`, `syscall`, `x/sys` and purego are allowed only in `platform/win32`, `platform/x11`, `platform/wayland`, `platform/cocoa`, `gpu/d3d11`, `gpu/vulkan` and `gpu/metal`.
- `reflect` is allowed only in `core` (plus test helpers and the Inspector).
The depguard rules in `.golangci.yml` enforce all of this, and `golangci-lint run` fails on a violation. The conventions are in [CODING_STYLE.md](CODING_STYLE.md) §3 (Japanese).
### Dependencies
All pure Go: `github.com/ebitengine/purego` (C calls on Linux and macOS, and purego/objc), `golang.org/x/sys` (Win32), `github.com/go-text/typesetting` (shaping and font lookup), `golang.org/x/image` (glyph rasterization, WebP), `golang.org/x/text` (BiDi, locales), `github.com/godbus/dbus/v5` (D-Bus on Linux).
---
## gowaku design specification
[日本語](DESIGN.ja.md)
`widgets` and `theme` are built to this specification (ADR 0011). For examples, see `examples/gallery` and the [widget catalog](catalog/en/README.md). Only the continuous-curvature corners (§4) are not implemented.
---
### 1. Position
gowaku has its own default design. It has no name yet.
In one line: **a quiet desktop tool, made for Japanese text.** It borrows "subtraction" and the way materials are built from Apple's aesthetic, and its typography starts from Japanese.
#### What we borrow from Apple
| What we borrow | How it looks in gowaku |
|---|---|
| The courage not to use color | Surfaces are neutral. There is a single accent color, used only for things you can operate and for where you are now |
| Hairline rules | Separators are 1px translucent lines, not shadows |
| Inset groups | Settings and forms place rows in a rounded card, and separators stop short of the left edge |
| Two-layer shadows | A thin contact shadow plus a wide, faint shadow. Never one dark blur |
| Physical feel | Pressing sinks to 0.97, the switch knob is a white ball with a shadow, motion uses springs |
| Hierarchy through weight | Weight and ink strength create contrast before size does |
| Focus ring | The keyboard position, and only that, is shown clearly with a soft outer ring |
#### What we do not borrow
- The San Francisco (SF) font. Its license does not allow it either.
- Anything meant to look like an Apple product: traffic-light buttons, the macOS title bar, icons, Liquid Glass-style effects. The default title bar is the one of the OS (the title bar gowaku draws is opt-in, ADR 0048).
- Materials that assume blur. The default design works with opaque surfaces. Blur is available as opt-in (`BackdropFilter`, `Dialog{Glass: true}`: the background is blurred at σ 20 and a `Glass` surface is laid on top. The see-through effect is kept subtle, and text legibility comes first. ADR 0044).
#### What is gowaku's own
- **Colorless surfaces**: the base is `f5f5f7`, which looks achromatic. Never beige or cream. Those look like typical AI-generated screens.
- **Typography based on Japanese text**: sizes and line heights are chosen for the legibility of Japanese (§3).
- **Indigo accent**: the default color is a strongly blue indigo (ai). It can be replaced with any color.
---
### 2. Color
HCT is used as is. The 36 Material color roles are dropped and narrowed to about 15 colors named by use. The user picks one accent color, and the rest is derived.
```go
Theme: theme.FromAccent(geom.Hex(0x2f5fd0)) // indigo when omitted
```
| Token | Light | Dark | Use |
|---|---|---|---|
| `Canvas` | N 96.5 | N 10 | Window background |
| `Sidebar` | N 93 | N 14 | Sidebar |
| `Card` | White | N 15 | Groups, cards |
| `Raised` | White | N 20 | Dialogs, menus |
| `Glass` | White 85% | N 20 at 78% | Glass dialog (`Dialog{Glass: true}`). Ink2 reaches 4.5:1 on top of any surface under the scrim (ADR 0044) |
| `Field` | White | N 19 | Input fields |
| `Control` | White | White 14% | Normal buttons |
| `Ink` | N 13 | N 95 | Body text |
| `Ink2` | N 42 | N 72 | Secondary text. At least 4.5:1 on every surface (ADR 0041) |
| `Ink3` | N 62 | N 50 | Placeholders, disabled, decoration. Deliberately below 4.5:1, so do not use it for text that carries information such as times or counts; use `Ink2` |
| `Hair` | Black 9% | White 10% | Lines |
| `Fill` | Black 5% | White 8% | Subtle fills, segment background |
| `FillStrong` | Black 9% | White 14% | Switch when off, tracks |
| `Accent` | A 45 | A 45 | Fills. White text sits on top, at 4.5:1 also under hover (ADR 0123) |
| `AccentInk` | A 41 | A 74 | Text, lines, focus ring |
| `AccentTint` | A 45 at 12% | A 62 at 22% | Selected row. `Ink` reads on it; `Ink2`, `AccentInk`, `Danger` and `Success` fall below 4.5:1 there, so what sits on it takes the colors of `Colors.OnTint`, which mixes each toward `Ink` by the least that reads (ADR 0138) |
| `Danger` | Red 41 | Red 72 | Destructive actions, errors |
| `Success` | Green 41 | Green 72 | Positive states, such as something finished or a break in progress |
| `Warning` | Amber 70 | Amber 76 | What needs attention before it goes wrong, such as the icon and border of `SeverityWarning` of `InfoBar`. For icons, dots, borders and tints, not for text (ADR 0124) |
N is the neutral palette (hue 235, chroma 3.5). Red, green and amber are hues 25, 145 and 60. A is a palette with the accent's hue and chroma max(seed, 40). The numbers are tones.
#### Why these colors
- **The neutral chroma must not go near 0.** HCT's achromatic point is around hue 209, chroma 2.8. Setting chroma to 0.8 actually shifts toward pink.
- **The base color was chosen by drawing four candidates side by side.** The warm `f6f5f4` looked beige and was rejected. Pure gray `f5f5f5` looks slightly muddy next to a white card, and going as blue as `f4f5f9` looks like a SaaS admin panel. Hue 265 leans purple. `f5f5f7` gives no sense of color.
- **One accent color is not enough.** In dark mode, a color bright enough to read as text makes white text unreadable when used as a fill. So there is one for fills and one for text.
- Changing the seed to green or orange does not break anything. Surfaces are neutral, so the seed only affects controls.
---
### 3. Text
The default body size is 13px. Yu Gothic on Windows is thin at 400, so labels use 500. Line heights are set in pixels, and all of them are even, so elements stacked below stay on the grid.
| Role | Size | Weight | Line height |
|---|---|---|---|
| `LargeTitle` | 24 | 600 | 32 |
| `Title` | 16 | 600 | 24 |
| `Headline` | 13 | 600 | 20 |
| `Body` | 13 | 400 | 20 |
| `Control` | 13 | 500 | 20 |
| `Caption` | 12 | 400 | 18 |
| `Section` | 12 | 500 | 18 |
| `Reading` | 15 | 400 | 26 |
| `Code` | 13 | 400 | 20 |
Line heights are fixed values based on Japanese text. Text sizes are limited to 9 roles.
`Code` is the only role with a family of its own: a monospaced font for source code, logs and values to copy, the default of `editor.Editor` and of code in markdown. Its family is a list that every OS reads in order, taking the first it has: Cascadia Mono and Consolas on Windows, SF Mono and Menlo on macOS, DejaVu Sans Mono, Noto Sans Mono and Liberation Mono on Linux (`theme.MonoFamilies`). Japanese inside code falls through to the Japanese families.
---
### 4. Shape and dimensions
The scale uses even numbers only. Even numbers become whole physical pixels at 100%, 150% and 200%. The values are `theme.Space2` to `theme.Space28`; do not write raw numbers in code.
| | Value |
|---|---|
| Corner radius | Small 4 (checkbox) / standard 8 (buttons, input fields, rows) / large 12 (groups) / extra large 16 (dialogs) |
| Control height | Small 24 / **standard 30** (buttons, input fields, segments, sidebar rows) / large 38 |
| Group row height | 44 or more |
| Sidebar row with a `Detail` | 46: the two lines (20 and 18) and 4 above and below |
| Spacing | 2, 4, 6, 8, 10, 12, 16, 20, 24, 28 |
| Which spacing where | Page 28, between sections 24, left and right inside a card 16, between controls 8, heading to body 6 |
| Sidebar width | 208, hairline included (`Sidebar.Width`) |
#### Snapping to physical pixels
`render` aligns rounded rectangles to physical pixels. The same length becomes the same physical length wherever it is, so line widths stay even. Anything under 2 physical pixels is rounded down (1px at 150% is 1 physical pixel).
Not snapped: shapes being scaled (they must move by less than a pixel) and circles (so a knob does not move in steps). Only the border width stays even during scaling.
**Continuous-curvature corners** (the key to Apple's rounded corners) are not implemented. The current SDF uses circular arcs, and at a radius of about 8 the difference is small. We expect that changing the corners of `roundedBoxDistance` in the shader to a p-norm would work without changing the `Instance` format, but this is not verified. It will be tried in a later step.
---
### 5. Components
**Buttons** come in 3 levels plus a destructive one, 4 kinds in all. They are one type, `Button{Label, Style}`, and the zero value is a normal button.
| `Style` | Look | When to use |
|---|---|---|
| `ButtonNormal` (zero value) | White background + line + contact shadow | Default |
| `ButtonPrimary` | Accent fill | Only one per screen |
| `ButtonQuiet` | No background, accent text | Secondary actions |
| `ButtonDanger` | No background, red text | Delete |
Buttons without a background use 8 for left and right padding. With 16, the gap to the neighbor looks too wide.
**Input fields**: the label goes above (`field.Input.Label`) or to the left of the row (`GroupRow`). No floating labels. On focus the line turns accent and a faint 3px ring appears outside. `layout.RenderRing` draws the ring as a line, so it does not affect the fill inside.
**Switch**: 38×22, a white knob of 18 with a two-layer shadow. Pressing stretches the knob sideways. **Slider**: track 4, white knob 18, grows slightly when the pointer is over it. **Checkbox**: 16, corner radius 4.5.
**New components**
- `SegmentedControl`: 2 to 4 choices, such as switching appearance. The selected plate slides on a spring.
- `Group` and `GroupRow`: an inset list. Name on the left, control on the right.
- `Sidebar` and `SidebarItem`: selection is an `AccentTint` surface, and the chosen row sets its content in the colors of `Colors.OnTint`. A `Detail` is a second line in `Caption` and `Ink2`, cut to one line.
- `Steps`: where a flow of steps is. Circles of 24 and names, joined by lines 2 thick. Done steps and the current one have `Accent` circles, the steps ahead `Fill` circles and `Ink2` names, and only the name of the current step is bold.
**Dialog**: width 340, padding 24, corner radius 16, `Raised`, left-aligned, two-layer shadow. The scrim is black 25%. With `Glass: true`, the surface becomes `Glass` and what is behind is blurred at σ 20.
#### States are the same for every component
| State | How it shows |
|---|---|
| hover | Background or line changes in 80ms. All of Switch, Checkbox, Segmented, Sidebar, Slider, Input, Button |
| press | Sinks, stretches or darkens on a spring. All except Input |
| focus | A faint 3px ring. Custom components built with `Pressable` show the same ring when `PressState.Focused` is set |
| disabled | Drawn with the `Fill` and `Ink3` tokens. The whole component is not made translucent |
The `widgets` tests (`TestHover_MovesEveryControl`, `TestPress_MovesEveryControl`, `TestDisabled_UsesTokensNotOpacity`, `TestControls_ShareOneHeight`, `TestStacking_StaysOnTheGrid`) keep these promises.
---
### 6. Shadows
Light comes from directly above. Two layers: a contact shadow and a wide shadow.
| Level | Near shadow | Far shadow | Use |
|---|---|---|---|
| 1 | y 0.5 / blur 1 / 5% | None | Normal button |
| 2 | y 0.5 / blur 1 / 8% | y 1 / blur 2–3 / 16% | Segment plate, switch knob |
| 3 | y 2 / blur 4 / 8% | y 24 / blur 48 / 16% | Dialog |
In dark mode shadows show less, so steps are made with surface brightness (`Card` → `Raised`) plus a line.
---
### 7. Motion
Instead of ripples, gowaku's signature is **physical feel made with springs**. `motion.SpringSimulation` already exists, so almost no new machinery is needed.
| Motion | Value |
|---|---|
| hover | 80ms. Linear |
| Press | **Only the background** sinks to 0.97 and the fill changes. Spring (fast, no bounce) |
| Release | Returns on the same spring. Velocity carries over, so rapid presses do not jump |
| Switch, segment | Spring (slight bounce) |
| Dialog | 0.96 → 1 plus fade. 280ms `motion.SpringOut`. Closing is quick, 120ms |
| Color change | 150ms |
The press motion is applied only to the background, with `Decoration.Sink`. Shrinking the text too could make glyphs jump near 0.97 because of glyph pixel-size quantization. The text stays in place.
---
### 8. Effect on the API
- "Good-looking with no effort" means **it looks right when you specify nothing**. `Button{Label: "保存"}` ("Save") alone gives a finished look.
- `theme` has `Colors`, an 8-role `TextTheme`, `Radii` and `Lift`. It has HCT, `TonalPalette`, `Set`, `ThemeMode` and following the OS setting.
- There is one button, `Button`, and one input field, `field.Input`.
---
## Benchmark results: gowaku, Gio, Cogent Core
We wrote the same scenarios (startup, idle, scrolling 10,000 rows, 100 simultaneous animations, resizing) in three libraries and measured them the same way from outside the process. The code and the steps are in [examples/bench](../examples/bench/README.md).
Items where gowaku lost are shown as they are.
[日本語](BENCH.ja.md)
### Windows
Measured on 2026-11-10. Raw data: [results/windows-2026-11-10.json](../examples/bench/results/windows-2026-11-10.json).
#### Environment
| Item | Value |
|---|---|
| PC | Windows 11, i7-12700H, Iris Xe + RTX 3050 Ti, 1920×1200 / 60Hz, scale 150% |
| Go | 1.27.3 |
| Compared with | Gio v0.10.3, Cogent Core v0.5.27 |
| Runs | Median of 3 runs. Startup only: median of 15 runs |
There is no three-way comparison on Linux. The Linux test environment has no real GPU, and comparing libraries on a software Vulkan driver means nothing. Reference values for gowaku alone are given below instead.
#### Results
Bold marks the best value in the row. No bold when the difference is within measurement noise.
| Item | gowaku | Gio | Cogent Core |
|---|---:|---:|---:|
| **Startup** (ms) | **89** | 144 | 1217 |
| **Binary** hello (MB, `-s -w`) | 7.7 | 6.4 | 32.4 |
| cgo | Not needed | Not needed | **Needed** |
| **Idle** CPU (%) | 0.00 | 0.03 | 2.40 |
| Idle GPU (%) | 0.00 | 0.00 | 1.26 |
| Idle package power (W) | **3.2** | 3.5 | 3.9 |
| **10,000-row scroll** fps | 60.0 | 60.0 | 53.9 |
| Scroll CPU (%) | **9.1** | 12.7 | 28.7 |
| Scroll GPU (%) | 3.1 | 3.1 | 10.8 |
| Scroll frame interval p99 (ms) | 18.2 | 18.3 | 18.2 |
| **100 simultaneous animations** fps | 59.0 | 60.1 | 31.9 |
| Animation CPU (%) | **7.8** | 44.4 | 69.4 |
| Animation GPU (%) | 8.0 | 10.0 | 7.1 |
| Animation frame interval p99 (ms) | 33.3 | **18.0** | 50.6 |
| **Resize** sizes received / s | 50 | 60 | 96 |
| Resize frames drawn / s | 55 | **120** | 6 |
| Resize CPU (%) | **11.2** | 18.7 | 44.1 |
| Resize GPU (%) | 3.6 | 6.9 | **1.7** |
| **Peak memory** scroll (MB) | 240 | **159** | 434 |
| Peak memory resize (MB) | 256 | **176** | 497 |
- CPU: 100% is one full core. fps is capped by the 60Hz display, so the differences show up in CPU.
- For startup, only the first of the 15 runs is cold and slow. It does not affect the median.
- **Animation frame interval p99 is 33ms**: in 8 seconds, 2 to 6 frames take two frame periods. The cause is not known.
- **Power** is for the whole machine. Read it as a ratio between the three libraries within the same round.
#### How to read it
**Where gowaku won**
- CPU for 100 simultaneous animations is about 1/6 of Gio and about 1/9 of Cogent Core. Note that Gio has no shadow blur; it uses translucent rounded rectangles instead.
- CPU for the 10,000-row scroll is about 70% of Gio and about 1/3 of Cogent Core.
- CPU for resizing is about 60% of Gio.
- The app code only writes target values. It does not compute anything per frame.
**Where gowaku lost** (background in [ADR 0015](ADR/0015-bench-results.md))
- Memory is higher than Gio in every item. Parsing the Japanese font keeps about 40MB of heap.
- Fewer sizes are received during resize than Gio (50 vs 60). Gio draws two frames per size; gowaku draws one. The cause is not known.
**No difference**
- Idle and scroll GPU are the same as Gio. Startup is faster than Gio, and the binary is 1.3MB larger. Cogent Core keeps using CPU and GPU even when idle.
### Large files
`examples/bigfile -report` opens a log and prints how long it took, on the same Windows machine (16 GB of memory). The editor reads only the lines in view, from a source that indexes the file on a goroutine of its own and keeps one entry for every 64 lines ([ADR 0157](ADR/0157-editor-line-source.md)). "The first lines" is the first frame after the window opened with the file, measured from the start of `gowaku.Run`; memory is the Go heap after a collection, including the 43 MB that the window holds without a file.
| | 1 GB, 12.6 million lines | 10 GB, 125 million lines |
|---|---:|---:|
| Start to the first lines | 76 to 82 ms | 80 to 84 ms |
| Every line indexed, in the background | 0.41 to 0.42 s | 9.1 to 9.8 s |
| Memory | 51 MB | 84 MB |
- The 1 GB file was in the cache of the OS; the 10 GB one did not fit there, so its indexing reads the disk, at about 1.1 GB/s. The first lines do not wait for it.
- The first run after writing the 10 GB file showed its first lines after 678 ms, while the system was still writing the file out.
- Scrolling and searching do not wait for the indexing either: the lines known so far scroll, and a search runs on its own goroutine and goes on into the lines as they come ([ADR 0154](ADR/0154-editor-background-find.md)).
### Linux (WSL) reference values
Measured on 2026-11-10. Only gowaku was measured.
**These are not GPU numbers.** gowaku runs on headless sway (Wayland, pixman) in WSL, with Vulkan on lavapipe, Mesa's CPU driver. Drawing happens on the CPU, so CPU usage is several times higher than on a real GPU. Only trends are meaningful: idle goes to 0, layers help, startup time, binary size.
Steps: [results/wsl-2026-11-10.md](../examples/bench/results/wsl-2026-11-10.md).
| Scenario | Result |
|---|---|
| Startup (from launch until after the first frame, median of 7 runs; the first run was 204ms) | 165ms |
| Binary (examples/hello, `-s -w`, linux/amd64) | 9.4MB |
| animate (100 boxes) | 59fps, CPU 191% |
| dense (with layers) | 59fps, CPU 102% |
| dense-flat (without layers) | 59fps, CPU 284% |
| idle | CPU 0.0%, 0 frames |
- scroll and resize were not measured. The harness that drives the wheel and the window size from outside exists only on Windows.
- Frames are capped by sway's headless output (60Hz).
- The gap between dense and dense-flat (CPU 102% vs 284%) points the same way as the layer effect seen on Windows and macOS.
### macOS
Measured on 2026-11-10. The same three programs were measured with the macOS harness (`harness/main_darwin.go`). Raw data: [results/macos-2026-11-10.json](../examples/bench/results/macos-2026-11-10.json). Steps: [examples/bench](../examples/bench/README.md#macos).
Neither root nor the Accessibility permission was used. Because of that, what can be measured and how the programs are driven differ from Windows, and the Windows table cannot be compared number by number. The differences are listed under "What we could not measure" and "Differences from Windows" below.
#### Environment
| Item | Value |
|---|---|
| PC | Mac (Apple M5, 10-core GPU, 24GB memory), built-in Liquid Retina 2560×1664 / 60Hz, scale 2 |
| OS | macOS 27.0.1 |
| Go | 1.27.3 (darwin/arm64) |
| Build | gowaku with `CGO_ENABLED=0`. Gio and Cogent Core with `CGO_ENABLED=1` (Apple clang 21). All with `-s -w` |
| Compared with | Gio v0.10.3 (Metal), Cogent Core v0.5.27 (Metal through WebGPU) |
| Window | 800×700 points (1600×1400 pixels) for all three. Position is each library's default |
| Runs | Median of 3 runs. Startup only: median of 15 runs. Under `caffeinate -d -i` |
Other resident processes (`mediaanalysisd`, an antivirus extension, and so on) were running during the measurement. Load average was 2 to 3.
#### Results
Bold marks the best value in the row. No bold when the difference is within measurement noise.
| Item | gowaku | Gio | Cogent Core |
|---|---:|---:|---:|
| **Startup** (ms) | 145 | 151 | 355 |
| **Binary** hello (MiB, `-s -w`) | 7.5 | **5.9** | 24.4 |
| cgo | **Not needed** | Needed | Needed |
| **Idle** CPU (%) | 0.00 | 0.00 | 2.21 |
| Idle GPU time (%) | 0.00 | 0.00 | 0.26 |
| Idle frame count (60 s) | 0 | 0 | 0 |
| **10,000-row scroll** fps | 60.0 | 60.0 | 57.6 |
| Scroll CPU (%) | **11.2** | 17.8 | 42.8 |
| Scroll GPU time (%) | 10.8 | **7.9** | 9.6 |
| Scroll frame interval p99 (ms) | 17.5 | 17.7 | 33.4 |
| **100 simultaneous animations** fps | 59.0 | 60.0 | 33.2 |
| Animation CPU (%) | **9.0** | 32.4 | 82.4 |
| Animation GPU time (%) | 19.9 | 27.7 | **4.1** |
| Animation frame interval p99 (ms) | 33.2 | **18.7** | 66.8 |
| Estimated process CPU power: scroll (mW) | **15** | 25 | 859 |
| Estimated process CPU power: animation (mW) | **13** | 88 | 5462 |
| **Peak memory** (resident) idle (MB) | 173 | **160** | 202 |
| Peak memory (resident) scroll (MB) | 175 | **169** | 272 |
| Peak footprint idle (MB) | 263 | **178** | 242 |
| Peak footprint scroll (MB) | 287 | **207** | 316 |
| Peak footprint animation (MB) | **234** | 414 | 281 |
- CPU: 100% is one full core. fps is capped by the 60Hz display.
- **GPU time** is the increase in `accumulatedGPUTime`, which the GPU driver counts per process, divided by wall-clock time. Its definition differs from the Windows "3D engine utilization". The value changes with GPU frequency, so read it as a ratio between the three libraries.
- **Estimated process CPU power** is the estimated energy the kernel assigns to CPU time (`ri_energy_nj`). It includes neither the GPU nor the rest of the machine. It varies a lot with core type (P / E) and frequency, so it does not match the CPU% ratio (Cogent Core uses 9 times the CPU and 400 times the power).
- **Peak memory (resident)** is `ru_maxrss`, the counterpart of the Windows peak working set. **Peak footprint** is the maximum of the "Memory" column in Activity Monitor. It includes GPU memory the process holds, such as Metal buffers.
- **Binary** is the size of `examples/hello`, `hello/gio` and `hello/cogent` built for darwin/arm64 (in units of 2^20 bytes).
- Startup ranges were 130 to 201ms for gowaku and 139 to 179ms for Gio. Read them as about the same.
#### gowaku layers (`dense`)
| Scenario | fps | CPU (%) | GPU time (%) |
|---|---:|---:|---:|
| `dense` (with boundary) | 59.0 | **7.1** | 13.8 |
| `dense-flat` (without boundary) | 58.9 | 16.4 | 16.6 |
The effect points the same way as on WSL (284% → 102%).
#### How to read it
**Where gowaku won**
- Scroll CPU is about 60% of Gio and about 1/4 of Cogent Core.
- Animation CPU is about 1/4 of Gio and about 1/9 of Cogent Core. GPU time is also lower than Gio (Gio stacks four rounded rectangles in place of a shadow blur).
- gowaku is the only one that needs no cgo. On macOS, Gio needs cgo too.
- Idle is 0, the same as Gio. Cogent Core keeps using 2% CPU and some GPU while doing nothing.
**Where gowaku lost**
- **Memory is higher than Gio.** 5 to 15MB more resident memory; 85MB more footprint at idle and 80MB more while scrolling. The idle footprint is even higher than Cogent Core (242MB). Only during animation is it lower than Gio (414MB).
- **Scroll GPU time is higher than Gio** (10.8% vs 7.9%).
- **Animation frame interval p99 is 33ms.** In 10 seconds, 0 to 4 frames take two frame periods. Same symptom as on Windows, and the same with `dense`. The cause is not known.
- **The binary is 1.6MiB larger than Gio.**
**No difference**
- Startup is the same as Gio. Cogent Core is faster than on Windows (1.2 s) but still takes more than twice as long.
#### What we could not measure
| Item | Reason |
|---|---|
| Resize | Resizing another process's window needs the Accessibility permission. Having each program resize itself would be a different path from the Windows "`SetWindowPos` from outside", so we did not build it |
| GPU utilization (same definition as Windows) | `powermetrics` needs root. GPU time is shown instead |
| Whole-machine power | Also `powermetrics` (root). Estimated process CPU power is shown instead |
| 4K | The built-in display is 2560×1664. No external display |
| 120Hz | The display is 60Hz |
#### Differences from Windows
- **Scroll input.** macOS does not allow sending input from outside (it needs the Accessibility permission). So gowaku, like Gio, places the list itself every frame at `ScrollSpeed` × elapsed time (`-autoscroll`, `ListController.JumpToIndex`). On Windows gowaku glides with wheel inertia, so what it draws is slightly different. Cogent Core scrolls by row in both cases.
- **The window is not brought to the front.** The harness cannot change window stacking. Each program comes to the front when it starts.
- **Each program decides its window size.** gowaku and Gio open at 800×700 points by default. Cogent Core opens at 60% or more of the screen to fit its content, so on macOS only it resizes itself to 800×700 after the first frame.
- **The mouse is not moved away from the window.** The Windows harness moves the window to the corner far from the mouse; on macOS it cannot. The mouse position is not controlled (the idle frame count is 0, so no hover happened).
#### What happened during measurement
- The first attempt (3 rounds) was discarded. In its first round, during a period when the display was probably asleep, Gio and Cogent Core each failed to start 5 times (no first frame), and in the same period gowaku drew `scroll` and `animate` at 112 to 120fps. The display is 60Hz, so gowaku was drawing without display sync during that time. Metal hands out drawables without waiting for vsync when the window is not visible. We fixed it by not drawing invisible windows, the same as minimized ones (ADR 0083 §6). From the second attempt on, we measured under `caffeinate -d -i`.
- Even in the round we kept, Cogent Core's first `animate` run was 5fps at 18% CPU (it does not affect the median).
### Gap to the goals
| Goal | Result |
|---|---|
| CPU does not rise when resizing at 4K | **Not confirmed.** 3840×2160 was not measured (on this PC the window tops out at 1924×1170). At that size it uses 11.2% |
| 120fps with 10,000 rows | Capped because the display is 60Hz. `examples/listview -bench` without vsync reaches 1800fps (Iris Xe, 800×900) |
| 0% at idle | Achieved (Windows, macOS, WSL). Resize was not measured on macOS, so the 4K item has Windows values only |
### What we could not align
Scroll input, Gio's shadows, how Cogent Core frames are counted, and GPU selection differ slightly between the three. Details in [examples/bench](../examples/bench/README.md#what-we-could-not-align).
Power is for the whole machine and varied from 10 to 18W under the same conditions. It cannot be used for comparison, so it was removed from the table. It is kept in the raw data.
---
## Roadmap
[日本語](ROADMAP.ja.md)
What gowaku does not do yet, where it is known to fall short, and what it will not do. There are no dates here. How the library is built is in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
### Not verified yet
- **Linux desktops.** gowaku has run on X11 (XWayland, Xvfb) and on Wayland (Weston under WSLg, a headless sway), with a software Vulkan driver. It has not been run on a real Ubuntu desktop with a real GPU, nor on GNOME or KDE.
- **Linux input methods.** On Wayland, composition shows inline through `text-input-v3`. This was checked with fcitx5 and Mozc on sway; ibus on GNOME only partly.
- **macOS.** VoiceOver, drag and drop with Finder, the IME, transparent windows and the effects of drawing groups are tested by code, not yet by hand.
- **Window decorations.** The Wayland window icon (`xdg-toplevel-icon-v1`) has not been tried on a compositor that has it. On X11, transparency and always-on-top have not been checked under a window manager that implements all of EWMH.
### Known limits
- **IME under X11** takes only committed text through XIM. The input method draws its own composition window.
- **IME clauses on Wayland.** `text-input-v3` carries no clause attributes, so the focused clause is not highlighted there as it is on Windows and macOS.
- **macOS** runs on Apple Silicon only. Intel Macs return `ErrUnsupported`. Notifications need the application inside an .app bundle.
- **OS settings.** gowaku follows the OS for light and dark, reduced motion and locale. It does not yet follow high contrast, the OS accent color or the OS text scale.
- **Drawing groups.** Inside a group that needs multisampling (one that contains paths), blend modes that read the backdrop fall back to source-over, and backdrop blur is not drawn. Groups larger than 2048 pixels are drawn at lower resolution. Filters under rotation or skew are approximated.
- **Window features not covered:** click-through on transparent areas, the AppUserModelID on Windows, and always-on-top on Wayland, which has no standard protocol for it.
- **Markdown** does not fetch images from the network (an application can supply them), does not show SVG or animated GIF images, and does not scroll wide tables sideways.
- **File dialog on Linux** needs xdg-desktop-portal. Without it, `ShowFileDialog` reports `ErrNoFileDialog`.
### Planned, not built
- **Packaging helper.** A small helper that sets the application icon and metadata for each OS. It does not exist yet.
### Out of scope
These are deliberate, not gaps.
- **Web (WASM) and mobile.** gowaku is for desktops. A WebGPU backend would fit behind `gpu.Backend`, but the platform side (DOM events, IME) is a different thing.
- **3D.** gowaku is a 2D UI library. A custom shader can draw small 3D effects.
- **Mirroring layouts for right-to-left languages.** BiDi text works. Flipping rows and icons would touch every widget.
- **Printing and PDF output.**
- **Hot reload.** Not practical in Go. Use previews (`cmd/gowaku-preview`) and the Inspector instead.
- **Video playback.** The codecs are not available without cgo.
- **Plugins and dynamic loading.** Go's `plugin` package needs cgo.
- **A file dialog widget of its own.** The OS dialog is used everywhere.
- **Charts with axes and legends.** `Sparkline` draws small lines and bars, no more.
- **Ready-made themes besides the default.** `theme.FromAccent` and `theme.Extension` are the ways to adapt it.
- **Installers, code signing and auto-update.** Distribution is left to the application.
---
## Contributing to gowaku
[日本語](CONTRIBUTING.ja.md)
Thank you for helping. Bug reports, small fixes and documentation are all welcome. For a new widget or a change to the public API, open an issue first so that the design can be agreed before the code is written.
### Before you write code
Read these two:
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): the layers and how a frame is made.
- [docs/CODING_STYLE.md](docs/CODING_STYLE.md): the rules of the code.
The rules that matter most:
- **Dependencies point down only.** `core` does not import `layout`, `gpu` or `platform`. The `depguard` linter in `.golangci.yml` enforces the layers.
- **`unsafe`, `syscall` and `purego` stay inside** `platform/win32`, `platform/x11`, `platform/wayland`, `platform/cocoa`, `gpu/d3d11`, `gpu/vulkan` and `gpu/metal`.
- **The hot paths do not allocate.** Reconcile, Layout, Paint and batching must stay at 0 allocs/op in their benchmarks.
- **Widgets are value types that work at their zero value.** No functional options, no method chains.
- **Errors and panics.** A failure to initialize returns an `error`. A broken contract while running panics with a message that starts with `gowaku: `. The library never calls `recover`.
- **No GPU needed for most tests.** `core`, `layout`, `paint`, `text`, `theme` and `motion` pass `go test ./...` without a GPU. Tests that need one carry `//go:build gpu`.
### Commands
Check and test, as CI does:
```bash
gofmt -s -l . && go vet ./... && golangci-lint run
```
```bash
GOOS=linux golangci-lint run && GOOS=darwin golangci-lint run
```
```bash
go test -race ./...
```
```bash
GOOS=linux CGO_ENABLED=0 go build ./...
```
Tests that need a GPU or a window system run on your machine only:
| Command | Where |
|---|---|
| `go test -tags gpu ./gpu/...` | Windows (D3D11 and Vulkan are compared) |
| `go test -tags gpu ./internal/golden` | Windows: D3D11 and Vulkan against the same pixel goldens |
| `go test -tags gpu ./platform/x11/` | Linux, under an X server |
| `go test -tags gpu ./platform/wayland/` | Linux, under a Wayland compositor |
| `go test -tags gpu ./gpu/metal/ ./platform/cocoa/` | macOS on Apple Silicon |
Without a Linux desktop, [scripts/wsl](scripts/wsl) runs the Linux GPU tests in WSL with a headless sway and Mesa's software Vulkan driver. Start with `getdebs.sh`, then `sway.sh`, then `gputests.sh`; each script explains itself at the top.
Generated files:
```bash
go test ./internal/golden -update # remake the pixel goldens; look at the PNG diff before committing
go run ./internal/cmd/catalog # remake the widget catalog (pictures and pages)
go generate ./gpu/... # remake the shaders
go generate ./platform/wayland/ # remake the Wayland bindings
```
`go test ./internal/catalog/` fails when the catalog is out of date. A new public widget needs an entry in `internal/catalog/registry.go` and a scene function; see [docs/catalog/README.md](docs/catalog/README.md).
### The markdown module
[markdown/](markdown) is a module of its own too. Its go.mod has `replace github.com/bankai-tensei/gowaku => ../` for work in this checkout, but a module that depends on markdown ignores that line and fetches the gowaku that markdown requires. So the require must name a version that exists and has every API markdown uses: when markdown starts to use something new from gowaku, push gowaku first, then set the require to that commit with `go get github.com/bankai-tensei/gowaku@` in `markdown/`. A release tags both, as `vX.Y.Z` and `markdown/vX.Y.Z`, with the require of markdown at `vX.Y.Z`.
### The website
[website/](website) builds the site at https://bankai-tensei.github.io/gowaku/ from the Markdown of the repository and `docs/catalog/catalog.json`. It is a module of its own, so its libraries stay out of the go.mod of gowaku. To see your changes:
```bash
cd website && go run . -serve :7901
```
The page rebuilds on every reload. A merge into main publishes it through `.github/workflows/pages.yml`. The words of the landing page are in `website/words.go`, in English and Japanese.
### Benchmarks
When you change a hot path, run the benchmarks of the package before and after, on a quiet machine, and put both numbers in the pull request:
```bash
go test -bench . -benchmem -run '^$' ./core/ ./text/ ./render/
```
### Documentation
- Doc comments are in English. Every exported identifier has one.
- User documentation is in English and Japanese: `X.md` is English and `X.ja.md` is Japanese (the guides use `docs/guide/en` and `docs/guide/ja`). Change both when you can; if you can write only one, say so in the pull request and we will translate it.
- A design decision gets an ADR in `docs/ADR/NNNN-slug.md`: background, options, decision, consequences. ADRs are written in Japanese; an English summary in the pull request is fine and we will help.
### Commits and pull requests
- Commit messages follow the Go project: `package: lowercase summary`, for example `layout: fix the baseline of a wrapped row`. Several packages: `core, layout: ...`. Everything: `all: ...`.
- One commit, one intent. Formatting-only changes go in their own commit.
- A pull request that changes what you see includes a screenshot, light and dark when it matters.
- CI must pass.
### Reporting bugs
Open an issue with the OS and its version, the GPU, the Go version, the smallest program that shows the bug, and what you expected. For text and IME bugs, add the input method and the text. For security problems, see [SECURITY.md](SECURITY.md).
By contributing, you agree that your contributions are licensed under the [MIT License](LICENSE).
---
## Changelog
All notable changes to gowaku are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/). Before v1.0, a minor version may change the public API; each such change is listed under **Changed** or **Removed**.
### [Unreleased]
### [0.3.0] - 2026-11-25
#### Added
- `App.OnQuitRequest`, which answers when the OS asks the whole application to quit, which only macOS does (Cmd+Q, Quit in the Dock, logging out): true quits as `Quit` does, false keeps running. Without it every window gets a close request, as before.
- `WindowHandle.Hide`, `Show` and `Hidden`, which take a window off the screen and the task bar without closing it, so that an application can stay in the tray: hide the window in `OnCloseRequest`, return false, and show it from the tray. A click on the Dock icon shows hidden windows again on macOS. Wayland cannot hide a window, and minimizes it instead.
- `gowaku.RequestNotifications(ctx, done)`, which asks for leave to show notifications (the user, on macOS) and calls `done` on the UI goroutine with nil or `ErrNoNotifications`.
- `core.NewTreeWithHost`, which connects a tree to its host before the first build.
- `gowakutest.Tester.SetNotificationsAllowed`, which decides the answer of `RequestNotifications` and whether `Notify` succeeds.
- `platform`: `Trays.RequestNotifications`, `Window.SetVisible`, and the events `EventQuit` and `EventReopen`.
#### Fixed
- macOS: `Notify` sent the notification without waiting for the user to allow notifications, so that the first one could be lost while macOS asked, and it returned nil although the user had refused. Notifications sent before the answer now wait for it, and once the user has refused `Notify` returns `ErrNoNotifications`.
- macOS: notifications did not show while the application was in front. They now show as a banner, in the list and with sound, as on Windows and Linux.
- `ShowTray`, `Notify` and the clipboard functions called from an `InitState` of the first build of a window, or of a `gowakutest.Tester`, found no host and failed, with `ErrNoTray` for `ShowTray`, although its documentation allows `InitState`. The tree now has its host before it is first built.
### [0.2.1] - 2026-11-24
#### Fixed
- Linux: with Num Lock on, a key of the numeric keypad sent the navigation key it carries without Num Lock as well as its digit, so that `124` typed on the keypad into a text field became `142`. On Wayland and X11 the keypad keys now follow Num Lock and Shift: with Num Lock on they send `Key0` to `Key9` and `KeyPeriod`.
### [0.2.0] - 2026-11-21
#### Changed
- `gowaku.FileDialog`, `FileFilter`, `ClipboardContent` and `ClipboardKinds` no longer come from `platform`, which promises no compatibility: they are defined in `core` and named in gowaku, as `Widget` and `BuildContext` are. They have the same fields, so code that uses them through gowaku still builds; code that passed them to or from `platform` must convert. `gowaku.ThemeMode` is likewise `theme.Mode`, with `ThemeSystem`, `ThemeLight` and `ThemeDark` as before.
- `gowaku.ShowFileDialog`, `SetTheme` and `CurrentTheme` take a `BuildContext` first, as `ShowTray` and the clipboard functions do: `ShowFileDialog(ctx, d, done)`, `SetTheme(ctx, set, mode)`, `CurrentTheme(ctx)`. They go through the window of `ctx`, so they work under a `gowakutest.Tester`, and the file dialog opens in front of that window instead of the focused one, or of another open window once that one has closed. Code with no context of its own, as a callback of `Post`, keeps the `BuildContext` of a widget, or uses `WindowHandle.ShowFileDialog`. Outside a window they no longer panic: `ShowFileDialog` calls `done` with `ErrNoFileDialog`, `SetTheme` does nothing, and `CurrentTheme` returns the zero `theme.Set`, which stands for `theme.Default()`, and `ThemeSystem`.
- `gowakutest.Tester.ClipboardContent` and `SetClipboardContent` take a `core.ClipboardContent`, which is `gowaku.ClipboardContent`.
- `ClipboardContent.Kinds` has a value receiver, so that `gowaku.ReadClipboard(ctx, k).Kinds()` builds.
- `field.Input` takes `OnFocus func(focused bool)` as a field of its own, and `field.Extras` and `Input.Extras` are gone. Replace `Extras: field.Extras{OnFocus: f}` with `OnFocus: f`.
- `overlay.Dialog.OnDismissRequest` and `overlay.Sheet.OnDismissRequest` are now `func() bool`, as `OnCloseRequest` of a window is: Escape or a click beside the dialog or sheet closes it when the function returns true and leaves it open when it returns false. A function that kept the dialog open and called `dismiss` itself to close it should now `return false`; one that only looked on can `return true` and need not call `dismiss`.
- `overlay.ShowDialog` and `overlay.ShowSheet` return `dismiss func()`, as `overlay.ShowToast` does: the same function that `build` gets, which does nothing once the dialog or sheet is closing or gone. Code that called them as a statement compiles as before; code that saved the `dismiss` of `build` in a variable only to close the dialog from outside can take the return value instead.
#### Added
- `core.FileDialogHost`, which a host implements to show file dialogs.
- `theme.Mode`, with `ModeSystem`, `ModeLight`, `ModeDark` and `Mode.For`, which `gowaku.ThemeMode` names.
- `gowakutest`: file dialogs that the test answers, through `Tester.FileDialogs`, `Tester.FileDialog` and `FileDialog.Options`, `Choose`, `Cancel` and `Fail`; `gowaku.SetTheme` changes the theme of the Tester's tree, and `ThemeSystem` follows `Options.Dark`.
### [0.1.2] - 2026-11-20
#### Fixed
- Ruby: a group ruby drew its whole base with the font and orientation of its first character, so that in `AI時代` the kanji took a Latin font, or a kanji from a fallback font became tofu, and in vertical text the kanji turned with the Latin letters. The base now keeps the look of each character. Line breaking and the space between Japanese and Western text after the group follow its last character, not its first; `jlreq.Unit` has a new `Last` field for that. Ruby longer than its base now overhangs small kana and the prolonged sound mark as it does other kana (JLReq 3.3.8). In `text/aozora`, a kanji with a variation selector, as in `葛󠄀《かつら》`, is part of the implicit base.
- Vertical text: dashes, leaders and curly quotes (`… ‥ ― — – ‐ “ ” ‘ ’`) took their orientation from the script around them, so between kana a dash with no vertical form in the font, such as `—` in Yu Gothic, stood upright and crossed the column, and alone or next to Latin `…` turned sideways instead of taking its vertical form. They now stand upright where the font has a `vert` form for them and turn sideways where it does not.
- JLReq Oikomi counted the space after the last character of a line, such as the quarter em before Western text, as room to squeeze, although that space goes with the line end. A character that must not start a line was then pushed in, and the line ran past its width.
- JLReq: a quarter em of Japanese–Western space was put between the ideographic space U+3000 and Western text. JLReq puts none next to a full-width space.
- Editor: a search on its own goroutine, as of a file, looked at `maxMatches` and at being stopped only every 65,536 lines, so that a frequent query over long lines gathered millions of matches before the cap applied, and a new query waited for the batch to end. It now stops at once, at exactly 100,000 matches, also within one line.
- Editor: every edit with a search open copied all the matches after the edited lines into a new slice, megabytes a keystroke with 100,000 matches; they now move in place.
- Editor: `Controller.ReplaceAll` replaced the matches one at a time, each moving the lines or the pieces of a file after it and, in an editor that wraps, counting the rows of every line again, so that 100,000 matches took from seconds to minutes. It now makes the new lines in one pass over the matched lines and changes the text in one step; Undo still takes it back at once.
- `layout.MeasuredExtents.Resize` rebuilt its trees over every row whenever the count changed, so a `List` with `MeasureItems` that gained one row walked all of them. Adding k rows at the end now costs O(k log n), and dropping rows O(log n).
- `collection.Table` with `RowKey` and `GridView` with `ItemKey` called the key for every row when one row was added or removed at the end, to find the selection again. When the selected rows, the focus and the anchor are still at their indexes, the selection now stays without looking further, and an unchanged build calls the key once per selected row instead of twice.
### [0.1.1] - 2026-11-20
#### Fixed
- SVG: an arc whose numbers sweep no angle, or overflow, panicked with an index out of range; it is now drawn as a line. A large `stroke-dashoffset` over a short `stroke-dasharray` could loop forever; the offset is now reduced in float64, and a pattern whose length is not finite draws the stroke solid.
- Layers of `RepaintBoundary` that left the tree stayed in the renderer's layer pool for good, and with them the boundary and its whole subtree, so that scrolling a `List` or `GridView` leaked every row that had shown. Entries not drawn for 120 frames are now dropped. `Canvas.Reset` and the render children of an element no longer keep references past their length.
- Windows: the COM calls of the file dialog and of DirectComposition did not keep pointer arguments alive and in place during the call, and the filter specs of the file dialog were not kept until it returned. `SysAllocString` and a UI Automation call converted pointers to `uintptr` outside the call. Wayland: the locale string given to xkb compose was not kept alive during the call.
### [0.1.0] - 2026-11-18
The first public release.
- A Widget / Element / RenderObject tree with value-type widgets, states, keys and inherited data.
- GPU rendering without cgo: Direct3D 11 on Windows, Vulkan on Linux (Wayland and X11), Metal on macOS (Apple Silicon), and a CPU renderer for tests. Rounded rectangles, gradients, shadows, blur, blend modes, affine transforms, paths, clips, custom shaders, SVG and animated images.
- Text: shaping, fallback fonts, color emoji, BiDi, variable fonts, hyphenation, and Japanese typesetting after JLReq, with ruby and vertical text.
- Input: keyboard, mouse, touchpad, touch, inline IME composition on Windows, macOS and Wayland.
- Accessibility through UI Automation, AT-SPI and the macOS accessibility API.
- Over a hundred widgets in `widgets/basic`, `control`, `field`, `collection`, `nav`, `overlay`, `interact` and `editor`, and a Markdown view.
- Themes generated from one accent color, light and dark following the OS.
- Animations: implicit animations, controllers, springs, hero and page transitions.
- Lists, tables, trees and editors of any length: only the rows in view are laid out, and scroll offsets are float64, so that a hundred million rows still scroll a pixel at a time. `collection.Table` takes rows through `RowCount` and `Row`; `editor.Editor` takes lines through `editor.LineSource`, as those of a file of gigabytes, keeps only the edited lines in memory and searches on a goroutine of its own.
- Desktop: multiple windows, modal windows, menus, custom title bars, tray icons, notifications, clipboard, file dialogs, drag and drop.
- `gowakutest` for tests without a window, `gowakupreview` and `cmd/gowaku-preview` for live previews.
[Unreleased]: https://github.com/bankai-tensei/gowaku/compare/v0.3.0...HEAD
[0.3.0]: https://github.com/bankai-tensei/gowaku/compare/v0.2.1...v0.3.0
[0.2.1]: https://github.com/bankai-tensei/gowaku/compare/v0.2.0...v0.2.1
[0.2.0]: https://github.com/bankai-tensei/gowaku/compare/v0.1.2...v0.2.0
[0.1.2]: https://github.com/bankai-tensei/gowaku/compare/v0.1.1...v0.1.2
[0.1.1]: https://github.com/bankai-tensei/gowaku/compare/v0.1.0...v0.1.1
[0.1.0]: https://github.com/bankai-tensei/gowaku/releases/tag/v0.1.0
---
## Security
[日本語は下にある](#日本語)
### Reporting a vulnerability
Please do not open a public issue for a security problem. Report it privately through GitHub: on the repository page, open **Security**, then **Report a vulnerability**. Include what is affected, how to reproduce it, and the impact you see.
You will get an answer within a week. Once a fix is ready, it is released and the report is published with credit to you, unless you ask otherwise.
### Supported versions
gowaku is before v1.0. Only the latest release gets security fixes.
### 日本語
セキュリティの問題は、公開の issue に書かないでほしい。GitHub の非公開の報告を使う。リポジトリのページで **Security** を開き、**Report a vulnerability** から送る。影響を受けるもの、再現の手順、考えられる影響を書く。
1 週間以内に返事をする。修正ができたらリリースし、希望が無ければ報告者の名前を添えて報告を公開する。
gowaku は v1.0 の前なので、セキュリティの修正は最新のリリースにだけ入れる。
---
## Third-party notices
gowaku is licensed under the [MIT License](LICENSE). It includes or derives from the following material, under its own license.
### Included in the library
| What | Where | Source | License |
|---|---|---|---|
| HCT color math, ported to Go | `theme/cam16.go`, `theme/solver.go`, `theme/srgb.go`, `theme/palette.go` and nearby | [material-color-utilities](https://github.com/material-foundation/material-color-utilities), Copyright 2021 Google LLC | Apache License 2.0, [theme/LICENSE.material-color-utilities](theme/LICENSE.material-color-utilities) |
| Hyphenation patterns for American English | `text/hyphen/patterns/hyph-en-us.pat.txt`, `hyph-en-us.hyp.txt` | hyph-utf8, Copyright (C) 1990, 2004, 2005 Gerard D.C. Kuiken | Permissive, kept with the notice in [text/hyphen/patterns/hyph-en-us.license.txt](text/hyphen/patterns/hyph-en-us.license.txt) |
### Used only by tests
| What | Where | Source | License |
|---|---|---|---|
| Lucide icons | `internal/golden/testdata/svg/lucide/` | [lucide-static](https://lucide.dev) 1.70.0 | ISC, some icons MIT (Feather); [LICENSE](internal/golden/testdata/svg/lucide/LICENSE) |
| Material Symbols | `internal/golden/testdata/svg/material/` | @material-symbols/svg-400 0.48.3, Google | Apache License 2.0; [LICENSE](internal/golden/testdata/svg/material/LICENSE) |
| Test values of the HCT math | `theme/testdata/` | extracted from the tests of material-color-utilities | Apache License 2.0, as above |
### Go modules
gowaku depends on these modules, each under its own license: [purego](https://github.com/ebitengine/purego) (Apache 2.0), [go-text/typesetting](https://github.com/go-text/typesetting) (BSD-3-Clause / Unlicense), [godbus/dbus](https://github.com/godbus/dbus) (BSD-2-Clause), and `golang.org/x/image`, `golang.org/x/sys`, `golang.org/x/text` (BSD-3-Clause). The Go fonts, used by tests and the catalog pictures, come with `golang.org/x/image` under the BSD-3-Clause license.
### Examples
`examples/tategaki` sets the opening of Natsume Soseki's *Botchan* (1906), which is in the public domain, from Aozora Bunko.
---
## Widget catalog
Every public widget, with the package to import and an example. The examples use `core.Widget`, which is `gowaku.Widget`; lower-case helpers such as `themed` and `tile` are small functions of internal/catalog/helpers.go.
### Buttons and actions
Controls that do something when pressed. One `control.Button` covers every button; its `Style` picks one of four looks.
#### control.Button
Import `github.com/bankai-tensei/gowaku/widgets/control`. Also covers control.ButtonStyle, control.ButtonSize.
Runs `OnPress` when pressed. `Style` picks normal, primary, quiet or danger, and `Size` the height. Without `OnPress` it is disabled.
```go
save := func() {}
return basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space12, Children: []core.Widget{
basic.Row{Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
control.Button{Label: "Save", Style: control.ButtonPrimary, OnPress: save},
control.Button{Label: "Duplicate", OnPress: save},
control.Button{Label: "Learn more", Style: control.ButtonQuiet, OnPress: save},
control.Button{Label: "Delete", Style: control.ButtonDanger, OnPress: save},
}},
basic.Row{Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
control.Button{Label: "Copy", Icon: icons.Copy(), OnPress: save},
control.Button{Label: "Small", Size: control.ButtonSmall, OnPress: save},
control.Button{Label: "Disabled"},
control.Button{Label: "Settings", Icon: icons.Settings(), HideLabel: true, OnPress: save},
control.Button{Label: "More", Icon: icons.More(), HideLabel: true, Style: control.ButtonQuiet, OnPress: save},
}},
}}
```
#### interact.Pressable
Import `github.com/bankai-tensei/gowaku/widgets/interact`. Also covers interact.PressState.
The base for a pressable area with a look of your own: `Build` gets the hover, press and focus `PressState` and returns the content.
```go
interact.Pressable{Label: "Open project", OnPress: func() {}, Build: func(s interact.PressState) core.Widget {
return themed(func(th *theme.Theme) core.Widget {
ground := th.Color.Card
if s.Hovered {
ground = th.Color.AccentTint
}
return interact.FocusRing{Visible: s.FocusVisible, Radius: th.Radius.Control, Child: basic.Container{
Width: 220, Padding: geom.All(theme.Space12), Radius: th.Radius.Control, Color: ground,
Child: basic.Row{Spacing: theme.Space8, Children: []core.Widget{
basic.Icon{Path: icons.Folder(), Size: 20, Color: th.Color.AccentInk},
basic.Text{Content: "Open project", Style: colored(th.Text.Control, th.Color.Ink)},
}},
}}
})
}}
```
#### control.Link
Import `github.com/bankai-tensei/gowaku/widgets/control`.
A short text beside the text it belongs to that does something when pressed. It is set in the accent ink and underlined under the pointer. Enter presses it, Space does not. Without `OnPress` it is disabled.
```go
basic.Row{Size: layout.MainMin, Spacing: theme.Space4, Children: []core.Widget{
basic.Text{Content: "Sync is off.", Style: note},
control.Link{Label: "Turn it on", OnPress: func() {}},
}},
control.Link{Label: "Release notes", Style: th.Text.Caption, OnPress: func() {}},
control.Link{Label: "Disabled without OnPress"},
```
### Input
Controls that take text and numbers. Labels sit above the field or at the left of a `collection.GroupRow`.
#### field.Input
Import `github.com/bankai-tensei/gowaku/widgets/field`. Also covers field.InputController.
A single or multiline text field with its label above. It handles IMEs, ruby, vertical text and undo. A multiline field grows with its text where nothing sets its height, and fills the height that an `Expanded` or the like gives it, with or without a label. With `SubmitOnEnter`, a multiline field sends on Enter and breaks the line on Shift+Enter, as the box of a chat does. `Autofocus` gives it the keyboard when it first appears, also in a dialog. For long documents, use `editor.Editor`.
```go
set := func(string) {}
return basic.SizedBox{Width: 300, Height: 260, Child: basic.Column{Cross: layout.CrossStretch, Spacing: theme.Space16, Children: []core.Widget{
field.Input{Label: "Name", Value: "Hanako Yamada", OnChange: set},
field.Input{Label: "Email", Placeholder: "name@example.com", OnChange: set},
basic.Expanded{Child: field.Input{
Label: "Notes", Multiline: true, Value: "A multiline field fills the height\nthat an Expanded gives it.", OnChange: set,
}},
}}}
```
#### field.Search
Import `github.com/bankai-tensei/gowaku/widgets/field`.
A text field for searching, with a magnifier and a clear button. Escape empties it.
```go
basic.SizedBox{Width: 260, Child: basic.Column{Size: layout.MainMin, Cross: layout.CrossStretch, Spacing: theme.Space12, Children: []core.Widget{
field.Search{OnChange: func(string) {}},
field.Search{Value: "quarterly report", OnChange: func(string) {}},
}}}
```
#### field.Autocomplete
Import `github.com/bankai-tensei/gowaku/widgets/field`.
A text field that suggests choices below itself as you type. The arrows move through them; Enter or Tab takes one.
```go
cities := []string{"Amsterdam", "Athens", "Berlin", "Lisbon", "Madrid", "Paris", "Prague", "Rome"}
return basic.SizedBox{Width: 260, Child: field.Autocomplete[string]{
Label: "City", Placeholder: "Type a city", Options: cities, OnSelect: func(string) {},
}}
```
#### editor.Editor
Import `github.com/bankai-tensei/gowaku/widgets/editor`. Also covers editor.Controller, editor.Decoration, editor.TextPosition, editor.TextRange, editor.FindOptions.
An editor for code and long text, with line numbers, decorations and find and replace. It lays out only the lines in view. While the find bar is open, the text keeps the room of the bar above its first line, and a match shows below the bar. Lines given through `Controller.SetSource`, as of a file, are read only where they are in view, and only the lines edited are held in memory, so that a file of gigabytes opens at once.
```go
var doc editor.Controller
doc.SetText("package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"Hello, gowaku\")\n}")
return basic.SizedBox{Width: 420, Height: 180, Child: editor.Editor{
Controller: &doc, Label: "Source", LineNumbers: true, Border: true, HighlightCurrentLine: true,
}}
```
#### control.NumberStepper
Import `github.com/bankai-tensei/gowaku/widgets/control`.
Changes a whole number with minus and plus buttons. `Format` adds a unit. For the steps of a wizard, see `nav.Steps`.
```go
seconds := func(v int) string { return strconv.Itoa(v) + " s" }
return basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space12, Children: []core.Widget{
control.NumberStepper{Value: 4, Max: 12, Label: "Copies", OnChange: func(int) {}},
control.NumberStepper{Value: 30, Max: 60, Step: 5, Format: seconds, Label: "Delay", OnChange: func(int) {}},
}}
```
#### control.Slider
Import `github.com/bankai-tensei/gowaku/widgets/control`.
Picks a value in a range. `Snap` holds it to the grid of `Step`. The arrow keys move it too.
```go
basic.SizedBox{Width: 260, Child: basic.Column{Size: layout.MainMin, Cross: layout.CrossStretch, Spacing: theme.Space16, Children: []core.Widget{
control.Slider{Value: 0.35, Label: "Volume", OnChange: func(float32) {}},
control.Slider{Value: 40, Min: 0, Max: 100, Step: 10, Snap: true, Label: "Zoom", OnChange: func(float32) {}},
control.Slider{Value: 0.7, Label: "Disabled"},
}}}
```
#### control.RangeSlider
Import `github.com/bankai-tensei/gowaku/widgets/control`.
A `Slider` with two thumbs that picks a range; dragging the band between them moves both. The thumbs stay `MinGap` apart, and each is a stop of Tab.
```go
control.RangeSlider{
Label: "Price", Low: 20000, High: 60000, Min: 0, Max: 100000,
Step: 1000, Snap: true, MinGap: 5000, OnChange: set,
},
control.RangeSlider{Label: "Disabled", Low: 0.3, High: 0.6},
```
#### field.NumberField
Import `github.com/bankai-tensei/gowaku/widgets/field`.
A field for a number, typed or stepped with the arrow keys, the wheel while it has the focus, or a drag of the handle at its end. It takes full-width digits, and the separators follow the locale. Enter takes the typed text as the value; inside a `FormItem` it then submits the `Form` around with the new value, and outside one it submits nothing.
```go
basic.SizedBox{Width: 140, Child: field.NumberField{Label: "Quantity", Value: 3, Min: 0, Max: 99, OnChange: set}},
basic.SizedBox{Width: 180, Child: field.NumberField{Label: "Price", Value: 128000, Step: 100, Grouping: true, OnChange: set}},
basic.SizedBox{Width: 140, Child: field.NumberField{Label: "Ratio", Value: 0.25, Min: 0, Max: 1, Step: 0.05, OnChange: set}},
```
#### field.TokenField
Import `github.com/bankai-tensei/gowaku/widgets/field`.
Edits a list of short texts such as tags or addresses, each shown as a chip. Enter or a separator makes a token, but not while an IME converts. Two Backspaces at the start remove the last token.
```go
field.TokenField{Label: "Tags", Tokens: []string{"design", "go", "typography"}, Placeholder: "Add a tag", OnChange: set},
field.TokenField{Label: "Disabled", Tokens: []string{"read only"}},
```
#### field.Form
Import `github.com/bankai-tensei/gowaku/widgets/field`. Also covers field.FormItem, field.FormController.
Checks and submits the `FormItem`s below it together. Errors show below the fields, whose borders turn red, on submit and when a field loses the focus. The error of `Required` follows the control inside: Required for a text field, Choose one for a choice such as a `DropdownMenu` or a `DatePicker`, Check this box for a `Checkbox`; `RequiredMessage` replaces it. Enter in a single-line field of a `FormItem` submits the form.
```go
var form field.FormController
email := regexp.MustCompile(`[^@\s]+@[^@\s]+\.[^@\s]+`)
return basic.SizedBox{Width: 280, Child: field.Form{Controller: &form, Child: basic.Column{
Size: layout.MainMin, Cross: layout.CrossStretch, Spacing: theme.Space12, Children: []core.Widget{
field.FormItem[string]{Required: true, Child: field.Input{Label: "Name", OnChange: func(string) {}}},
field.FormItem[string]{
Value: "taro@",
Validators: []func(string) string{field.Pattern(email, "Enter an address like name@example.com")},
Child: field.Input{Label: "Email", Value: "taro@", OnChange: func(string) {}},
},
field.FormItem[time.Time]{Required: true, Child: field.DatePicker{
Label: "Birth date", Placeholder: "Choose a date", OnChange: func(time.Time) {},
InitialMonth: time.Date(1995, time.January, 1, 0, 0, 0, 0, time.UTC),
}},
field.FormItem[bool]{Required: true, Child: control.Checkbox{Label: "I agree to the terms", OnChange: func(bool) {}}},
basic.Row{Main: layout.MainEnd, Children: []core.Widget{
control.Button{Label: "Create account", Style: control.ButtonPrimary, OnPress: func() { form.Submit() }},
}},
},
}}}
```
#### field.TimePicker
Import `github.com/bankai-tensei/gowaku/widgets/field`. Also covers field.HourCycle.
A field for a time of day, edited part by part with the arrows or digits. The locale picks the 12 or 24 hour clock.
```go
at := func(h, m int) time.Duration { return time.Duration(h)*time.Hour + time.Duration(m)*time.Minute }
return basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space12, Children: []core.Widget{
field.TimePicker{Label: "Start", Value: at(9, 30), MinuteStep: 15, OnChange: func(time.Duration) {}},
field.TimePicker{Value: at(21, 5) + 42*time.Second, Seconds: true, HourCycle: field.HourCycle24, OnChange: func(time.Duration) {}},
}}
```
### Selection
Controls that pick from a set of choices: `control.SegmentedControl` for two to four, `field.DropdownMenu` for more.
#### control.Checkbox
Import `github.com/bankai-tensei/gowaku/widgets/control`.
A box that turns an option on and off. The label is part of the target.
```go
set := func(bool) {}
return basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space12, Children: []core.Widget{
control.Checkbox{Value: true, Label: "Open at login", OnChange: set},
control.Checkbox{Label: "Show in menu bar", OnChange: set},
control.Checkbox{Value: true, Label: "Disabled"},
}}
```
#### control.Switch
Import `github.com/bankai-tensei/gowaku/widgets/control`.
Turns a setting on and off at once, with a knob that moves on a spring.
```go
basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space12, Children: []core.Widget{
basic.Row{Size: layout.MainMin, Spacing: theme.Space12, Children: []core.Widget{
control.Switch{Value: true, Label: "Wi-Fi", OnChange: func(bool) {}},
basic.Text{Content: "Wi-Fi"},
}},
basic.Row{Size: layout.MainMin, Spacing: theme.Space12, Children: []core.Widget{
control.Switch{Label: "Bluetooth", OnChange: func(bool) {}},
basic.Text{Content: "Bluetooth"},
}},
}}
```
#### control.RadioGroup
Import `github.com/bankai-tensei/gowaku/widgets/control`. Also covers control.RadioOption.
A set of radio buttons that picks one choice. It is one stop for Tab, and the arrows move between the choices.
```go
control.RadioGroup[string]{
Label: "Appearance", Value: "auto", OnChange: func(string) {},
Options: []control.RadioOption[string]{
{Value: "light", Label: "Light"},
{Value: "dark", Label: "Dark"},
{Value: "auto", Label: "Automatic"},
{Value: "contrast", Label: "High contrast", Disabled: true},
},
}
```
#### control.Radio
Import `github.com/bankai-tensei/gowaku/widgets/control`.
A single radio button, for layouts a `RadioGroup` cannot give. Name the set with a `Semantics`.
```go
interact.Semantics{Role: semantics.RoleRadioGroup, Label: "Size", Child: basic.Row{
Size: layout.MainMin, Spacing: theme.Space16, Children: []core.Widget{
control.Radio{Label: "Small", OnSelect: func() {}},
control.Radio{Label: "Medium", Selected: true, OnSelect: func() {}},
control.Radio{Label: "Large", OnSelect: func() {}},
},
}}
```
#### control.SegmentedControl
Import `github.com/bankai-tensei/gowaku/widgets/control`.
Picks one of two to four choices, with a plate that slides on a spring.
```go
basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space12, Children: []core.Widget{
control.SegmentedControl{Label: "Repeat", Options: []string{"Off", "All", "One"}, Selected: 1, OnChange: func(int) {}},
control.SegmentedControl{Label: "View", Options: []string{"Day", "Week", "Month", "Year"}, Selected: 2, OnChange: func(int) {}},
}}
```
#### field.DropdownMenu
Import `github.com/bankai-tensei/gowaku/widgets/field`. Also covers field.DropdownOption.
A field that opens a list below itself to pick one choice. Typing a letter jumps to the choices that start with it.
```go
basic.SizedBox{Width: 200, Child: field.DropdownMenu[string]{
Label: "Plan", Value: "team", OnChange: func(string) {},
Options: []field.DropdownOption[string]{
{Value: "free", Label: "Free"},
{Value: "team", Label: "Team"},
{Value: "business", Label: "Business"},
{Value: "school", Label: "School", Disabled: true},
},
}}
```
#### control.Chip
Import `github.com/bankai-tensei/gowaku/widgets/control`.
A compact pill: a toggling filter with `OnChange`, a button with `OnPress`, or a plain tag with neither.
```go
basic.SizedBox{Width: 360, Child: basic.Wrap{Spacing: theme.Space8, RunSpacing: theme.Space8, Children: []core.Widget{
control.Chip{Label: "All", Selected: true, OnChange: func(bool) {}},
control.Chip{Label: "Unread", OnChange: func(bool) {}},
control.Chip{Label: "Starred", Icon: icons.Star(), OnChange: func(bool) {}},
control.Chip{Label: "Suggested reply", OnPress: func() {}},
control.Chip{Label: "design", OnRemove: func() {}},
control.Chip{Label: "Plain tag"},
}}}
```
#### field.Calendar
Import `github.com/bankai-tensei/gowaku/widgets/field`.
Picks a day from a month. The first day of the week and the names follow the locale. `Marks` puts dots under days. The title opens the months of the year, and the year the years of a decade, so a day far away, such as a birth date, takes a few presses. While `Value` is zero it opens on `InitialMonth`.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.Container{Color: th.Color.Card, Radius: th.Radius.Group, Padding: geom.All(theme.Space12), Child: field.Calendar{
Value: day(18), Today: day(9), OnChange: func(time.Time) {},
Marks: func(d time.Time) []geom.Color {
if d.Day() == 12 || d.Day() == 24 {
return []geom.Color{th.Color.AccentInk}
}
return nil
},
}}
})
```
#### field.DatePicker
Import `github.com/bankai-tensei/gowaku/widgets/field`.
A field that shows a date and opens a `Calendar` below itself, whose title switches to the months and the years (the picture shows the years). For a birth date, give an `InitialMonth` some thirty years back and a `Max` of today. In a `FormItem` its border turns red with an error.
```go
day := func(d int) time.Time { return time.Date(2026, time.November, d, 0, 0, 0, 0, time.UTC) }
return field.DatePicker{
Label: "Due date", Value: day(18), Today: day(9),
ShowToday: true, ShowClear: true, OnChange: func(time.Time) {},
}
```
#### field.ColorPicker
Import `github.com/bankai-tensei/gowaku/widgets/field`.
Chooses a color with a plane of saturation and brightness, strips of hue and opacity, and a hex field. It keeps HSV, so the hue survives black and gray. A `collection.PropertyColor` with `OnChange` opens one.
```go
field.ColorPicker{
Value: geom.Hex(0x3a7bf0), Label: "Accent color", OnChange: func(geom.Color) {},
Swatches: []geom.Color{
geom.Hex(0x3a7bf0), geom.Hex(0x5e5ce6), geom.Hex(0xbf5af2), geom.Hex(0xff375f),
geom.Hex(0xff9f0a), geom.Hex(0x30d158), geom.Hex(0x8e8e93),
},
}
```
### Display
Widgets that show text, pictures and numbers, with no action of their own.
#### basic.Text
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Shows a string broken into lines by the rules of its `Style`, with Japanese line breaking, vertical text and justification. `Style.MaxLines` cuts it short with an ellipsis; a screen reader still reads it whole.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.SizedBox{Width: 340, Child: basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space6, Children: []core.Widget{
basic.Text{Content: "Large title", Style: th.Text.LargeTitle},
basic.Text{Content: "Title", Style: th.Text.Title},
basic.Text{Content: "Body text breaks into lines by the rules of its style, and the line height stays on an even grid."},
basic.Text{Content: "Caption in the secondary ink", Style: colored(th.Text.Caption, th.Color.Ink2)},
// MaxLines cuts the text short with an ellipsis.
basic.Text{Content: "A one-line preview of a long message that does not fit in the row", Style: th.Text.Body.WithMaxLines(1)},
}}}
})
```
#### basic.RichText
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Mixes spans of different looks in one paragraph, with ruby and emphasis dots, and a `Background` behind a span, such as a match of a search. `Style.MaxLines` works as for `Text`.
```go
themed(func(th *theme.Theme) core.Widget {
c := &th.Color
return basic.SizedBox{Width: 320, Child: basic.RichText{Style: colored(th.Text.Body, c.Ink).WithMaxLines(2), Spans: []text.Span{
{Text: "Rich text mixes "},
{Text: "accented", Style: colored(th.Text.Body, c.AccentInk)},
{Text: ", "},
{Text: "bold", Style: colored(th.Text.Body, c.Ink).WithWeight(700)},
{Text: ", "},
{Text: "large", Style: text.Style{Size: 20, Color: c.Ink}},
{Text: ", "},
{Text: "quiet", Style: colored(th.Text.Caption, c.Ink2)},
{Text: " and "},
{Text: "highlighted", Background: c.Warning.WithAlpha(0.35)},
{Text: " runs in one paragraph that wraps, and stops after two lines with an ellipsis."},
}}}
})
```
#### field.SelectionArea
Import `github.com/bankai-tensei/gowaku/widgets/field`.
Makes the `Text` and `RichText` below it selectable with the mouse and the keyboard, and copyable, across paragraphs; ruby copies as its base text.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.SizedBox{Width: 380, Child: field.SelectionArea{Child: basic.Column{
Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space8, Children: []core.Widget{
basic.Text{Content: "Upload failed", Style: th.Text.Title},
basic.Text{Content: "dial tcp 192.0.2.10:443: i/o timeout"},
basic.Text{Content: "Drag, double click or Ctrl+A, then Ctrl+C.", Style: colored(th.Text.Caption, th.Color.Ink2)},
},
}}}
})
```
#### basic.Icon
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Draws a vector shape on a 24 unit grid. Without a `Label` it is decorative. Package `icons` holds 24 common shapes: folder, file, search, close, chevrons, gear, trash and more.
```go
themed(func(th *theme.Theme) core.Widget {
// The stock icons of package icons. Build them once and keep them, as
// in InitState: each call makes a new path.
set := []*paint.Path{
icons.Folder(), icons.File(), icons.Document(), icons.Image(), icons.Search(), icons.Plus(),
icons.Minus(), icons.Close(), icons.Check(), icons.ChevronLeft(), icons.ChevronRight(), icons.ChevronUp(),
icons.ChevronDown(), icons.Settings(), icons.Trash(), icons.Edit(), icons.Copy(), icons.Home(),
icons.Star(), icons.Info(), icons.Warning(), icons.Error(), icons.Menu(), icons.More(),
}
stock := make([]core.Widget, len(set))
for i, p := range set {
stock[i] = basic.Icon{Path: p, Color: th.Color.Ink2}
}
return basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space20, Children: []core.Widget{
basic.Row{Size: layout.MainMin, Spacing: theme.Space16, Cross: layout.CrossCenter, Children: []core.Widget{
basic.Icon{Path: set[0], Color: th.Color.AccentInk, Label: "Folder"},
basic.Icon{Path: set[18], Size: 32, Color: th.Color.Danger},
basic.Icon{Path: set[8], Size: 16, Color: th.Color.Success},
basic.Icon{Path: circleIcon(), Color: th.Color.Ink2}, // a path of your own
}},
basic.SizedBox{Width: 400, Child: basic.Wrap{Spacing: theme.Space16, RunSpacing: theme.Space16, Children: stock}},
}}
})
```
#### basic.Image
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Shows a picture. `Fit` picks how it fills its box, `Radius` rounds it and `Quality` sets the filtering.
```go
picture := photo() // paint.NewImage of an image.Image, made once and kept
return basic.Row{Size: layout.MainMin, Spacing: theme.Space16, Children: []core.Widget{
basic.Image{Source: picture, Width: 160, Label: "Hills under a clear sky"},
basic.Image{Source: picture, Width: 100, Height: 100, Fit: layout.FitCover, Radius: 50},
basic.Image{Source: picture, Width: 48, Height: 48, Quality: paint.FilterNearest},
}}
```
#### basic.SVG
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Draws an SVG drawing fitted into a square. `Color` is the currentColor icon sets draw with.
```go
cloud, err := paint.ParseSVG([]byte(``))
if err != nil {
panic(err)
}
return themed(func(th *theme.Theme) core.Widget {
return basic.Row{Size: layout.MainMin, Spacing: theme.Space16, Children: []core.Widget{
basic.SVG{Data: cloud, Label: "Cloud"},
basic.SVG{Data: cloud, Size: 36, Color: th.Color.AccentInk},
basic.SVG{Data: cloud, Size: 56, Color: th.Color.Ink2},
}}
})
```
#### basic.AnimatedImage
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Plays an animated GIF, APNG or WebP. When the OS asks for less motion it shows the first frame.
```go
movie, err := paint.DecodeAnimation(bytes.NewReader(blinkGIF()))
if err != nil {
panic(err)
}
return basic.AnimatedImage{Source: movie, Width: 96, Height: 96, Radius: 12, Quality: paint.FilterNearest, Label: "Blinking light"}
```
#### control.Badge
Import `github.com/bankai-tensei/gowaku/widgets/control`.
A small mark for a count, a word or a dot. With a child it sits on the child's top right corner.
```go
themed(func(th *theme.Theme) core.Widget {
inbox := basic.Icon{Path: squareIcon(), Color: th.Color.Ink2}
return basic.Row{Size: layout.MainMin, Spacing: theme.Space24, Cross: layout.CrossCenter, Children: []core.Widget{
control.Badge{Count: 3, Child: inbox},
control.Badge{Count: 120, Child: inbox},
control.Badge{Dot: true, Child: inbox},
control.Badge{Label: "New"},
control.Badge{Count: 12, Quiet: true},
}}
})
```
#### control.Card
Import `github.com/bankai-tensei/gowaku/widgets/control`.
A surface that holds one piece of content. With `OnPress` the whole card is a button.
```go
basic.Row{Size: layout.MainMin, Spacing: theme.Space16, Cross: layout.CrossStart, Children: []core.Widget{
basic.SizedBox{Width: 200, Child: control.Card{Label: "Summary", Child: basic.Column{
Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space6, Children: []core.Widget{
basic.Text{Content: "Summary"},
basic.Text{Content: "A plain card holds one piece of content."},
},
}}},
basic.SizedBox{Width: 200, Child: control.Card{Label: "Open note", OnPress: func() {}, Child: basic.Column{
Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space6, Children: []core.Widget{
basic.Text{Content: "Pressable"},
basic.Text{Content: "With OnPress the whole card is a button."},
},
}}},
}}
```
#### control.Disclosure
Import `github.com/bankai-tensei/gowaku/widgets/control`.
A header that opens and closes the content below it. Closed content is not laid out, and Tab and assistive technology pass it by. With `OnChange` the parent keeps the state, which makes several in a row an accordion.
```go
control.Disclosure{Title: "Advanced", Child: basic.Text{Content: "Closed, the content is not laid out.", Style: note}},
control.Disclosure{Title: "Sync", Open: true, Child: basic.Text{
Content: "Open starts it open. Without OnChange it keeps its own state.", Style: note,
}},
control.Disclosure{Title: "Notifications", Header: basic.Row{Size: layout.MainMin, Spacing: theme.Space6, Children: []core.Widget{
basic.Text{Content: "Notifications", Style: th.Text.Headline}, control.Badge{Count: 3},
}}, Child: basic.Text{Content: "A header can hold a badge.", Style: note}},
```
#### interact.InteractiveViewer
Import `github.com/bankai-tensei/gowaku/widgets/interact`. Also covers interact.ViewerController, interact.ViewerBoundary, interact.ViewerKeys.
Shows its child through a pan and a zoom: drag to move, Ctrl with the wheel or a pinch to zoom about the pointer. `WheelZooms` zooms with the plain wheel, as image viewers do. The arrow keys pan only while there is room to, and otherwise go on to the shortcuts of the app; `Keys` leaves them out, or keeps the viewer out of the focus. The child is laid out once, and the buttons in it keep working. `ViewerController` moves the view from outside.
```go
var view interact.ViewerController
view.Fit(false) // once the viewer knows its size
return basic.SizedBox{Width: 440, Height: 280, Child: basic.Container{
Radius: th.Radius.Control, Border: paint.Stroke{Width: 1, Color: th.Color.Hair},
Child: interact.InteractiveViewer{
Controller: &view, MinScale: 0.2, MaxScale: 6, BoundaryMargin: 16,
DoubleTapZoom: true, Label: "Drawing", Child: drawing,
},
}}
```
#### basic.Divider
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
A hairline between groups of content. `Indent` keeps it short of the edge, and `Axis` stands it up.
```go
basic.SizedBox{Width: 300, Child: basic.Column{Size: layout.MainMin, Cross: layout.CrossStretch, Spacing: theme.Space12, Children: []core.Widget{
basic.Text{Content: "Above the line"},
basic.Divider{},
basic.Text{Content: "Indented line below"},
basic.Divider{Indent: theme.Space16},
basic.Row{Size: layout.MainMin, Spacing: theme.Space12, Children: []core.Widget{
basic.Text{Content: "Left"},
basic.SizedBox{Height: 20, Child: basic.Divider{Axis: layout.Vertical}},
basic.Text{Content: "Right"},
}},
}}}
```
#### control.Sparkline
Import `github.com/bankai-tensei/gowaku/widgets/control`. Also covers control.SparklineKind.
A line or bar chart the size of a table cell, without axes or legend. NaN leaves a gap, and bars rise and fall from zero. Painting does not allocate.
```go
basic.Row{Size: layout.MainMin, Cross: layout.CrossCenter, Spacing: theme.Space24, Children: []core.Widget{
basic.SizedBox{Width: 140, Height: 28, Child: control.Sparkline{
Data: trend, Fill: true, MarkLast: true, Label: "Temperature, now 21.4 degrees",
}},
basic.SizedBox{Width: 120, Height: 28, Child: control.Sparkline{Kind: control.SparklineBars, Data: change}},
}}
```
### Navigation
Widgets that move between pages and places. Only the current place takes the accent color.
#### control.Tabs
Import `github.com/bankai-tensei/gowaku/widgets/control`. Also covers control.TabPage.
Switches between pages, with the chosen page below a row of underlined tabs.
```go
basic.SizedBox{Width: 340, Height: 150, Child: control.Tabs{
Label: "Settings", Selected: 1, OnChange: func(int) {},
Pages: []control.TabPage{
{Label: "General"},
{Label: "Appearance", Child: basic.Padding{Insets: geom.All(theme.Space16), Child: basic.Text{
Content: "The page of the chosen tab shows below the bar.",
}}},
{Label: "Advanced"},
},
}}
```
#### collection.Sidebar
Import `github.com/bankai-tensei/gowaku/widgets/collection`. Also covers collection.SidebarItem.
The column of places at the left of a window. It draws its own ground and the hairline at its right edge; put it first in a `Row` with `CrossStretch`. `Width` sets its width, 208 when zero. When the rows do not fit, they alone scroll: the title, the `Header` under it, such as a search field, and the `Footer` pinned at the bottom, such as buttons, stay. The selected row takes the `AccentTint` ground. The `Count` of a `SidebarItem`, such as of unread messages, shows in a quiet pill at the end of the row, and a screen reader hears it once, as the value of the row. A `Detail` is a smaller second line in `Ink2` (on the selected row in the colors of `theme.Colors.OnTint`, which read on the tint, as is its count), such as the last message of a chat, cut to one line with an ellipsis; a row with one is 46 high, and a screen reader hears the whole detail once, as the description of the row. `Leading` puts a widget in place of the `Icon`, such as the colored dot of a mail label; on the selected row it is built under the `OnTint` theme, so that what takes the colors of the theme reads on the tint, while a color of its own, as that of the dot, stays.
```go
open := func() {}
return basic.SizedBox{Height: 340, Child: collection.Sidebar{
Title: "Library",
Header: field.Search{Placeholder: "Search", OnChange: func(string) {}},
Children: []core.Widget{
collection.SidebarItem{Label: "Home", Icon: icons.Home(), OnPress: open},
collection.SidebarItem{Label: "Shared", Icon: icons.Folder(), Detail: "With Aoi and Ren, edited today", OnPress: open},
collection.SidebarItem{Label: "Documents", Icon: icons.Document(), Count: 3, Selected: true, OnPress: open},
collection.SidebarItem{Label: "Starred", Icon: icons.Star(), Count: 128, OnPress: open},
collection.SidebarItem{Label: "Pictures", Icon: icons.Image(), OnPress: open},
},
Footer: control.Button{Label: "New Folder", Icon: icons.Plus(), Style: control.ButtonQuiet, OnPress: open},
}}
```
#### nav.Breadcrumb
Import `github.com/bankai-tensei/gowaku/widgets/nav`. Also covers nav.BreadcrumbItem.
The trail to the current place. Where it does not fit, the middle folds into a menu.
```go
trail := []nav.BreadcrumbItem{
{Label: "Home", Icon: icons.Folder()}, {Label: "Documents"}, {Label: "Projects"}, {Label: "gowaku"}, {Label: "widgets"},
}
return basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space12, Children: []core.Widget{
basic.SizedBox{Width: 480, Child: nav.Breadcrumb{Items: trail, OnSelect: func(int) {}}},
// Where the trail does not fit, the middle folds into a menu.
basic.SizedBox{Width: 260, Child: nav.Breadcrumb{Items: trail, OnSelect: func(int) {}}},
}}
```
#### nav.Steps
Import `github.com/bankai-tensei/gowaku/widgets/nav`.
Shows where a flow of several steps is, such as a wizard or a checkout: a numbered circle and a name for each step, joined by lines. The steps before `Current` are done and show a check; the current one has a circle in the accent and a bold name. With `OnStepPress`, the done steps can be pressed to go back, and Tab and Enter or Space reach them. A screen reader hears a list of the steps, each with its name, its place, such as 2 of 3, and "Current step" or "Completed". For the minus and plus buttons of a number, see `control.NumberStepper`.
```go
labels := []string{"Account", "Shipping", "Payment", "Review"}
return basic.Column{Size: layout.MainMin, Cross: layout.CrossStretch, Spacing: theme.Space20, Children: []core.Widget{
nav.Steps{Labels: labels, Current: 2, OnStepPress: func(int) {}},
// Every step done.
nav.Steps{Labels: labels[:3], Current: 3},
}}
```
#### nav.Navigator
Import `github.com/bankai-tensei/gowaku/widgets/nav`. Also covers nav.NavigatorController, nav.PageRoute, nav.RoutePattern, nav.RouteParams.
A stack of pages. Routes build pages from name patterns, and Alt+Left goes back.
```go
basic.SizedBox{Width: 360, Height: 190, Child: nav.Navigator{
Home: noteList{}, // its rows call NavigatorOf(ctx).PushNamed("/notes/1")
Routes: []nav.RoutePattern{{Pattern: "/notes/:id", Build: func(p nav.RouteParams) core.Widget {
i, _ := p.Int("id")
return notePage{index: i}
}}},
}}
```
#### nav.BackButton
Import `github.com/bankai-tensei/gowaku/widgets/nav`.
Goes back to the previous page of the nearest `Navigator`. On the first page it shows nothing.
```go
// The top bar of a page that a Navigator pushed:
return basic.Row{Children: []core.Widget{nav.BackButton{Label: "Notes"}}}
```
### Feedback and overlays
Widgets that report progress and results, and the ones that float above the page, shown with the `overlay.Show...` functions.
#### control.ProgressBar
Import `github.com/bankai-tensei/gowaku/widgets/control`.
Shows how much is done as a bar that fills from the left. A new value slides into place. With `Indeterminate` it shows work of unknown length as a band that crosses the bar again and again, and a screen reader hears a busy indicator with no value. The band moves only while it is seen, and stands in the middle when the window asks for less motion.
```go
basic.SizedBox{Width: 260, Child: basic.Column{Size: layout.MainMin, Cross: layout.CrossStretch, Spacing: theme.Space16, Children: []core.Widget{
control.ProgressBar{Value: 0.62, Label: "Library sync"},
control.ProgressBar{Value: 0.25, Label: "Upload"},
control.ProgressBar{Indeterminate: true, Label: "Connecting"},
}}}
```
#### control.ProgressRing
Import `github.com/bankai-tensei/gowaku/widgets/control`.
Shows how much is done as a ring that fills clockwise from twelve, with a child in its middle. With `Indeterminate` it is a spinner for work of unknown length: an arc turns around the ring. A screen reader hears a busy indicator with no value, named Loading in the language of the window when it has no label. The arc turns only while it is seen, and stands at twelve when the window asks for less motion.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.Row{Size: layout.MainMin, Spacing: theme.Space24, Cross: layout.CrossCenter, Children: []core.Widget{
control.ProgressRing{Value: 0.32, Label: "Album art"},
control.ProgressRing{Value: 0.75, Size: 48, Color: th.Color.Success, Label: "Lyrics", Child: basic.Text{
Content: "75", Style: colored(th.Text.Caption, th.Color.Ink2),
}},
control.ProgressRing{Indeterminate: true, Label: "Syncing"},
}}
})
```
#### control.Skeleton
Import `github.com/bankai-tensei/gowaku/widgets/control`. Also covers control.SkeletonShape, control.SkeletonText, control.SkeletonGroup.
Stands in for content that is still loading. One band of light crosses the window, only while a skeleton is seen, and stops when the OS asks for less motion. `SkeletonGroup` tells assistive technology that it is loading.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.Container{Width: 320, Color: th.Color.Card, Radius: th.Radius.Group, Padding: geom.All(theme.Space16), Child: control.SkeletonGroup{
Label: "Loading messages",
Child: basic.Row{Cross: layout.CrossStart, Spacing: theme.Space12, Children: []core.Widget{
control.Skeleton{Shape: control.SkeletonCircle, Width: 40},
basic.Expanded{Child: basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space8, Children: []core.Widget{
control.Skeleton{Width: 96, Height: 14},
control.SkeletonText{Lines: 3},
}}},
}},
}}
})
```
#### overlay.Tooltip
Import `github.com/bankai-tensei/gowaku/widgets/overlay`.
A short label that shows when the pointer rests on its child or the keyboard moves to it. Assistive technology gets it as the description.
```go
tool := func(label, tip string) core.Widget {
return overlay.Tooltip{Message: tip, Child: control.Button{Label: label, Style: control.ButtonQuiet, OnPress: func() {}}}
}
return basic.Row{Size: layout.MainMin, Spacing: theme.Space4, Children: []core.Widget{
tool("Bold", "Bold (Ctrl+B)"),
tool("Italic", "Italic (Ctrl+I)"),
tool("Link", "Insert a link (Ctrl+K)"),
}}
```
#### overlay.Toast
Import `github.com/bankai-tensei/gowaku/widgets/overlay`.
A short message at the bottom of the window for a few seconds, with an optional action such as Undo. Show it with `ShowToast`.
```go
basic.Builder{Content: func(ctx core.BuildContext) core.Widget {
return control.Button{Label: "Move to trash", OnPress: func() {
overlay.ShowToast(ctx, overlay.Toast{Message: "Moved 3 notes to the trash", Action: "Undo", OnAction: func() {}})
}}
}}
```
#### control.InfoBar
Import `github.com/bankai-tensei/gowaku/widgets/control`. Also covers control.InfoSeverity.
A notice that stays in the page: info, success, warning or error, with a close button and one action. The parent shows it with `Open`.
```go
control.InfoBar{
Open: true, Severity: control.SeverityWarning,
Title: "You are offline", Message: "Changes are saved on this device and sync when you reconnect.",
OnClose: closed,
},
control.InfoBar{
Open: true, Severity: control.SeverityError,
Title: "Could not save", Message: "The disk is full.",
Action: "Retry", OnAction: func() {}, OnClose: closed,
},
```
#### overlay.Dialog
Import `github.com/bankai-tensei/gowaku/widgets/overlay`.
A card that stops the work for an answer. Show it with `ShowDialog`; the focus stays inside. `Glass` blurs what is behind.
```go
basic.Builder{Content: func(ctx core.BuildContext) core.Widget {
return control.Button{Label: "Delete", Style: control.ButtonDanger, OnPress: func() {
overlay.ShowDialog(ctx, func(dismiss func()) core.Widget {
return overlay.Dialog{
Title: "Delete this note?",
Message: "It cannot be undone.",
Actions: []core.Widget{
control.Button{Label: "Cancel", OnPress: dismiss},
control.Button{Label: "Delete", Style: control.ButtonDanger, OnPress: dismiss},
},
}
})
}}
}}
```
#### overlay.Sheet
Import `github.com/bankai-tensei/gowaku/widgets/overlay`. Also covers overlay.SheetEdge.
A panel that slides in from the bottom or the side of the window. Show it with `ShowSheet`.
```go
basic.Builder{Content: func(ctx core.BuildContext) core.Widget {
return control.Button{Label: "Share", OnPress: func() {
overlay.ShowSheet(ctx, overlay.Sheet{Label: "Share note"}, func(dismiss func()) core.Widget {
return basic.Column{Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
basic.Text{Content: "Anyone with the link can read this note."},
basic.Row{Main: layout.MainEnd, Spacing: theme.Space8, Children: []core.Widget{
control.Button{Label: "Cancel", OnPress: dismiss},
control.Button{Label: "Copy link", Style: control.ButtonPrimary, OnPress: dismiss},
}},
}}
})
}}
}}
```
### Data
Widgets that show and edit many rows. Each builds only the rows in view.
#### collection.List
Import `github.com/bankai-tensei/gowaku/widgets/collection`.
A vertical list of any length that builds only the rows near the view. Rows may differ in height.
```go
basic.SizedBox{Width: 320, Height: 180, Child: collection.List{
ItemCount: 10000, ItemExtent: 36,
ItemBuilder: func(i int) core.Widget {
return basic.Padding{Insets: geom.Symmetric(theme.Space12, theme.Space8), Child: basic.Text{
Content: "Row " + strconv.Itoa(i+1) + " of 10,000",
}}
},
}}
```
#### collection.GridView
Import `github.com/bankai-tensei/gowaku/widgets/collection`.
A grid of tiles of any number that builds only the rows near the view. The width decides the columns, and a `TableController` holds the selection and the focus, which stay on the same items when they move given an `ItemKey`. The arrows move between tiles and Enter opens one.
```go
var photos collection.TableController
photos.SetSelection(collection.RowRange{Start: 1, End: 3})
return basic.SizedBox{Width: 460, Height: 280, Child: collection.GridView{
ItemCount: 10000, MinColumnWidth: 96, AspectRatio: 4.0 / 3, ExtraHeight: 20,
Spacing: theme.Space8, RunSpacing: theme.Space8, Padding: geom.All(theme.Space8),
Label: "Photos", Controller: &photos,
LabelOf: func(i int) string { return "Photo " + strconv.Itoa(i+1) },
ItemBuilder: func(i int) core.Widget {
tone := theme.TonalPalette{Hue: float64(i*47%360) + 0.5, Chroma: 36}.Tone(66)
return basic.Column{Cross: layout.CrossStretch, Spacing: theme.Space4, Children: []core.Widget{
basic.Expanded{Child: basic.Container{Color: tone, Radius: th.Radius.Control}},
basic.Text{Content: "Photo " + strconv.Itoa(i+1), Style: small},
}}
},
}}
```
#### collection.ReorderableList
Import `github.com/bankai-tensei/gowaku/widgets/collection`.
A `List` whose items move by drag or with Ctrl+Shift and an arrow. It does not own the items: `OnReorder` asks for the move. A screen reader hears the new place.
```go
basic.SizedBox{Width: 300, Height: 220, Child: collection.ReorderableList{
ItemCount: len(todos), ItemExtent: 44, Label: "To do",
LabelOf: func(i int) string { return todos[i] },
// Move the item in your data, then build again.
OnReorder: func(_, _ int) {},
ItemBuilder: func(i int) core.Widget {
return basic.Padding{Insets: geom.Symmetric(theme.Space12, 0), Child: basic.Row{Cross: layout.CrossCenter, Children: []core.Widget{
basic.Expanded{Child: basic.Text{Content: todos[i]}},
basic.Text{Content: "≡"},
}}}
},
}}
```
#### collection.Table
Import `github.com/bankai-tensei/gowaku/widgets/collection`. Also covers collection.TableColumn, collection.TableController, collection.TableSort, collection.TableFilter, collection.TableEdit, collection.TableEditor, collection.CellKind, collection.CellTone, collection.RowRange, collection.SortOrder, collection.TableSelectMode.
A table with sorting, filters, range selection, cell editing and frozen columns. Cells show text, badges, dots, bars or check boxes. With `RowKey` the selection stays on the same rows when they are sorted or deleted. The header of the sorted column tells a screen reader its order. Rows that live elsewhere, as the lines of a file, come through `RowCount` and `Row` without a slice of them.
```go
rows := []task{
{"Design review", "Aiko", "Done", 1},
{"Release notes", "Ben", "In progress", 0.6},
{"Fix the build", "Chiara", "Blocked", 0.2},
{"Translate docs", "Daichi", "In progress", 0.4},
{"Plan the sprint", "Aiko", "Done", 1},
}
tone := func(t task) collection.CellTone {
switch t.status {
case "Done":
return collection.CellToneSuccess
case "Blocked":
return collection.CellToneDanger
}
return collection.CellToneAccent
}
return basic.SizedBox{Width: 520, Height: 220, Child: collection.Table[task]{
Label: "Tasks", Rows: rows,
Sort: collection.TableSort{Column: 0, Order: collection.SortAscending}, OnSort: func(collection.TableSort) {},
Columns: []collection.TableColumn[task]{
{Title: "Task", Width: 160, Text: func(t task) string { return t.name }, Sortable: true},
{Title: "Owner", Width: 100, Text: func(t task) string { return t.owner }, Sortable: true},
{Title: "Status", Width: 120, Text: func(t task) string { return t.status }, Kind: collection.CellBadge, Tone: tone},
{Title: "Done", Width: 120, Kind: collection.CellProgress, Value: func(t task) float32 { return t.done }},
},
}}
```
#### collection.Tree
Import `github.com/bankai-tensei/gowaku/widgets/collection`. Also covers collection.TreeController, collection.TreeMove, collection.TreeDrop.
A tree of nodes that open and close, with multiple selection, lazy loading, renaming and moves by drag.
```go
isFolder := func(k string) bool { return len(folders[k]) > 0 || k == "Documents" }
return basic.SizedBox{Width: 280, Height: 260, Child: collection.Tree[string]{
Label: "Files", Roots: folders[""], Controller: &ctrl,
ChildrenOf: func(k string) []string { return folders[k] },
HasChildren: isFolder,
IconOf: func(k string) core.Widget {
if isFolder(k) {
return basic.Icon{Path: icons.Folder(), Size: 16, Color: geom.Hex(0x2f5fd0)}
}
return basic.Icon{Path: icons.Document(), Size: 16, Color: geom.Hex(0x8a8a8e)}
},
}}
```
#### collection.PropertyGrid
Import `github.com/bankai-tensei/gowaku/widgets/collection`. Also covers collection.Property, collection.PropertyCategory, collection.PropertyEditor, collection.PropertyText, collection.PropertyBool, collection.PropertyChoice, collection.PropertyInt, collection.PropertyNumber, collection.PropertyColor, collection.PropertyCustom.
An inspector that edits properties in two columns of names and values, in categories that fold.
```go
type fit int
return basic.SizedBox{Width: 340, Child: collection.PropertyGrid{Label: "Inspector", Categories: []collection.PropertyCategory{
{Name: "General", Properties: []collection.Property{
{Name: "Name", Description: "The name of the layer.", Editor: collection.PropertyText{Value: "Header", OnChange: func(string) {}}},
{Name: "Visible", Editor: collection.PropertyBool{Value: true, OnChange: func(bool) {}}},
{Name: "Fit", Editor: collection.PropertyChoice[fit]{Value: 1, OnChange: func(fit) {}, Options: []field.DropdownOption[fit]{
{Value: 0, Label: "Fill"}, {Value: 1, Label: "Contain"},
}}},
}},
{Name: "Layout", Properties: []collection.Property{
{Name: "Width", Editor: collection.PropertyInt{Value: 320, Max: 4096, OnChange: func(int) {}}},
{Name: "Opacity", Editor: collection.PropertyNumber{Value: 0.85, Max: 1, OnChange: func(float64) {}}},
{Name: "Tint", Editor: collection.PropertyColor{Value: geom.Hex(0x2f5fd0), OnPress: func() {}}},
}},
{Name: "Advanced", Collapsed: true, Properties: []collection.Property{
{Name: "Cache", Editor: collection.PropertyBool{OnChange: func(bool) {}}},
}},
}}}
```
#### collection.Group
Import `github.com/bankai-tensei/gowaku/widgets/collection`. Also covers collection.GroupRow.
A card of rows, the stuff of settings pages and forms. The lines between rows stop short of the left edge.
```go
basic.SizedBox{Width: 420, Child: collection.Group{Title: "Playback", Children: []core.Widget{
collection.GroupRow{Label: "Shuffle", Child: control.Switch{Value: true, OnChange: func(bool) {}}},
collection.GroupRow{Label: "Repeat", Child: control.SegmentedControl{
Options: []string{"Off", "All", "One"}, Selected: 1, OnChange: func(int) {},
}},
collection.GroupRow{Label: "Crossfade", Detail: "Seconds between songs", Child: control.NumberStepper{
Value: 4, Max: 12, OnChange: func(int) {},
}},
}}}
```
### Desktop
Widgets particular to desktop applications: the menu bar, context menus, toolbars, document tabs and split panes.
#### overlay.MenuBar
Import `github.com/bankai-tensei/gowaku/widgets/overlay`. Also covers overlay.MenuItem, interact.Action, interact.Actions, interact.Shortcut.
The menu bar at the top of a window. Each `Action` holds the label, the shortcut, the check mark and whether it can run.
```go
run := func() {}
return basic.SizedBox{Width: 420, Child: overlay.MenuBar{Items: []overlay.MenuItem{
{Action: interact.Action{Label: "&File"}, Items: []overlay.MenuItem{
{Action: interact.Action{Label: "&Save", Shortcut: interact.Shortcut{Key: input.KeyS, Modifiers: input.ModControl}, OnInvoke: run}},
}},
{Action: interact.Action{Label: "&Edit"}, Items: editItems()},
{Action: interact.Action{Label: "&View"}, Items: []overlay.MenuItem{
{Action: interact.Action{Label: "Zoom &in", OnInvoke: run}},
}},
}}}
```
#### overlay.ContextMenu
Import `github.com/bankai-tensei/gowaku/widgets/overlay`.
Opens a menu over its child on a right click or the menu key.
```go
overlay.ContextMenu{Items: editItems(), Child: themed(func(th *theme.Theme) core.Widget {
return basic.Container{
Width: 240, Height: 160, Radius: th.Radius.Group, Color: th.Color.Card,
Border: paint.Stroke{Width: 1, Color: th.Color.Hair}, Padding: geom.All(theme.Space12),
Child: basic.Text{Content: "Right-click here", Style: colored(th.Text.Body, th.Color.Ink2)},
}
})}
```
#### nav.Toolbar
Import `github.com/bankai-tensei/gowaku/widgets/nav`. Also covers nav.ToolbarItem.
A row of buttons. Items that do not fit move into a menu at the end; the arrow keys move between items.
```go
run := func() {}
return basic.SizedBox{Width: 460, Child: nav.Toolbar{Label: "Format", Items: []nav.ToolbarItem{
{Action: interact.Action{Label: "Bold", OnInvoke: run, Checkable: true, Checked: true}, Icon: squareIcon()},
{Action: interact.Action{Label: "Italic", OnInvoke: run, Checkable: true}, Icon: circleIcon()},
{Action: interact.Action{Label: "Shape"}, Icon: triangleIcon()},
{Separator: true},
{Action: interact.Action{Label: "Share", OnInvoke: run}, Icon: icons.Star(), ShowLabel: true},
{Spacer: true},
{Action: interact.Action{Label: "Export", OnInvoke: run}},
}}}
```
#### nav.StatusBar
Import `github.com/bankai-tensei/gowaku/widgets/nav`. Also covers nav.StatusItem.
The band along the bottom of a window, with leading and trailing items. When narrow, items of low priority hide first.
```go
basic.SizedBox{Width: 520, Child: nav.StatusBar{
Leading: []nav.StatusItem{
{Text: "Ln 12, Col 4", Priority: 2},
{Text: "No selection"},
},
Trailing: []nav.StatusItem{
{Text: "UTF-8", Tooltip: "Encoding", OnPress: func() {}, Priority: 1},
{Text: "LF"},
{Text: "Go", Priority: 1},
},
}}
```
#### field.CommandPalette
Import `github.com/bankai-tensei/gowaku/widgets/field`. Also covers field.PaletteItem.
Finds a registered Action by fuzzy search and runs it. Ctrl+Shift+P opens it.
```go
run := func() {}
actions := []interact.Action{
{Label: "&New File", OnInvoke: run},
{Label: "&Open File...", OnInvoke: run},
{Label: "&Save", Shortcut: interact.Shortcut{Key: input.KeyS, Modifiers: input.ModControl}, OnInvoke: run},
{Label: "Save &As...", OnInvoke: run},
{Label: "&Export..."},
{Label: "Toggle &Sidebar", Checkable: true, Checked: true, OnInvoke: run},
}
return basic.SizedBox{Width: 600, Height: 440, Child: field.CommandPalette{
Actions: actions,
Child: interact.Actions{Actions: actions, Child: basic.Builder{Content: func(ctx core.BuildContext) core.Widget {
return basic.Align{Alignment: layout.AlignTopLeft, Child: control.Button{
Label: "Open palette", OnPress: func() { field.OpenCommandPalette(ctx) },
}}
}}},
}}
```
#### nav.TabBar
Import `github.com/bankai-tensei/gowaku/widgets/nav`. Also covers nav.TabItem, nav.TabGroup, nav.TabTearOff.
Document tabs that close, reorder, and tear off into another window. A tab with unsaved changes shows a dot, which turns into the close button under the pointer.
```go
icon := icons.Document()
return basic.SizedBox{Width: 520, Child: nav.TabBar{
Label: "Files", Selected: 1,
Tabs: []nav.TabItem{
{Key: "readme", Label: "README.md", Icon: icon, Modified: true},
{Key: "main", Label: "main.go", Icon: icon},
{Key: "long", Label: "A long name that does not fit.txt", Icon: icon},
},
OnSelect: func(int) {}, OnClose: func(int) {}, OnNew: func() {}, OnMove: func(int, int) {},
}}
```
#### control.SplitPane
Import `github.com/bankai-tensei/gowaku/widgets/control`. Also covers control.SplitCollapse.
Two panes divided by a draggable divider. One of them can fold away.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.Container{
Width: 480, Height: 200, Color: th.Color.Card, Radius: th.Radius.Group,
Border: paint.Stroke{Width: 1, Color: th.Color.Hair},
Child: control.SplitPane{
Position: 160, Pixels: true, MinFirst: 120, MinSecond: 200, Collapsible: control.SplitCollapseFirst,
First: basic.Container{Color: th.Color.Sidebar, Radius: th.Radius.Group, Padding: geom.All(theme.Space12),
Child: basic.Text{Content: "Sidebar"}},
Second: basic.Padding{Insets: geom.All(theme.Space12), Child: basic.Text{Content: "Drag the divider, or press Enter on it to fold the sidebar."}},
},
}
})
```
#### nav.DockLayout
Import `github.com/bankai-tensei/gowaku/widgets/nav`. Also covers nav.DockPanel, nav.DockController, nav.DockArrangement, nav.DockNode, nav.DockZone.
Arranges groups of tabs as an IDE does. Dragging a divider resizes, and dragging a tab moves it between groups or to an edge, keeping its state. The arrangement saves and restores as a `DockArrangement`.
```go
panels := []nav.DockPanel{
{ID: "files", Title: "Files", Build: note("go.mod\nmain.go\ndock.go")},
{ID: "main", Title: "main.go", Closable: true, Build: note("package main")},
{ID: "dock", Title: "dock.go", Closable: true, Build: note("package main")},
{ID: "output", Title: "Output", Closable: true, Build: note("$ go build ./...")},
}
start := nav.DockArrangement{Root: nav.DockNode{
Weights: []float32{1, 3},
Children: []nav.DockNode{
{Panels: []string{"files"}},
{Axis: layout.Vertical, Weights: []float32{2, 1}, Children: []nav.DockNode{
{Panels: []string{"main", "dock"}, Active: "main"},
{Panels: []string{"output"}},
}},
},
}}
return basic.SizedBox{Width: 560, Height: 300, Child: nav.DockLayout{Panels: panels, Default: start, Label: "Panels"}}
```
### Layout
Widgets that place and size their children. Spacing uses the even steps of `theme.Space*`.
#### basic.Row
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Lays out its children in a row. `Main` and `Cross` align them, and `Spacing` puts gaps between.
```go
basic.SizedBox{Width: 360, Child: basic.Row{Spacing: theme.Space8, Main: layout.MainSpaceBetween, Children: []core.Widget{
tile("A", 64, 40), tile("B", 96, 40), tile("C", 64, 40),
}}}
```
#### basic.Column
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Lays out its children in a column. `Size: layout.MainMin` shrinks it to its content.
```go
basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space8, Children: []core.Widget{
tile("First", 160, 32), tile("Second", 120, 32), tile("Third", 200, 32),
}}
```
#### basic.Flex
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
The `Row` and `Column` with its axis as a field, for a direction chosen at run time.
```go
axis := layout.Vertical // chosen at run time, as by the width of the window
return basic.Flex{Axis: axis, Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
tile("Flex", 120, 32), tile("picks its axis", 160, 32), tile("at run time", 140, 32),
}}
```
#### basic.Expanded
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Fills the rest of a `Row` or `Column`, shared by the weights of `Flex`.
```go
basic.SizedBox{Width: 520, Child: basic.Row{Spacing: theme.Space8, Children: []core.Widget{
tile("Fixed", 80, 40),
basic.Expanded{Child: tile("Expanded takes the rest", 0, 40)},
basic.Expanded{Flex: 2, Child: tile("Flex 2", 0, 40)},
}}}
```
#### basic.Flexible
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Shares the free space, but the child may stay smaller than its share. `Fit: layout.FitTight` makes it an `Expanded`.
```go
basic.SizedBox{Width: 420, Child: basic.Row{Spacing: theme.Space8, Children: []core.Widget{
basic.Flexible{Child: tile("Flexible stays small", 140, 40)},
basic.Flexible{Fit: layout.FitTight, Child: tile("Tight fills its share", 60, 40)},
}}}
```
#### basic.Stack
Import `github.com/bankai-tensei/gowaku/widgets/basic`. Also covers basic.Positioned.
Paints its children on top of each other. `Positioned` places a child from the edges.
```go
basic.SizedBox{Width: 240, Height: 140, Child: basic.Stack{Children: []core.Widget{
tile("Below", 200, 120),
basic.Positioned{Left: 120, Top: 70, Child: tile("On top", 110, 60)},
basic.Positioned{AnchorRight: true, Right: 0, Top: 0, Child: control.Badge{Count: 2}},
}}}
```
#### basic.PositionedFill
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Stretches a child over the whole `Stack`, whose size the other children decide.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.Stack{Children: []core.Widget{
basic.Image{Source: photo(), Width: 240},
basic.PositionedFill{Insets: geom.All(theme.Space8), Child: basic.Container{
Radius: th.Radius.Control, Border: paint.Stroke{Width: 2, Color: geom.RGBA(1, 1, 1, 0.9)},
}},
}}
})
```
#### basic.Wrap
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
A `Row` that starts a new run when the next child does not fit, for tags and chips.
```go
words := []string{"Go", "GPU", "desktop", "cgo-free", "Flutter-style", "widgets", "Japanese text", "accessibility"}
chips := make([]core.Widget, len(words))
for i, w := range words {
chips[i] = control.Chip{Label: w}
}
return basic.SizedBox{Width: 300, Child: basic.Wrap{Spacing: theme.Space8, RunSpacing: theme.Space8, Children: chips}}
```
#### basic.Grid
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Lays out tiles in columns of the same width: a fixed number, or as many as a minimum width allows.
```go
tiles := make([]core.Widget, 6)
for i := range tiles {
tiles[i] = tile("Tile "+strconv.Itoa(i+1), 0, 0)
}
return basic.SizedBox{Width: 320, Child: basic.Grid{Columns: 3, Spacing: theme.Space8, RunSpacing: theme.Space8, TileHeight: 48, Children: tiles}}
```
#### basic.Padding
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Puts room around its child.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.Container{Color: th.Color.Fill, Radius: th.Radius.Control, Child: basic.Padding{
Insets: geom.Insets{Left: 24, Top: 12, Right: 24, Bottom: 12},
Child: tile("Child", 120, 40),
}}
})
```
#### basic.Align
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Places its child within the space it is given, from 0 to 1 on each axis (not -1 to 1 as in Flutter).
```go
themed(func(th *theme.Theme) core.Widget {
box := func(a layout.Alignment, label string) core.Widget {
return basic.Container{Width: 120, Height: 80, Radius: th.Radius.Control, Color: th.Color.Fill,
Child: basic.Align{Alignment: a, Child: tile(label, 48, 24)}}
}
return basic.Row{Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
box(layout.AlignTopLeft, "top left"), box(layout.AlignCenter, "center"), box(layout.AlignBottomRight, "end"),
}}
})
```
#### basic.Center
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Places its child in the middle.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.Container{Width: 240, Height: 100, Radius: th.Radius.Control, Color: th.Color.Fill,
Child: basic.Center{Child: tile("Centered", 100, 32)}}
})
```
#### basic.SizedBox
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Forces a width, a height or both. Without a child it is an empty gap.
```go
basic.Row{Size: layout.MainMin, Spacing: theme.Space8, Cross: layout.CrossStart, Children: []core.Widget{
basic.SizedBox{Width: 140, Height: 48, Child: tile("140 by 48", 0, 0)},
basic.SizedBox{Width: 24}, // an empty gap
basic.SizedBox{Width: 80, Height: 80, Child: tile("80 by 80", 0, 0)},
}}
```
#### basic.ConstrainedBox
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Adds minimum and maximum sizes to its child.
```go
basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space8, Children: []core.Widget{
basic.ConstrainedBox{MinWidth: 160, Child: control.Button{Label: "OK", OnPress: func() {}}},
basic.ConstrainedBox{MaxWidth: 200, Child: basic.Text{Content: "MaxWidth makes a long line of text wrap inside 200 pixels."}},
}}
```
#### basic.Container
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
A box that combines size, padding, color, gradient, border, corners and shadows.
```go
basic.Row{Size: layout.MainMin, Spacing: theme.Space16, Children: []core.Widget{
basic.Container{Width: 120, Height: 72, Radius: 12, Color: geom.Hex(0x2f5fd0),
Shadows: []paint.BoxShadow{{Color: geom.RGBA(0, 0, 0, 0.25), Blur: 12, Offset: geom.Offset{Y: 4}}}},
basic.Container{Width: 120, Height: 72, Radius: 12, Border: paint.Stroke{Width: 1.5, Color: geom.Hex(0x2f5fd0)},
Padding: geom.All(12), Child: basic.Text{Content: "Border"}},
basic.Container{Width: 120, Height: 72, Radius: 36, Gradient: &paint.Gradient{
End: geom.Offset{X: 120, Y: 72}, StartColor: geom.Hex(0x7b8cff), EndColor: geom.Hex(0x2f5fd0),
}},
}}
```
#### basic.DecoratedBox
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Paints a `layout.Decoration` behind its child.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.DecoratedBox{
Decoration: layout.Decoration{Color: th.Color.Card, Radius: th.Radius.Group, Border: &paint.Stroke{Width: 1, Color: th.Color.Hair}},
Child: basic.Padding{Insets: geom.All(theme.Space16), Child: basic.Text{Content: "DecoratedBox paints behind its child"}},
}
})
```
#### basic.Scroll
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Shows a child larger than itself, moved by the wheel and a scroll bar. Its parent must bound its size. `Reverse` starts it at the right end, or the bottom, so that a long vertical text opens at its first column. A `ScrollController` reads and sets the offset from code.
```go
lines := make([]core.Widget, 12)
for i := range lines {
lines[i] = basic.Text{Content: "Line " + strconv.Itoa(i+1) + " of a column taller than its box"}
}
return basic.SizedBox{Width: 300, Height: 140, Child: basic.Scroll{Child: basic.Column{
Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space4, Children: lines,
}}}
```
#### basic.CustomLayout
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Arranges its children with the algorithm of a `layout.Delegate`.
```go
basic.CustomLayout{Delegate: diagonal{step: 56}, Children: []core.Widget{
tile("One", 96, 32), tile("Two", 96, 32), tile("Three", 96, 32), tile("Four", 96, 32),
}}
```
#### basic.LayoutBuilder
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Builds its content with the constraints its parent gives it, to change with the room it has, such as one pane above the other when narrow and side by side when wide. The content is built again only when the constraints change or the parent rebuilds.
```go
panes := basic.LayoutBuilder{Content: func(_ core.BuildContext, c layout.Constraints) core.Widget {
if c.MaxW < 300 { // narrow: one above the other
return basic.Column{Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
tile("List", c.MaxW, 40), tile("Detail", c.MaxW, 40),
}}
}
return basic.Row{Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
tile("List", 120, 88), tile("Detail", c.MaxW-120-theme.Space8, 88),
}}
}}
return basic.Row{Size: layout.MainMin, Spacing: theme.Space16, Cross: layout.CrossStart, Children: []core.Widget{
basic.SizedBox{Width: 160, Child: panes},
basic.SizedBox{Width: 320, Child: panes},
}}
```
#### basic.AspectRatio
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Sizes its child to a width over height of `Ratio`. It takes all the width it may, or all the height where that is too tall. Tight constraints leave no room for the ratio, so put it in a `Center`.
```go
// box is a 200 by 120 frame with the largest rectangle of ratio in it.
box := func(ratio float32, label string) core.Widget {
return basic.Container{
Width: 200, Height: 120, Padding: geom.All(theme.Space8),
Radius: th.Radius.Control, Border: paint.Stroke{Width: 1, Color: th.Color.Hair},
Child: basic.Center{Child: basic.AspectRatio{Ratio: ratio, Child: tile(label, 0, 0)}},
}
}
return basic.Row{Size: layout.MainMin, Spacing: theme.Space16, Children: []core.Widget{
box(16.0/9, "16:9"), // as wide as the frame
box(1, "1:1"), // as tall as the frame
}}
```
### Effects and painting
Widgets that change how their child looks, and the ones that paint on their own. None changes the layout.
#### basic.Opacity
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Paints its child with a uniform transparency. At 0 the pointer, the focus and assistive technology skip it.
```go
accent := geom.Hex(0x2f5fd0)
return basic.Row{Size: layout.MainMin, Spacing: theme.Space12, Children: []core.Widget{
swatch("1.0", accent),
basic.Opacity{Opacity: 0.6, Child: swatch("0.6", accent)},
basic.Opacity{Opacity: 0.3, Child: swatch("0.3", accent)},
}}
```
#### basic.Blend
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Combines its child as one picture with what is below, as mix-blend-mode does in CSS.
```go
backdrop := basic.Container{Width: 280, Height: 80, Radius: 12, Gradient: &paint.Gradient{
End: geom.Offset{X: 280}, StartColor: geom.Hex(0xfde047), EndColor: geom.Hex(0x10b981),
}}
return basic.Stack{Children: []core.Widget{
backdrop,
basic.Positioned{Left: 10, Child: rings()},
basic.Positioned{Left: 150, Child: basic.Blend{Mode: paint.BlendMultiply, Child: rings()}},
}}
```
#### basic.BackdropFilter
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Blurs what is painted below its box, then paints its child: frosted glass.
```go
basic.Stack{Children: []core.Widget{
busy(320, 120),
basic.Positioned{Left: 40, Top: 20, Child: basic.BackdropFilter{Sigma: 12, Radius: 16, Child: basic.Container{
Width: 240, Height: 80, Radius: 16, Color: geom.RGBA(1, 1, 1, 0.4), Padding: geom.All(16),
Child: basic.Text{Content: "Frosted glass", Style: text.Style{Size: 16, Weight: 600, Color: geom.Hex(0x111111)}},
}}},
}}
```
#### basic.ImageFiltered
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Draws its child blurred, as filter: blur() does in CSS.
```go
basic.Row{Size: layout.MainMin, Spacing: theme.Space24, Children: []core.Widget{
basic.Image{Source: photo(), Width: 140},
basic.ImageFiltered{Sigma: 3, Child: basic.Image{Source: photo(), Width: 140}},
}}
```
#### basic.ShaderMask
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Draws its child through a custom shader: shimmers, ripples, tints.
```go
// shaders.Shimmer is a shader of examples/shader, made by cmd/gowaku-shader.
shimmer := paint.ShaderParams{0.5, 0.2, 0.35, 0, 1, 1, 1, 0.85}
return basic.ShaderMask{Shader: shaders.Shimmer, Params: shimmer, Time: 1250 * time.Millisecond, Animate: true,
Child: basic.Text{Content: "gowaku", Style: text.Style{Size: 56, Weight: 700, Color: geom.Hex(0x2f5fd0)}},
}
```
#### basic.Transform
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Turns, slants or stretches its child with an affine transform. The pointer and assistive technology follow the picture.
```go
basic.Row{Size: layout.MainMin, Spacing: theme.Space28, Children: []core.Widget{
basic.Rotate(0.2, swatch("Rotate", geom.Hex(0x2f5fd0))),
basic.Skew(0.3, 0, swatch("Skew", geom.Hex(0x10a37f))),
basic.Transform{Transform: geom.Scaling(1.2, 0.8), Origin: layout.AlignCenter, Child: swatch("Scale", geom.Hex(0xd04a2f))},
}}
```
#### basic.Translate
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Paints its child moved by a fraction of its size: the cheap move of a transition.
```go
basic.Column{Size: layout.MainMin, Cross: layout.CrossStart, Spacing: theme.Space8, Children: []core.Widget{
tile("In place", 140, 32),
basic.Translate{X: 0.3, Child: tile("X: 0.3 of its width", 140, 32)},
}}
```
#### basic.ClipRRect
Import `github.com/bankai-tensei/gowaku/widgets/basic`. Also covers basic.ClipRect.
Cuts what its child paints to its box; `ClipRRect` rounds the corners, to the theme's card corners when Radius is 0. The pointer reaches the child only inside the cut shape.
```go
basic.Row{Size: layout.MainMin, Spacing: 40, Children: []core.Widget{
picture,
basic.ClipRect{Child: picture},
basic.ClipRRect{Child: picture},
}}
```
#### basic.Scale
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Paints its child scaled around `Origin`: the cheap zoom of a transition.
```go
basic.Row{Size: layout.MainMin, Spacing: theme.Space24, Children: []core.Widget{
tile("1.0", 80, 48),
basic.Scale{Scale: 0.8, Origin: layout.AlignCenter, Child: tile("0.8", 80, 48)},
basic.Scale{Scale: 1.2, Origin: layout.AlignCenter, Child: tile("1.2", 80, 48)},
}}
```
#### control.CustomPaint
Import `github.com/bankai-tensei/gowaku/widgets/control`.
Paints with a `layout.Painter`, for charts, meters and other shapes no widget offers.
```go
control.CustomPaint{Width: 240, Height: 100, Painter: layout.PainterFunc(func(cv *paint.Canvas, sz geom.Size) {
bars := []float32{0.4, 0.7, 0.5, 0.9, 0.6, 0.8}
w := sz.W / float32(len(bars))
for i, v := range bars {
r := geom.Rect{X: float32(i)*w + 4, Y: sz.H * (1 - v), W: w - 8, H: sz.H * v}
cv.DrawRRect(geom.RRectAll(r, 4), paint.Paint{Color: geom.Hex(0x2f5fd0).WithAlpha(0.4 + v*0.6)})
}
var line paint.Path
line.MoveTo(0, sz.H*0.7)
line.QuadTo(sz.W/2, 0, sz.W, sz.H*0.4)
cv.DrawPath(&line, paint.Paint{Stroke: &paint.Stroke{Width: 2, Color: geom.Hex(0xd04a2f)}})
})}
```
#### basic.RepaintBoundary
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Keeps the picture of its child apart, so a change on one side does not repaint the other.
```go
// A meter that changes on every frame keeps its repaints to itself.
return basic.RepaintBoundary{Child: basic.SizedBox{Width: 200, Child: control.ProgressBar{Value: 0.45, Label: "Level"}}}
```
#### interact.FocusRing
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Draws the pale 3px focus ring of the standard controls, for controls of your own.
```go
themed(func(th *theme.Theme) core.Widget {
return interact.FocusRing{Visible: true, Radius: th.Radius.Control, Child: basic.Container{
Width: 140, Height: 36, Radius: th.Radius.Control, Color: th.Color.AccentTint,
Child: basic.Center{Child: basic.Text{Content: "Focus ring", Style: colored(th.Text.Control, th.Color.AccentInk)}},
}}
})
```
### Animation
Widgets that move to new values over time. When the OS asks for less motion they jump instead.
#### basic.AnimatedContainer
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
A `Container` that moves to new colors, sizes, padding, corners, borders and shadows over time.
```go
expanded := true // a field of the State; SetState changes it
w, c := float32(120), geom.Hex(0x8a8a8e)
if expanded {
w, c = 220, geom.Hex(0x2f5fd0)
}
return basic.AnimatedContainer{Duration: 250 * time.Millisecond, Width: w, Height: 48, Radius: 24, Color: c}
```
#### basic.AnimatedOpacity
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
An `Opacity` that fades to a new value.
```go
visible := false // a field of the State
var o float32 = 1
if !visible {
o = 0.4
}
return basic.AnimatedOpacity{Opacity: o, Child: swatch("Fading", geom.Hex(0x2f5fd0))}
```
#### basic.AnimatedAlign
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
An `Align` that moves to a new alignment.
```go
themed(func(th *theme.Theme) core.Widget {
return basic.Container{Width: 280, Height: 56, Radius: 28, Color: th.Color.Fill, Padding: geom.All(4),
Child: basic.AnimatedAlign{Alignment: a, Child: basic.Container{Width: 48, Height: 48, Radius: 24, Color: th.Color.Accent}}}
})
```
#### basic.AnimatedPositioned
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
A `Positioned` that moves to a new place in its `Stack`.
```go
moved := true // a field of the State
var left float32 = 8
if moved {
left = 160
}
return basic.SizedBox{Width: 260, Height: 80, Child: basic.Stack{Children: []core.Widget{
tile("", 260, 80),
basic.AnimatedPositioned{Left: left, Top: 16, Child: swatch("Moves", geom.Hex(0x2f5fd0))},
}}}
```
#### basic.AnimatedSwitcher
Import `github.com/bankai-tensei/gowaku/widgets/basic`. Also covers basic.SwitcherTransition.
Crossfades or slides from an old child to a new one. Tell children of one type apart with `core.Keyed`.
```go
page := 1 // a field of the State
return basic.AnimatedSwitcher{
Duration: 250 * time.Millisecond,
Transition: basic.SlideTransition(0.04, 0),
Child: core.Keyed(page, tile("Page "+strconv.Itoa(page+1), 200, 64)),
}
```
#### nav.Hero
Import `github.com/bankai-tensei/gowaku/widgets/nav`.
When a `Navigator` changes pages, the child with the same `Tag` flies from one place to the other. The picture shows the page after landing.
```go
// In the row of the list:
row := basic.Row{Spacing: theme.Space12, Children: []core.Widget{nav.Hero{Tag: 1, Child: icon}, basic.Text{Content: "Trip to Kyoto"}}}
// On the page the row opens, with the same Tag:
header := basic.Row{Spacing: theme.Space12, Children: []core.Widget{nav.Hero{Tag: 1, Child: big}, basic.Text{Content: "Trip to Kyoto"}}}
```
### Input handling and accessibility
Widgets that draw nothing and add pointer, keyboard, drag and assistive technology behavior to their child. They have examples but no pictures.
#### interact.GestureDetector
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Reports taps, double taps, secondary taps, long presses, drags (start, update, end) and pinches on its child. A press that moves only a little stays a tap. `OnTapDownAt`, `OnTapAt` and `OnSecondaryTapAt` tell the modifier keys held along with the place, for a click with Shift or Ctrl.
```go
interact.GestureDetector{
OnTap: func() { /* select */ },
OnDoubleTap: func() { /* open */ },
OnSecondaryTapAt: func(layout.Tap) { /* a menu where the press was */ },
OnLongPress: func(_ geom.Offset, _ input.PointerDevice) { /* more choices */ },
OnDragUpdate: func(_, _ geom.Offset) { /* move by the delta */ },
Child: tile("Tap me", 120, 40),
}
```
#### interact.MouseRegion
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Reports the pointer entering and leaving, and sets the cursor over its child.
```go
interact.MouseRegion{
Cursor: input.CursorHand,
OnEnter: func() { /* show the controls */ },
OnExit: func() { /* hide them */ },
Child: tile("Hover", 120, 40),
}
```
#### interact.Listener
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Hands every pointer event over its child to a function, with the pressure of a pen, for drawing.
```go
interact.Listener{
OnPointer: func(e *core.PointerEvent) {
switch e.Kind {
case core.PointerDown:
// start a stroke at e.Pos, as wide as e.Pressure for a pen
case core.PointerMove:
// add e.Pos to the stroke while one is going
}
},
Child: basic.SizedBox{Width: 300, Height: 200},
}
```
#### interact.Focus
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Lets its child take the keyboard. Tab moves in the order of painting.
```go
interact.Focus{
Enabled: true,
OnKey: func(e *core.KeyEvent) bool {
return e.Key == input.KeySpace // handled; false passes it on
},
OnShowFocus: func(_ bool) { /* show a FocusRing while true */ },
Child: tile("Focusable", 120, 40),
}
```
#### basic.IgnorePointer
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Lets the pointer pass through its child to what is below.
```go
basic.Stack{Children: []core.Widget{
control.Button{Label: "Still clickable", OnPress: func() {}},
basic.IgnorePointer{Child: basic.Container{Width: 160, Height: 30, Color: geom.RGBA(1, 1, 1, 0.2)}},
}}
```
#### interact.Draggable
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Drags data out of its child: to a `DragTarget`, another window or another program.
```go
interact.Draggable{
Data: input.DragData{Text: "notes.txt"},
Allowed: input.DropCopy | input.DropMove,
OnDragEnd: func(_ input.DropEffect) { /* remove the row on DropMove */ },
Child: tile("notes.txt", 120, 32),
}
```
#### interact.DragTarget
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Takes text or files dropped on its child, from this window or from programs such as Explorer or a browser.
```go
interact.DragTarget{
Kinds: input.DataFiles,
OnHover: func(_ bool) { /* light up while true */ },
OnDrop: func(_ input.DragData, _ geom.Offset) { /* open the files */ },
Child: tile("Drop files here", 240, 120),
}
```
#### interact.Semantics
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Describes its child to assistive technology and does what a screen reader asks. The standard controls have their own.
```go
interact.Semantics{
Role: semantics.RoleButton, Label: "Play", Hint: "Plays the album from the start",
OnTap: func() { /* play */ },
Child: basic.Icon{Path: triangleIcon()},
}
```
#### interact.ExcludeSemantics
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Hides its child from assistive technology, as aria-hidden does, for text that only decorates, such as the initial in an avatar. It is still drawn and still takes the pointer.
```go
basic.Row{Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
// The initial only decorates; the name beside it is read.
interact.ExcludeSemantics{Child: basic.Text{Content: "S"}},
basic.Text{Content: "Sato Hana"},
}}
```
#### interact.FocusTraversalOrder
Import `github.com/bankai-tensei/gowaku/widgets/interact`.
Sets where the controls below it come in the order of Tab, as tabindex does in HTML.
```go
basic.Column{Children: []core.Widget{
field.Input{Label: "Details", OnChange: func(string) {}},
// Tab reaches the search field first, wherever it is painted.
interact.FocusTraversalOrder{Order: 1, Child: field.Search{OnChange: func(string) {}}},
}}
```
### Tree services
Widgets that hand the theme, the window, the words and a place for overlays to the widgets below. `gowaku.Run` puts each at the root of a window; use them to change a part.
#### basic.Builder
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Builds its content with the `BuildContext` of its place, to read what is above, such as the theme.
```go
basic.Builder{Content: func(ctx core.BuildContext) core.Widget {
th := basic.ThemeOf(ctx)
return basic.Text{Content: "Builder reads the theme above it", Style: colored(th.Text.Title, th.Color.AccentInk)}
}}
```
#### basic.Theme
Import `github.com/bankai-tensei/gowaku/widgets/basic`.
Gives the widgets below it their look, for a part of the window with another accent.
```go
basic.Builder{Content: func(ctx core.BuildContext) core.Widget {
green := theme.FromAccent(geom.Hex(0x1f8a5b)).For(basic.MediaQueryOf(ctx).Brightness)
return basic.Row{Size: layout.MainMin, Spacing: theme.Space16, Children: []core.Widget{
control.Button{Label: "Window accent", Style: control.ButtonPrimary, OnPress: func() {}},
basic.Theme{Data: green, Child: basic.Row{Size: layout.MainMin, Spacing: theme.Space8, Children: []core.Widget{
control.Button{Label: "Green accent", Style: control.ButtonPrimary, OnPress: func() {}},
control.Switch{Value: true, Label: "Green", OnChange: func(bool) {}},
}}},
}}
}}
```
#### basic.MediaQuery
Import `github.com/bankai-tensei/gowaku/widgets/basic`. Also covers basic.MediaQueryData.
Tells the widgets below about the window: brightness, scale, reduced motion, locale and the size of its content area. A widget that reads the size with `basic.WindowSizeOf` is rebuilt when the window is resized, and only it. Here the British locale starts the week on Monday.
```go
basic.Builder{Content: func(ctx core.BuildContext) core.Widget {
data := basic.MediaQueryOf(ctx)
data.Locale = language.BritishEnglish // weeks start on Monday
return basic.MediaQuery{Data: data, Child: field.Calendar{
Value: time.Date(2026, time.November, 9, 0, 0, 0, 0, time.UTC), OnChange: func(time.Time) {},
}}
}}
```
#### basic.Localizations
Import `github.com/bankai-tensei/gowaku/widgets/basic`. Also covers basic.Strings.
Hands the standard widgets the words of their locale. Japanese and English are bundled; add `Strings` for others.
```go
german := &basic.Strings{Language: language.German, Today: "Heute", Clear: "Löschen"}
return basic.Localizations{Strings: []*basic.Strings{german}, Child: field.DatePicker{
ShowToday: true, ShowClear: true, OnChange: func(time.Time) {},
}}
```
#### overlay.Overlay
Import `github.com/bankai-tensei/gowaku/widgets/overlay`. Also covers overlay.Entry, overlay.Host.
A place to show entries on top of its child. Dialogs and menus show there too.
```go
basic.Builder{Content: func(ctx core.BuildContext) core.Widget {
return control.Button{Label: "Show a hint", OnPress: func() {
var entry *overlay.Entry
entry = overlay.Of(ctx).Insert(func() core.Widget {
return basic.Positioned{Left: 16, Top: 16, Child: control.Button{Label: "Close the hint", OnPress: func() { entry.Remove() }}}
})
}}
}}
```