From d828c8b2b0f71fcd59f287e1fc89656c86ff0273 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 17:03:09 +0800 Subject: [PATCH 01/15] fix(ui): tell a disabled Base it is disabled, and compare every Base with its control Box.Disabled did not reach the hit of an element given Hit or HitWith, so ButtonBase, CheckboxBase and SwitchBase stayed enabled to assistive technology and in the Tab order while the control with a look did not. Merge it into the hit's options. Add a test that declares each styled control and its Base in every state and compares what they tell the pointer, the keyboard and assistive technology, and one that fails for a page Base that is in neither that comparison nor an explained list. Document how a control and its Base are kept the same and what adding a control touches. --- docs/README.md | 2 + docs/maintaining-controls.md | 75 +++++++++++++++++ ui/base_parity_test.go | 158 +++++++++++++++++++++++++++++++++++ ui/base_scan_test.go | 68 +++++++++++++++ ui/box.go | 4 +- ui/page_bases.go | 6 +- ui/paint.go | 7 +- 7 files changed, 315 insertions(+), 5 deletions(-) create mode 100644 docs/maintaining-controls.md create mode 100644 ui/base_parity_test.go create mode 100644 ui/base_scan_test.go diff --git a/docs/README.md b/docs/README.md index 0e1a3cc63..e4f5bf82c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -31,6 +31,8 @@ mentions every exported method and theme field. ## What is here +- [maintaining-controls.md](maintaining-controls.md) — how a control and its Base are kept the + same, and what adding a control touches. - [conformance.md](conformance.md) — the scenarios that need a real window on a real platform, and the ones that still need eyes. - [accessibility.md](accessibility.md) — the semantic tree and native diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md new file mode 100644 index 000000000..c58ed8fbf --- /dev/null +++ b/docs/maintaining-controls.md @@ -0,0 +1,75 @@ +# Maintaining controls + +How a control is built, what keeps its two forms the same, and what adding one touches. +Written from the code and from the history of earlier additions; where a step is a +convention rather than something a test checks, it says so. + +## Two forms of one control + +A control that ships with a look has a **styled form** and a **Base**: + +- `ui.Button`, `ui.Checkbox`, `ui.Select`, … take the theme's look. +- `ui.ButtonBase`, `ui.CheckboxBase`, `ui.SelectBase`, … do everything the control does + (pointer, keyboard, focus, value binding, what assistive technology is told) and paint + nothing, so an application with a look of its own builds on them and does not copy a + behavior. They are in `ui/page_bases.go` (page level) and `ui/bases.go`, `ui/select.go`, + `ui/slider.go`, `ui/frame.go`, `ui/field.go` (frame level). + +The two forms are the same control. What differs is the look and nothing else. + +### How that is kept true + +- `TestStyledControlsDeclareWhatTheirBasesDeclare` (`ui/base_parity_test.go`) declares each + styled control and its Base in every state a caller can put it in (on, off, disabled, + chosen) and compares what each tells the pointer, the keyboard and assistive technology: + role, name, value, checked, mixed, selected, expanded, focusable, disabled, range. +- `TestEveryPageBaseIsComparedOrExplained` (`ui/base_scan_test.go`) fails for a page Base + that is in neither that comparison nor the list of Bases without a styled form, so a new + Base cannot be added without deciding. +- `TestEveryRemainingBaseIsItsControlWithoutALook` (`ui/base_contract_test.go`) checks that + a Base paints nothing and declares one focusable hit with its role and state. + +### Where the behavior lives + +Select, Slider, Input, Textarea and Field are built as `X = XBase` plus the theme's look +(`flagThemed`), so their behavior is written once. Button, Checkbox, Switch and Tabs are +separate code paths from their Bases: the styled form is painted by `components.BeginX`, +which declares the hit itself, and the Base declares it again in `ui/bases.go`. The parity +test is what keeps those two declarations equal until they share one. + +## Where a control's look is decided + +The look of a control is a recipe in `components` (`components/button.go`, …). Variants and +sizes of a styled control are chosen in `ui` (for a button, `Box.Outline`, `Box.Small`, and +the switch in `frame.paintButton`) and drawn by the recipe. A change to how a control looks +belongs in the recipe; a change to what it does belongs in `ui`. + +## Adding a control + +Each step names the file to look at; the tests listed are the ones that fail when it is +missed. + +1. **Recipe** — `components/.go`, one component per file, with its test and its look + for light and dark themes. Run `go generate ./cmd/viva` (the installable copies and + `cmd/viva/components_gen.go` are generated; `go run ./tools/componentgen -check` fails + when they are stale). +2. **Page control** — in `ui`: a node kind and constructor on the frame (`ui/frame.go`), its + layout (`ui/layout.go`) and paint (`ui/paint.go`), the page function and its control kind + (`ui/elements.go`, `ui/page.go`). Look at how `Switch` is wired and search for `kindSwitch` + and `pkSwitch` to see every place a kind appears. +3. **Base** — add the Base in `ui/bases.go` and `ui/page_bases.go`, and a row for it in + `TestStyledControlsDeclareWhatTheirBasesDeclare` and `comparedWithTheirStyledForm`. + `TestEveryPageBaseIsComparedOrExplained` fails until you do. +4. **Guide and docs** — every exported `Box` method must appear in + `cmd/viva/initfiles/AGENTS.md.txt` (`ui/guide_test.go`), and a program shown in a guide is + the one in `examples/guides` (`website`: `npm run sync:examples`). +5. **Catalog** — a demo in `internal/componentdemo`, registered in `state.go` and the + catalog, so the component browser shows it. +6. **Cost** — a benchmark for the declaration, and a zero-allocation check for a warm + repaint (see `TestSelectDisabledOptionsDeclareWithoutAllocating` for the form). + +## Where the packages stop + +`TestImportDirections` (`internal/layering`) fails when `gfx`, `text`, `components`, `ui` or +`app` imports a package above it. `components` paints into a `gfx.Canvas` and does not import +`ui`; `ui` paints its controls with `components`. diff --git a/ui/base_parity_test.go b/ui/base_parity_test.go new file mode 100644 index 000000000..9151d40f2 --- /dev/null +++ b/ui/base_parity_test.go @@ -0,0 +1,158 @@ +package ui_test + +import ( + "fmt" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// semantics is what a control tells the pointer, the keyboard and assistive +// technology it is. A control and its Base must declare the same, because a +// restyled control is the same control: the look is the only thing that differs. +type semantics struct { + Role gfx.Role + Label, Value string + Checked, Mixed, Selected bool + Expanded, Expandable bool + Focusable, Disabled bool + Multiline, ReadOnly bool + Secure bool + Range gfx.ValueRange +} + +func semanticsOf(h gfx.Hit) semantics { + return semantics{ + Role: h.Role, Label: h.Label, Value: h.Value, + Checked: h.Checked, Mixed: h.Mixed, Selected: h.Selected, + Expanded: h.Expanded, Expandable: h.Expandable, + Focusable: h.Focusable, Disabled: h.Disabled, + Multiline: h.Multiline, ReadOnly: h.ReadOnly, Secure: h.Secure, + Range: h.Range, + } +} + +// declared is the semantics of what a page declares, in paint order: the controls +// themselves, not the labels painted beside them nor the backdrops under overlays. +func declared(t *testing.T, view func(ui.C)) []semantics { + t.Helper() + d := openPage(t, view) + var out []semantics + for _, h := range d.driver.Snapshot().Hits { + if h.IsLabel || h.Backdrop || h.Block || h.ID.IsZero() { + continue + } + out = append(out, semanticsOf(h)) + } + return out +} + +func page(body func(c ui.C)) func(ui.C) { + return func(c ui.C) { ui.Column(c).Pad(16).Gap(8).Children(func() { body(c) }) } +} + +// Every styled control that has a Base declares what the Base declares, in each +// state a caller can put it in. A new Base, or a new state, belongs in this table: +// base_scan_test.go fails for a Base that is in neither this table nor its list of +// Bases without a styled twin. +func TestStyledControlsDeclareWhatTheirBasesDeclare(t *testing.T) { + choices := []string{"Small", "Large"} + for _, state := range []struct { + name string + on bool + disabled bool + }{{"off", false, false}, {"on", true, false}, {"disabled off", false, true}, {"disabled on", true, true}} { + on, disabled := state.on, state.disabled + // The label Checkbox and Switch put beside the box is the name the box + // gets; CheckboxBase and SwitchBase are given the same name. + pairs := []struct { + name string + styled, base func(ui.C) + }{ + {"button", + func(c ui.C) { ui.Button(c, "Go").Disabled(disabled) }, + func(c ui.C) { ui.ButtonBase(c, "Go").Size(40, 30).Disabled(disabled) }}, + {"checkbox", + func(c ui.C) { ui.Checkbox(c, &on, "Go").Disabled(disabled) }, + func(c ui.C) { ui.CheckboxBase(c, &on, "Go").Disabled(disabled) }}, + {"switch", + func(c ui.C) { ui.Switch(c, &on, "Go").Disabled(disabled) }, + func(c ui.C) { ui.SwitchBase(c, &on, "Go").Disabled(disabled) }}, + } + for _, p := range pairs { + t.Run(p.name+"/"+state.name, func(t *testing.T) { + styled, base := declared(t, page(p.styled)), declared(t, page(p.base)) + if fmt.Sprint(styled) != fmt.Sprint(base) { + t.Fatalf("the control and its Base declare different semantics\n styled: %+v\n base: %+v", styled, base) + } + }) + } + } + + for _, selected := range []string{"", "Large"} { + value := selected + t.Run("select/"+fmt.Sprintf("%q", selected), func(t *testing.T) { + styled := declared(t, page(func(c ui.C) { ui.Select(c, &value, choices, nil).Placeholder("Size") })) + base := declared(t, page(func(c ui.C) { ui.SelectBase(c, &value, choices, nil).Label("Size") })) + if fmt.Sprint(styled) != fmt.Sprint(base) { + t.Fatalf("the control and its Base declare different semantics\n styled: %+v\n base: %+v", styled, base) + } + }) + } + + t.Run("slider", func(t *testing.T) { + var a, b ui.SliderState + styled := declared(t, page(func(c ui.C) { ui.Slider(c, &a).Range(0, 10).Step(1).Label("Volume") })) + base := declared(t, page(func(c ui.C) { ui.SliderBase(c, &b).Range(0, 10).Step(1).Label("Volume") })) + if fmt.Sprint(styled) != fmt.Sprint(base) { + t.Fatalf("the control and its Base declare different semantics\n styled: %+v\n base: %+v", styled, base) + } + }) + + t.Run("text field", func(t *testing.T) { + var a, b string + styled := declared(t, page(func(c ui.C) { ui.TextField(c, &a, "Name", "Ada") })) + base := declared(t, page(func(c ui.C) { ui.TextFieldBase(c, &b, "Name", "Ada") })) + if fmt.Sprint(styled) != fmt.Sprint(base) { + t.Fatalf("the control and its Base declare different semantics\n styled: %+v\n base: %+v", styled, base) + } + }) + + // A strip of tabs and a segmented control are rows of Bases: each option says what + // the Base for that option says. + for _, chosen := range []string{"General", "About"} { + tab := chosen + t.Run("tabs/"+chosen, func(t *testing.T) { + names := []string{"General", "About"} + styled := declared(t, page(func(c ui.C) { ui.Tabs(c, &tab, names, nil) })) + base := declared(t, page(func(c ui.C) { + ui.Row(c).Children(func() { + for _, name := range names { + ui.TabBase(c.Key(name), &tab, name, name).Size(60, 28) + } + }) + })) + // Only what a Base is responsible for is compared: the strip's own + // roving focus (which tab is a Tab stop) is the group's, not the tab's. + if fmt.Sprint(styled) != fmt.Sprint(base) { + t.Fatalf("the strip and its Bases declare different semantics\n styled: %+v\n base: %+v", styled, base) + } + }) + choice := chosen + t.Run("choice/"+chosen, func(t *testing.T) { + names := []string{"General", "About"} + styled := declared(t, page(func(c ui.C) { ui.Choice(c, &choice, names, nil) })) + base := declared(t, page(func(c ui.C) { + ui.Row(c).Children(func() { + for _, name := range names { + ui.RadioBase(c.Key(name), &choice, name, name).Size(60, 28) + } + }) + })) + if fmt.Sprint(styled) != fmt.Sprint(base) { + t.Fatalf("the segmented control and its Bases declare different semantics\n styled: %+v\n base: %+v", styled, base) + } + }) + } +} diff --git a/ui/base_scan_test.go b/ui/base_scan_test.go new file mode 100644 index 000000000..eb4fdb06d --- /dev/null +++ b/ui/base_scan_test.go @@ -0,0 +1,68 @@ +package ui_test + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "slices" + "strings" + "testing" +) + +// comparedWithTheirStyledForm are the page Bases whose styled control is compared with them +// in TestStyledControlsDeclareWhatTheirBasesDeclare. Adding a Base means adding a row there +// and its name here, or, when no styled control is built from it, to withoutStyledForm. +var comparedWithTheirStyledForm = []string{ + "ButtonBase", "CheckboxBase", "SwitchBase", "SelectBase", "SliderBase", + "TextFieldBase", "TabBase", "RadioBase", +} + +// withoutStyledForm are the Bases that are not the Base of a control that ships with a look, +// so there is nothing to compare them with. ToggleBase has no Toggle on the page. +var withoutStyledForm = []string{"ToggleBase"} + +// A Base of a page is declared in a file that also declares the control it undresses. This +// test makes a new one say which of the two lists it belongs to, so a Base cannot be added +// without deciding whether it must stay the same control as the one with a look. +func TestEveryPageBaseIsComparedOrExplained(t *testing.T) { + entries, err := os.ReadDir(".") + if err != nil { + t.Fatal(err) + } + var found []string + set := token.NewFileSet() + for _, entry := range entries { + name := entry.Name() + if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + file, err := parser.ParseFile(set, name, nil, 0) + if err != nil { + t.Fatal(err) + } + for _, declaration := range file.Decls { + fn, ok := declaration.(*ast.FuncDecl) + if !ok || fn.Recv != nil || !fn.Name.IsExported() || !strings.HasSuffix(fn.Name.Name, "Base") { + continue + } + // A page element takes the page's C first; the frame's own constructors are methods. + if params := fn.Type.Params.List; len(params) > 0 { + if ident, ok := params[0].Type.(*ast.Ident); ok && ident.Name == "C" { + found = append(found, fn.Name.Name) + } + } + } + } + known := append(slices.Clone(comparedWithTheirStyledForm), withoutStyledForm...) + for _, name := range found { + if !slices.Contains(known, name) { + t.Errorf("%s is a page Base that no test compares with its styled control: add it to TestStyledControlsDeclareWhatTheirBasesDeclare and comparedWithTheirStyledForm, or to withoutStyledForm if it has none", name) + } + } + for _, name := range known { + if !slices.Contains(found, name) { + t.Errorf("%s is listed in base_scan_test.go but is not a page Base any more: remove it", name) + } + } +} diff --git a/ui/box.go b/ui/box.go index f22f3f1e6..53513a69c 100644 --- a/ui/box.go +++ b/ui/box.go @@ -409,7 +409,9 @@ func (b Box) Small() Box { func (b Box) Large() Box { b.n().buttonSize = components.ButtonSizeLarge; return b } func (b Box) IconOnly() Box { b.n().buttonSize = components.ButtonSizeIcon; return b } -// Disabled(true) makes a Button, Checkbox, Switch or Tabs inert and dimmed; Disabled(false) +// Disabled(true) makes a Button, Checkbox, Switch or Tabs inert and dimmed, and an element +// given Hit or HitWith (a Base among them) unavailable to the pointer, the keyboard and +// assistive technology, with the look left to you; Disabled(false) // makes it enabled again, so a condition is written in the call: `.Disabled(m.count <= 0)`. func (b Box) Disabled(disabled bool) Box { if disabled { diff --git a/ui/page_bases.go b/ui/page_bases.go index 3cdacc793..021030457 100644 --- a/ui/page_bases.go +++ b/ui/page_bases.go @@ -9,9 +9,9 @@ import ( // is clicked by the pointer and the keyboard, and reaches assistive technology as the // control it is; its Background, Border, Radius, Ring, Hover, Pressed and Focus looks, the // elements it is built from as children, and Draw and DrawOver are yours. The control -// with the theme's look is the same Base dressed, so a restyled control never copies a -// behavior, and a component library of your own has the keys, the focus, the value -// binding and the popups of the ones that ship. +// with the theme's look declares what its Base declares (a test compares them), so a +// restyled control never copies a behavior, and a component library of your own has the +// keys, the focus, the value binding and the popups of the ones that ship. // // on := ui.SwitchBase(c, &m.dark, "Dark mode") // on.Radius(999).Background(track(on.State())).Draw(m.paintThumb) diff --git a/ui/paint.go b/ui/paint.go index 80b4f3590..2afb2d613 100644 --- a/ui/paint.go +++ b/ui/paint.go @@ -108,7 +108,12 @@ func (f *frame) paint(i int32) { } canvas.HitLabel(n.id, hit, text, n.flags&flagDisabled != 0) } else { - canvas.HitWithOptions(n.id, hit, n.label, extra.hit) + options := extra.hit + // Disabled on the element is the control's own: a Base that was told it is + // unavailable says so to assistive technology and leaves the Tab order, + // as the control with a look does. + options.Disabled = options.Disabled || n.flags&flagDisabled != 0 + canvas.HitWithOptions(n.id, hit, n.label, options) } } From 7a46c798a9d0f020d08ee8077a0121b7dfd34302 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 17:24:51 +0800 Subject: [PATCH 02/15] docs(guides): lead the drawing guide with painting inside a page The drawing guide opened by telling readers to compute every rectangle in a Paint callback. Lead with Draw, DrawOver and ui.Control on an element the page lays out, with a compiled example, and describe the whole-window canvas as the route for where ui has nothing that fits. Say what a copy made by viva add is and how to change a control's look without copying. --- cmd/viva/help.go | 4 +- examples/guides/paintinpage/main.go | 57 ++++++++++++++ examples/guides/paintinpage/main_test.go | 66 ++++++++++++++++ website/content/guides/en/components.md | 2 +- .../content/guides/en/drawing-and-layout.md | 75 ++++++++++++++++++- website/content/guides/zh/components.md | 2 +- .../content/guides/zh/drawing-and-layout.md | 75 ++++++++++++++++++- 7 files changed, 274 insertions(+), 7 deletions(-) create mode 100644 examples/guides/paintinpage/main.go create mode 100644 examples/guides/paintinpage/main_test.go diff --git a/cmd/viva/help.go b/cmd/viva/help.go index 817a4c411..0aef5441e 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -106,7 +106,9 @@ func commands() []command { }}, {name: "add", usage: "add [flags] ...", summary: "Copy component source into your project.", - detail: "The files are yours to change; nothing links back to viva. See viva list for the names. The recipes come\n" + + detail: "The files are yours to change; nothing links back to viva. A copy is a painting recipe: it draws into a gfx.Canvas\n" + + "in the rectangle you give it, so call it from a Draw callback of a page's element or from a whole-window Paint.\n" + + "See viva list for the names. The recipes come\n" + "with the viva command, so they match the Viva version it was built from; when the project's go.mod\n" + "requires a different version, add says so (go tool viva runs the version the project pins).", run: func(arguments []string, output, errorOutput io.Writer) error { diff --git a/examples/guides/paintinpage/main.go b/examples/guides/paintinpage/main.go new file mode 100644 index 000000000..418f84bc3 --- /dev/null +++ b/examples/guides/paintinpage/main.go @@ -0,0 +1,57 @@ +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +type model struct { + samples []float32 // 0 to 1 +} + +// page declares a chart's frame and the button that feeds it. The page lays the +// chart's element out; what is drawn inside it is the chart's own. +func (m *model) page(c ui.C) { + theme := c.Theme() + ui.Column(c).Fill().Pad(24).Gap(16).Children(func() { + ui.Text(c, "Samples").FontSize(20).Bold() + ui.Row(c).FillWidth().Height(120).Radius(8).Background(theme.Card).Border(1, theme.Border). + Hit(ui.ID(c), "Samples chart"). + Draw(m.bars). + DrawOver(func(d *ui.DrawContext) { + if d.State.Hovered { + d.Canvas.Fill(d.Rect, d.Fade(theme.Foreground.WithAlpha(0.06))) + } + }) + if ui.Button(c, "Add a sample").Clicked() { + m.samples = append(m.samples, float32(len(m.samples)%7+1)/8) + } + }) +} + +// bars paints one bar for each sample in d.Rect, the room the page gave the element. +// It only paints: it may run more than once a frame and declares no elements. +func (m *model) bars(d *ui.DrawContext) { + const gap = 6 + if len(m.samples) == 0 { + return + } + width := (d.Rect.Width - gap*float32(len(m.samples)+1)) / float32(len(m.samples)) + for i, value := range m.samples { + height := d.Rect.Height * 0.8 * value + d.Canvas.Fill(ui.Rect{ + X: d.Rect.X + gap + float32(i)*(width+gap), + Y: d.Rect.Y + d.Rect.Height - height - 8, + Width: width, Height: height, + }, d.Fade(d.Theme.Primary)) + } +} + +func main() { + m := &model{samples: []float32{0.3, 0.6, 0.45}} + if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, m.page); err != nil { + log.Fatal(err) + } +} diff --git a/examples/guides/paintinpage/main_test.go b/examples/guides/paintinpage/main_test.go new file mode 100644 index 000000000..a2e021c82 --- /dev/null +++ b/examples/guides/paintinpage/main_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +func open(t *testing.T, m *model) *app.Driver { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: m.page}) + driver, err := app.NewDriver(page.Config(app.Config{Width: 480, Height: 300}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + return driver +} + +func hit(t *testing.T, driver *app.Driver, name string) gfx.Hit { + t.Helper() + for _, h := range driver.Snapshot().Hits { + if strings.HasPrefix(h.Label, name) && !h.IsLabel { + return h + } + } + t.Fatalf("no control named %q on screen", name) + return gfx.Hit{} +} + +// The chart is an element of the page: it has the room the page laid out for it, takes +// the pointer and is named for assistive technology, and what is drawn in it follows the +// model. +func TestTheChartIsAnElementOfThePageDrawnFromTheModel(t *testing.T) { + m := &model{samples: []float32{0.3, 0.6}} + driver := open(t, m) + chart := hit(t, driver, "Samples chart") + if chart.Bounds.Width < 300 || chart.Bounds.Height != 120 { + t.Fatalf("the chart's room is %vx%v, want the width of the page and 120 high", chart.Bounds.Width, chart.Bounds.Height) + } + bars := func() (n int) { + // What the chart painted: filled shapes in the primary color inside its room. + for _, p := range driver.Snapshot().Primitives { + if p.Color == gfx.LightTheme().Primary && p.Bounds.X >= chart.Bounds.X && p.Bounds.Y >= chart.Bounds.Y && + p.Bounds.X+p.Bounds.Width <= chart.Bounds.X+chart.Bounds.Width && + p.Bounds.Y+p.Bounds.Height <= chart.Bounds.Y+chart.Bounds.Height { + n++ + } + } + return n + } + before := bars() + add := hit(t, driver, "Add a sample") + if err := driver.Click(add.Bounds.X+add.Bounds.Width/2, add.Bounds.Y+add.Bounds.Height/2); err != nil { + t.Fatal(err) + } + if len(m.samples) != 3 { + t.Fatalf("samples = %d, want 3", len(m.samples)) + } + if after := bars(); before == 0 || after <= before { + t.Fatalf("a new sample painted no new bar in the chart: %d before, %d after", before, after) + } +} diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index ebcda56ba..ed2a71e28 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -44,7 +44,7 @@ Two limits are deliberate. A chart draws every point it is given, so a very long ## Owning a copy -If you want to change a component, copy it. `viva list` names the recipes the installer can copy, and `viva add` writes them into your project as ordinary Go files: +If you want to change a component, copy it. `viva list` names the recipes the installer can copy, and `viva add` writes them into your project as ordinary Go files. A copy is a painting recipe: it draws into a `gfx.Canvas` in the rectangle you give it (`BeginButton(canvas, theme, id, bounds)`), so you use it from a `Draw` callback of a page's element or from a whole-window `Paint`, and its look is the code you edit. To change how every `ui.Button` looks without copying anything, give the page `PageConfig.Styles`; to build a control of your own look on the behavior `ui` ships, use `ui.ButtonBase` and the other Bases. ```sh # install viva once (see "Build and package"); in a project made by viva init, use go tool viva diff --git a/website/content/guides/en/drawing-and-layout.md b/website/content/guides/en/drawing-and-layout.md index 3c0591430..e960dedea 100644 --- a/website/content/guides/en/drawing-and-layout.md +++ b/website/content/guides/en/drawing-and-layout.md @@ -1,11 +1,82 @@ --- title: Drawing and layout -summary: Coordinates, slicing space with rows, columns and grids, and painting rectangles, text, icons and paths. +summary: Painting inside an element of a page, and the whole-window canvas, with coordinates, rows, columns and grids, rectangles, text, icons and paths. order: 6 group: guides --- -Everything on screen is painted into a `gfx.Canvas` from your `Paint` callback. There is no widget tree to build and no stylesheet: you compute rectangles and ask the canvas to fill them, draw text in them, or declare them interactive. +Everything on screen is painted into a `gfx.Canvas`. Most applications do not call it directly for their controls: they declare a page with package `ui` ([Declarative layout](declarative-layout)), which lays out the elements and paints the controls, and they paint themselves only where `ui` has nothing that fits. There are two ways to do that. + +## Painting inside a page + +Give an element of the page a `Draw` (after its background and border, before its children) or a `DrawOver` (after its children). The page decides where the element goes and how big it is, and the callback paints inside `d.Rect` with the canvas, the theme, and the element's hover, press and focus state. Declare the element with `Hit` and a name, and the pointer and assistive technology reach it as they reach a control. + + +```go +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +type model struct { + samples []float32 // 0 to 1 +} + +// page declares a chart's frame and the button that feeds it. The page lays the +// chart's element out; what is drawn inside it is the chart's own. +func (m *model) page(c ui.C) { + theme := c.Theme() + ui.Column(c).Fill().Pad(24).Gap(16).Children(func() { + ui.Text(c, "Samples").FontSize(20).Bold() + ui.Row(c).FillWidth().Height(120).Radius(8).Background(theme.Card).Border(1, theme.Border). + Hit(ui.ID(c), "Samples chart"). + Draw(m.bars). + DrawOver(func(d *ui.DrawContext) { + if d.State.Hovered { + d.Canvas.Fill(d.Rect, d.Fade(theme.Foreground.WithAlpha(0.06))) + } + }) + if ui.Button(c, "Add a sample").Clicked() { + m.samples = append(m.samples, float32(len(m.samples)%7+1)/8) + } + }) +} + +// bars paints one bar for each sample in d.Rect, the room the page gave the element. +// It only paints: it may run more than once a frame and declares no elements. +func (m *model) bars(d *ui.DrawContext) { + const gap = 6 + if len(m.samples) == 0 { + return + } + width := (d.Rect.Width - gap*float32(len(m.samples)+1)) / float32(len(m.samples)) + for i, value := range m.samples { + height := d.Rect.Height * 0.8 * value + d.Canvas.Fill(ui.Rect{ + X: d.Rect.X + gap + float32(i)*(width+gap), + Y: d.Rect.Y + d.Rect.Height - height - 8, + Width: width, Height: height, + }, d.Fade(d.Theme.Primary)) + } +} + +func main() { + m := &model{samples: []float32{0.3, 0.6, 0.45}} + if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, m.page); err != nil { + log.Fatal(err) + } +} +``` + +A callback only paints: it may run more than once a frame and declares no elements. When the area also takes keys, the pointer or text, use `ui.Control` with its `Handlers` instead of `Hit`; its `Parts` name the regions inside it that you declare while drawing. + +## Painting the whole window + +An application with no page paints everything from a `Paint` callback: there is no widget tree to build and no stylesheet, you compute rectangles and ask the canvas to fill them, draw text in them, or declare them interactive. You also slice the rectangles, name every hit and keep every control's state (an open menu, a scroll position) yourself, which `ui` does for the controls it has, so choose it only where nothing in `ui` fits. The sections below describe this route; what the canvas draws applies inside a page's `Draw` as well. ## Coordinates diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index 61dab4c06..cbd56ef4e 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -44,7 +44,7 @@ plot := components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state) ## 拥有一份副本 -想修改组件时,就复制它。`viva list` 列出安装器能复制的配方,`viva add` 把它们作为普通 Go 文件写进你的项目: +想修改组件时,就复制它。`viva list` 列出安装器能复制的配方,`viva add` 把它们作为普通 Go 文件写进你的项目。复制出来的是绘制配方:它在你给定的矩形里往 `gfx.Canvas` 上画(`BeginButton(canvas, theme, id, bounds)`),所以要在页面元素的 `Draw` 回调里或整窗的 `Paint` 里使用,外观就是你要改的那段代码。想改变所有 `ui.Button` 的外观又不想复制任何东西,给页面设置 `PageConfig.Styles`;想基于 `ui` 自带的行为做自己外观的控件,用 `ui.ButtonBase` 等 Base。 ```sh # 先安装 viva(见「构建与打包」);viva init 生成的项目里用 go tool viva diff --git a/website/content/guides/zh/drawing-and-layout.md b/website/content/guides/zh/drawing-and-layout.md index 0c435e1d9..c13153991 100644 --- a/website/content/guides/zh/drawing-and-layout.md +++ b/website/content/guides/zh/drawing-and-layout.md @@ -1,11 +1,82 @@ --- title: 绘制与布局 -summary: 坐标、用行、列和网格切分空间,以及绘制矩形、文字、图标和路径。 +summary: 在页面的元素里自绘,以及整窗画布:坐标、行、列和网格,矩形、文字、图标和路径。 order: 6 group: guides --- -屏幕上的一切都是在你的 `Paint` 回调里画进 `gfx.Canvas` 的。没有需要构建的控件树,也没有样式表:你计算矩形,然后让画布填充它们、在里面绘制文字,或者把它们声明为可交互。 +屏幕上的一切都是画进 `gfx.Canvas` 的。大多数应用不会直接为自己的控件调用它:它们用 `ui` 包声明一个页面(见[声明式布局](declarative-layout)),由页面排布元素并绘制控件,只有在 `ui` 里没有合适的东西时才自己画。自己画有两种方式。 + +## 在页面里绘制 + +给页面中的元素挂一个 `Draw`(在它的背景和边框之后、子元素之前执行)或 `DrawOver`(在子元素之后执行)。元素放在哪里、有多大由页面决定,回调在 `d.Rect` 里用画布、主题以及元素的悬停、按下和焦点状态来画。用 `Hit` 和一个名字声明这个元素,指针和辅助技术就能像对待控件一样触达它。 + + +```go +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +type model struct { + samples []float32 // 0 to 1 +} + +// page declares a chart's frame and the button that feeds it. The page lays the +// chart's element out; what is drawn inside it is the chart's own. +func (m *model) page(c ui.C) { + theme := c.Theme() + ui.Column(c).Fill().Pad(24).Gap(16).Children(func() { + ui.Text(c, "Samples").FontSize(20).Bold() + ui.Row(c).FillWidth().Height(120).Radius(8).Background(theme.Card).Border(1, theme.Border). + Hit(ui.ID(c), "Samples chart"). + Draw(m.bars). + DrawOver(func(d *ui.DrawContext) { + if d.State.Hovered { + d.Canvas.Fill(d.Rect, d.Fade(theme.Foreground.WithAlpha(0.06))) + } + }) + if ui.Button(c, "Add a sample").Clicked() { + m.samples = append(m.samples, float32(len(m.samples)%7+1)/8) + } + }) +} + +// bars paints one bar for each sample in d.Rect, the room the page gave the element. +// It only paints: it may run more than once a frame and declares no elements. +func (m *model) bars(d *ui.DrawContext) { + const gap = 6 + if len(m.samples) == 0 { + return + } + width := (d.Rect.Width - gap*float32(len(m.samples)+1)) / float32(len(m.samples)) + for i, value := range m.samples { + height := d.Rect.Height * 0.8 * value + d.Canvas.Fill(ui.Rect{ + X: d.Rect.X + gap + float32(i)*(width+gap), + Y: d.Rect.Y + d.Rect.Height - height - 8, + Width: width, Height: height, + }, d.Fade(d.Theme.Primary)) + } +} + +func main() { + m := &model{samples: []float32{0.3, 0.6, 0.45}} + if err := ui.Run(app.Config{Title: "Samples", Width: 480, Height: 300}, m.page); err != nil { + log.Fatal(err) + } +} +``` + +回调只负责绘制:一帧里可能运行多次,并且不能声明元素。区域还要接收键盘、指针或文本时,用带 `Handlers` 的 `ui.Control` 代替 `Hit`;它的 `Parts` 给你在绘制时声明的内部区域命名。 + +## 绘制整个窗口 + +没有页面的应用在 `Paint` 回调里画出一切:没有需要构建的控件树,也没有样式表,你计算矩形,然后让画布填充它们、在里面绘制文字,或者把它们声明为可交互。矩形要自己切分,每个命中区要自己命名,每个控件的状态(展开的菜单、滚动位置)也要自己保管,而这些 `ui` 对它已有的控件都会替你做,所以只在 `ui` 里没有合适的东西时才选这条路。下面的各节讲的就是这条路;画布能画什么,在页面的 `Draw` 里同样适用。 ## 坐标 From 86e602fa2a404d7bb6ec675f9dfb1933147fd23b Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 17:50:38 +0800 Subject: [PATCH 03/15] test(ui): a Dialog without a height fits its description and body Pin that a Dialog given no Height is as tall as the height an application gets by measuring the header with components.BeginDialog and adding its body's height, so a page does not need that measurement. Motty drops it in the paired commit. --- ui/dialog_fit_test.go | 66 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 ui/dialog_fit_test.go diff --git a/ui/dialog_fit_test.go b/ui/dialog_fit_test.go new file mode 100644 index 000000000..0ffa41b3a --- /dev/null +++ b/ui/dialog_fit_test.go @@ -0,0 +1,66 @@ +package ui_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// A Dialog given no Height is as tall as its header with the description, its body and its +// footer need: the same height an application gets by measuring the header with +// components.BeginDialog (FitBody) and adding the body's height to it, which is what it +// had to do before. Declaring the body with the height it has is enough. +func TestDialogWithoutAHeightFitsItsDescriptionAndBody(t *testing.T) { + short := "Delete this host?" + long := strings.Repeat("A description long enough that it wraps onto several lines in the dialog. ", 4) + for _, tc := range []struct { + name string + description string + width, body float32 + }{ + {"no description", "", 420, 80}, + {"short description", short, 480, 124}, + {"wrapped description", long, 480, 124}, + {"wrapped, narrow", long, 360, 200}, + {"no body", long, 480, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + var want float32 + dialogHeight := func(explicit bool) float32 { + d := openPage(t, func(c ui.C) { + spec := ui.DialogSpec{Title: "Title", Description: tc.description, Width: tc.width, + Scope: gfx.Item(7), CloseID: gfx.Item(8)} + if explicit { + layout := components.BeginDialog(c.Canvas(), *c.Theme(), gfx.Rect{Width: c.Bounds().Width, Height: c.Bounds().Height}, + components.DialogOptions{ContentSize: gfx.Size{Width: tc.width}, FitBody: true}).Layout(tc.description) + spec.Height = layout.Content.Height + tc.body + want = spec.Height + } + dialog := ui.Dialog(c, spec) + dialog.Body(func() { + ui.Column(c).Height(tc.body).Hit(ui.ID(c), "body") + }) + dialog.Footer(func() { ui.Button(c, "OK") }) + }) + // The surface runs from the top of the title to the bottom of the footer, less the + // padding the surface keeps around them; the footer button is the last thing in it. + var top, bottom float32 = 1e9, 0 + for _, h := range d.driver.Snapshot().Hits { + if h.Label == "Title" || h.Label == "OK" || h.Label == "body" { + top = min(top, h.Bounds.Y) + bottom = max(bottom, h.Bounds.Y+h.Bounds.Height) + } + } + return bottom - top + } + byHand, byFit := dialogHeight(true), dialogHeight(false) + if fmt.Sprintf("%.2f", byHand) != fmt.Sprintf("%.2f", byFit) { + t.Fatalf("with the height measured by hand (%v) the controls span %.2f, with none %.2f", want, byHand, byFit) + } + }) + } +} From 144329826b583664a6c192c10b006a5b16f3973d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 17:59:44 +0800 Subject: [PATCH 04/15] feat(ui): give a Select trigger a Hint for assistive technology components.Select already declared the trigger's Hint; ui had no way to set it. --- cmd/viva/initfiles/AGENTS.md.txt | 2 +- ui/select.go | 12 +++++++++++- ui/select_disabled_test.go | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 9f575755e..edace41aa 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -483,7 +483,7 @@ func (m *model) page(c ui.C) { `if ui.Select(c, &m.size, sizes, nil).Placeholder("Size").Changed() { m.load(m.size) }`. The list is placed under the trigger (above it when there is no room), painted over everything, and scrolls when it is taller than the window; the page routes the wheel to it while it is open. `.DisabledOptions(flags)` takes a `[]bool` you keep, indexed like the options: a true - entry is dimmed, takes no click or focus and is skipped by type-ahead. `.XSmall()` makes the trigger shorter. `ui.Combobox` takes the same arguments plus a label and filters as the user types. + entry is dimmed, takes no click or focus and is skipped by type-ahead. `.XSmall()` makes the trigger shorter, and `.Hint(text)` gives it a description for assistive technology. `ui.Combobox` takes the same arguments plus a label and filters as the user types. ### Slots, grids and absolute placement diff --git a/ui/select.go b/ui/select.go index 01747250c..f0beddf62 100644 --- a/ui/select.go +++ b/ui/select.go @@ -168,6 +168,7 @@ type selectDecl struct { labels []string icons []gfx.Icon disabled []bool // this declaration's DisabledOptions: what the list paints + hint string // the trigger's Hint selected int canvas *gfx.Canvas popup int32 // the Popup that places the list, or -1 when it is closed @@ -337,6 +338,15 @@ func (b Box) DisabledOptions(disabled []bool) Box { return b } +// Hint is the description assistive technology reads after a Select's name and value, for +// what the value alone does not say, such as the path a chosen shell stands for. +func (b Box) Hint(text string) Box { + if n := b.n(); n.kind == kindSelect { + b.f.widgets.selects[n.aux].hint = text + } + return b +} + // optionDisabled reports whether option i is marked in disabled. func optionDisabled(disabled []bool, i int) bool { return i >= 0 && i < len(disabled) && disabled[i] } @@ -402,7 +412,7 @@ func (f *frame) paintSelect(n *node) { count := len(d.labels) trigger := Rect{X: n.rect.X, Y: n.rect.Y, Width: n.rect.Width, Height: n.pref[axisY]} options := components.SelectOptions{ - TriggerID: d.scope.At(count), Label: n.label, Placeholder: n.text, + TriggerID: d.scope.At(count), Label: n.label, Placeholder: n.text, Hint: d.hint, Disabled: n.flags&flagDisabled != 0, Layer: d.layer, Scope: d.scope.At(count + 2), DismissID: d.scope.At(count + 1), Viewport: f.bounds, } diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index 962d2eb33..8914dc9be 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -61,6 +61,21 @@ func TestSelectDisabledOptionIsReportedDisabled(t *testing.T) { } } +// A Select's Hint reaches assistive technology as the trigger's description. +func TestSelectHintIsTheTriggersHint(t *testing.T) { + size := "M" + d := openPage(t, page(func(c ui.C) { ui.Select(c, &size, []string{"S", "M"}, nil).Hint("Medium is the default") })) + for _, h := range d.driver.Snapshot().Hits { + if h.Role == gfx.RoleCombobox { + if h.Hint != "Medium is the default" { + t.Fatalf("hint = %q", h.Hint) + } + return + } + } + t.Fatal("no select trigger") +} + // XSmall is a shorter trigger than the default, as a button's is. func TestSelectXSmallIsShorterThanDefault(t *testing.T) { height := func(xsmall bool) float32 { From 333a9306fa0f6934870cffd5f0c360c6467316d7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 18:04:41 +0800 Subject: [PATCH 05/15] feat(ui): let a page Field paint as invalid components.Input paints an invalid input with the destructive border and ring, but a page text field had no way to ask for it. Field.Invalid feeds the snapshot, as Secure does. Motty's vault unlock dialog needs it. --- ui/field.go | 6 +++++- ui/select_disabled_test.go | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/ui/field.go b/ui/field.go index d194702d2..bd76ff3e7 100644 --- a/ui/field.go +++ b/ui/field.go @@ -29,6 +29,10 @@ import ( type Field struct { // Secure shows bullets instead of the text and keeps it out of accessibility. Secure bool + // Invalid paints the field as one whose value is wrong, with the destructive + // border and ring components.Input gives an invalid input. It is the application's + // to set and clear, as Secure is; it changes the look only. + Invalid bool editor *text.Editor id gfx.ID @@ -163,7 +167,7 @@ func (field *Field) snapshot(f *frame, id gfx.ID, label, placeholder string) com focused := f.canvas != nil && f.canvas.Focused() == id selection := editor.Selection() snapshot := components.InputSnapshot{ - ID: id, Label: label, Value: value, Placeholder: placeholder, Secure: field.Secure, + ID: id, Label: label, Value: value, Placeholder: placeholder, Secure: field.Secure, Invalid: field.Invalid, Focused: focused, // The field paints its own text, caret, selection and composition, and the // platform's editor is only where input arrives. A platform that lays text out diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index 8914dc9be..267a7f12b 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -1,6 +1,7 @@ package ui_test import ( + "fmt" "testing" "github.com/vivaui/viva/gfx" @@ -115,3 +116,16 @@ func TestSelectDisabledOptionsDeclareWithoutAllocating(t *testing.T) { t.Fatalf("a warm paint of a Select with DisabledOptions allocates %v times", got) } } + +// An Invalid Field is painted differently from a valid one. +func TestFieldInvalidChangesTheLook(t *testing.T) { + look := func(invalid bool) string { + var f ui.Field + f.Invalid = invalid + d := openPage(t, page(func(c ui.C) { ui.TextFieldID(c, gfx.Item(5), &f, "Name", "") })) + return fmt.Sprint(d.driver.Snapshot().Primitives) + } + if look(false) == look(true) { + t.Fatal("an invalid field is painted like a valid one") + } +} From 01bf3b88f741c73c799c97099fce438fa3a008ae Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 18:19:58 +0800 Subject: [PATCH 06/15] feat(ui): measure a Button's room with ButtonExtent A page that reserves the room of a button it paints itself, or places beside something else, had to call components.BeginButton with an empty identity just to read its size. ButtonExtent(c, label, size) gives the width and height the element Button is laid out at, with a test per size against the laid-out hit. --- ui/button_extent.go | 38 ++++++++++++++++++++++++++++++++++++++ ui/select_disabled_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 ui/button_extent.go diff --git a/ui/button_extent.go b/ui/button_extent.go new file mode 100644 index 000000000..3429d6585 --- /dev/null +++ b/ui/button_extent.go @@ -0,0 +1,38 @@ +package ui + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +// ButtonSize names the heights of a Button that Box.XSmall, Small and Large give it. +type ButtonSize uint8 + +const ( + ButtonSizeDefault ButtonSize = iota + ButtonSizeXSmall + ButtonSizeSmall + ButtonSizeLarge +) + +// ButtonExtent is the width and height a Button showing label takes at size in the page's +// theme: what the element Button(c, label) is laid out at, for a page that has to reserve +// the room of a button it paints itself or places beside something else. +// +// room := ui.ButtonExtent(c, "Configure", ui.ButtonSizeXSmall) +// ui.Slot(c).Size(room.Width, room.Height) +// +// It measures with the page's canvas and declares nothing. +func ButtonExtent(c C, label string, size ButtonSize) Size { + button := components.BeginButton(c.Canvas(), *c.Theme(), gfx.ID{}, Rect{}) + switch size { + case ButtonSizeXSmall: + button = button.XSmall() + case ButtonSizeSmall: + button = button.Small() + case ButtonSizeLarge: + button = button.Large() + } + button = button.SizeToFit(label) + return Size{Width: button.BoundsWidth(), Height: button.BoundsHeight()} +} diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index 267a7f12b..4c06a4c1a 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -129,3 +129,34 @@ func TestFieldInvalidChangesTheLook(t *testing.T) { t.Fatal("an invalid field is painted like a valid one") } } + +// ButtonExtent is the room a Button of that size is laid out at. +func TestButtonExtentIsTheSizeOfTheButton(t *testing.T) { + for _, tc := range []struct { + name string + size ui.ButtonSize + set func(ui.Box) ui.Box + }{ + {"default", ui.ButtonSizeDefault, func(b ui.Box) ui.Box { return b }}, + {"xsmall", ui.ButtonSizeXSmall, func(b ui.Box) ui.Box { return b.XSmall() }}, + {"small", ui.ButtonSizeSmall, func(b ui.Box) ui.Box { return b.Small() }}, + {"large", ui.ButtonSizeLarge, func(b ui.Box) ui.Box { return b.Large() }}, + } { + t.Run(tc.name, func(t *testing.T) { + var room ui.Size + d := openPage(t, func(c ui.C) { + room = ui.ButtonExtent(c, "Configure", tc.size) + ui.Row(c).Children(func() { tc.set(ui.Button(c, "Configure")) }) + }) + for _, h := range d.driver.Snapshot().Hits { + if h.Label == "Configure" && !h.IsLabel { + if h.Bounds.Width != room.Width || h.Bounds.Height != room.Height { + t.Fatalf("laid out at %vx%v, ButtonExtent says %vx%v", h.Bounds.Width, h.Bounds.Height, room.Width, room.Height) + } + return + } + } + t.Fatal("no button") + }) + } +} From 8d814bfa3258a1b1726681983ffc1b873ad056f8 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 18:25:43 +0800 Subject: [PATCH 07/15] Revert "feat(ui): measure a Button's room with ButtonExtent" This reverts commit 01bf3b88f741c73c799c97099fce438fa3a008ae. --- ui/button_extent.go | 38 -------------------------------------- ui/select_disabled_test.go | 31 ------------------------------- 2 files changed, 69 deletions(-) delete mode 100644 ui/button_extent.go diff --git a/ui/button_extent.go b/ui/button_extent.go deleted file mode 100644 index 3429d6585..000000000 --- a/ui/button_extent.go +++ /dev/null @@ -1,38 +0,0 @@ -package ui - -import ( - "github.com/vivaui/viva/components" - "github.com/vivaui/viva/gfx" -) - -// ButtonSize names the heights of a Button that Box.XSmall, Small and Large give it. -type ButtonSize uint8 - -const ( - ButtonSizeDefault ButtonSize = iota - ButtonSizeXSmall - ButtonSizeSmall - ButtonSizeLarge -) - -// ButtonExtent is the width and height a Button showing label takes at size in the page's -// theme: what the element Button(c, label) is laid out at, for a page that has to reserve -// the room of a button it paints itself or places beside something else. -// -// room := ui.ButtonExtent(c, "Configure", ui.ButtonSizeXSmall) -// ui.Slot(c).Size(room.Width, room.Height) -// -// It measures with the page's canvas and declares nothing. -func ButtonExtent(c C, label string, size ButtonSize) Size { - button := components.BeginButton(c.Canvas(), *c.Theme(), gfx.ID{}, Rect{}) - switch size { - case ButtonSizeXSmall: - button = button.XSmall() - case ButtonSizeSmall: - button = button.Small() - case ButtonSizeLarge: - button = button.Large() - } - button = button.SizeToFit(label) - return Size{Width: button.BoundsWidth(), Height: button.BoundsHeight()} -} diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index 4c06a4c1a..267a7f12b 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -129,34 +129,3 @@ func TestFieldInvalidChangesTheLook(t *testing.T) { t.Fatal("an invalid field is painted like a valid one") } } - -// ButtonExtent is the room a Button of that size is laid out at. -func TestButtonExtentIsTheSizeOfTheButton(t *testing.T) { - for _, tc := range []struct { - name string - size ui.ButtonSize - set func(ui.Box) ui.Box - }{ - {"default", ui.ButtonSizeDefault, func(b ui.Box) ui.Box { return b }}, - {"xsmall", ui.ButtonSizeXSmall, func(b ui.Box) ui.Box { return b.XSmall() }}, - {"small", ui.ButtonSizeSmall, func(b ui.Box) ui.Box { return b.Small() }}, - {"large", ui.ButtonSizeLarge, func(b ui.Box) ui.Box { return b.Large() }}, - } { - t.Run(tc.name, func(t *testing.T) { - var room ui.Size - d := openPage(t, func(c ui.C) { - room = ui.ButtonExtent(c, "Configure", tc.size) - ui.Row(c).Children(func() { tc.set(ui.Button(c, "Configure")) }) - }) - for _, h := range d.driver.Snapshot().Hits { - if h.Label == "Configure" && !h.IsLabel { - if h.Bounds.Width != room.Width || h.Bounds.Height != room.Height { - t.Fatalf("laid out at %vx%v, ButtonExtent says %vx%v", h.Bounds.Width, h.Bounds.Height, room.Width, room.Height) - } - return - } - } - t.Fatal("no button") - }) - } -} From 3eaae58cab919c1d7cd395a5bb4da01fbd5a772f Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 18:39:28 +0800 Subject: [PATCH 08/15] feat(ui): FormField shows an error, the invalid look and labels a control The shared field layout already takes an Error, Invalid and the control the title labels (BeginField's For); FormFieldState now sets them. A page declaring a form row no longer needs a hand-painted BeginField for any of them. Tested: the error is painted and For makes the title the control's label. --- ui/form_field.go | 17 ++++++++++++++--- ui/select_disabled_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/ui/form_field.go b/ui/form_field.go index 01b976b46..f717a4c85 100644 --- a/ui/form_field.go +++ b/ui/form_field.go @@ -1,6 +1,9 @@ package ui -import "github.com/vivaui/viva/field" +import ( + "github.com/vivaui/viva/field" + "github.com/vivaui/viva/gfx" +) // FormFieldState is one form field's scratch, kept in the model next to the // values the field shows; the zero value is ready to use. Keep one for each @@ -8,6 +11,14 @@ import "github.com/vivaui/viva/field" // measured, placed and painted in, and it is reused every paint without // allocating. type FormFieldState struct { + // Error is the line under the control, in the destructive color, and Invalid gives + // the title the invalid look: set them before declaring the field, as BeginField's + // Invalid and the error it is painted with. For, when set, makes the title the label + // of the control with that identity: pressing it focuses and clicks the control. + Error string + Invalid bool + For gfx.ID + label string theme *Theme layout field.Layout @@ -52,12 +63,12 @@ func FormField(c C, state *FormFieldState, label string) Box { return p.container(c.f.customLayout(state)).Draw(state.paint) } -// spec is the field's field.Spec: a title and no metadata, the subset +// spec is the field's field.Spec: its title, error, invalid look and the control it labels, the subset // BeginField.Paint(label, "", "") paints. The shared layout still reserves the // description and error rows, so the field and a painted BeginField have the // same height. func (state *FormFieldState) spec() field.Spec { - return field.Spec{Title: state.label} + return field.Spec{Title: state.label, Error: state.Error, Invalid: state.Invalid, Control: state.For} } // MeasureWidth reports no preferred width: a form field takes the width its diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index 267a7f12b..6f5048bcd 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -129,3 +129,29 @@ func TestFieldInvalidChangesTheLook(t *testing.T) { t.Fatal("an invalid field is painted like a valid one") } } + +// A FormField with an Error paints it, with For the title is the control's label, and the +// field keeps the height it is given. +func TestFormFieldErrorInvalidAndFor(t *testing.T) { + var state ui.FormFieldState + state.Error, state.Invalid, state.For = "Not valid.", true, gfx.Item(9) + d := openPage(t, page(func(c ui.C) { + ui.FormField(c, &state, "Name").FillWidth().Height(90).Children(func() { + ui.TextFieldID(c, gfx.Item(9), new(ui.Field), "Name", "") + }) + })) + snap := d.driver.Snapshot() + var gotError, titleIsLabel bool + for _, x := range snap.Texts { + gotError = gotError || x.Value == "Not valid." + } + for _, h := range snap.Hits { + titleIsLabel = titleIsLabel || (h.IsLabel && h.Label == "Name") + } + if !gotError { + t.Fatal("the error line is not painted") + } + if !titleIsLabel { + t.Fatal("For did not make the title the control's label") + } +} From 8cf777db53df9dcf0916873d3582316124e796b7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 19:03:57 +0800 Subject: [PATCH 09/15] feat(ui): let a page Field be disabled components.Input paints a disabled input dimmed and out of the Tab order, but a page text field had no way to ask for it, which kept disabled proxy fields hand painted. Field.Disabled feeds the snapshot, as Secure and Invalid do. Tested: painted differently, reported disabled, not focusable. --- ui/field.go | 6 +++++- ui/select_disabled_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/ui/field.go b/ui/field.go index bd76ff3e7..1ff5ddf03 100644 --- a/ui/field.go +++ b/ui/field.go @@ -33,6 +33,10 @@ type Field struct { // border and ring components.Input gives an invalid input. It is the application's // to set and clear, as Secure is; it changes the look only. Invalid bool + // Disabled paints the field dimmed and takes it out of the Tab order and the pointer's + // reach, as components.Input does for a disabled input. It is the application's to set + // and clear, as Secure is. + Disabled bool editor *text.Editor id gfx.ID @@ -167,7 +171,7 @@ func (field *Field) snapshot(f *frame, id gfx.ID, label, placeholder string) com focused := f.canvas != nil && f.canvas.Focused() == id selection := editor.Selection() snapshot := components.InputSnapshot{ - ID: id, Label: label, Value: value, Placeholder: placeholder, Secure: field.Secure, Invalid: field.Invalid, + ID: id, Label: label, Value: value, Placeholder: placeholder, Secure: field.Secure, Invalid: field.Invalid, Disabled: field.Disabled, Focused: focused, // The field paints its own text, caret, selection and composition, and the // platform's editor is only where input arrives. A platform that lays text out diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index 6f5048bcd..88dd5e60c 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -155,3 +155,28 @@ func TestFormFieldErrorInvalidAndFor(t *testing.T) { t.Fatal("For did not make the title the control's label") } } + +// A Disabled Field is painted dimmed, reported disabled and not focusable. +func TestFieldDisabledIsDimmedAndInert(t *testing.T) { + look := func(disabled bool) (string, gfx.Hit) { + var f ui.Field + f.Disabled = disabled + d := openPage(t, page(func(c ui.C) { ui.TextFieldID(c, gfx.Item(5), &f, "Name", "") })) + snap := d.driver.Snapshot() + for _, h := range snap.Hits { + if h.Role == gfx.RoleTextField { + return fmt.Sprint(snap.Primitives), h + } + } + t.Fatal("no field") + return "", gfx.Hit{} + } + plain, enabled := look(false) + dim, disabled := look(true) + if plain == dim { + t.Fatal("a disabled field is painted like an enabled one") + } + if enabled.Disabled || !disabled.Disabled || disabled.Focusable { + t.Fatalf("hit: enabled.Disabled=%v disabled.Disabled=%v disabled.Focusable=%v", enabled.Disabled, disabled.Disabled, disabled.Focusable) + } +} From 7ae8b6b665876718f519ad3c3511c8939bfc9490 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 20:03:20 +0800 Subject: [PATCH 10/15] feat(ui): give one Button its own recipe PageConfig.Styles.Button dresses every button of a page, but a page had no way to dress one: Box.Background does not reach a themed Button, and ButtonBase drops the theme's hover, press, focus and disabled looks. Box.ButtonRecipe takes the typed function components.Button already accepts (start from components.ButtonRecipe and change a color) and wins over the page's Styles. Tested: only that button is dressed, removing the hook fails the test, and a warm declaration allocates nothing. Motty's bookmark editor forces a dark Save button this way. --- cmd/viva/initfiles/AGENTS.md.txt | 2 +- ui/box.go | 20 ++++++++++++++ ui/frame.go | 3 +- ui/paint.go | 3 ++ ui/select_disabled_test.go | 47 ++++++++++++++++++++++++++++++++ 5 files changed, 73 insertions(+), 2 deletions(-) diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index edace41aa..355c868b6 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -483,7 +483,7 @@ func (m *model) page(c ui.C) { `if ui.Select(c, &m.size, sizes, nil).Placeholder("Size").Changed() { m.load(m.size) }`. The list is placed under the trigger (above it when there is no room), painted over everything, and scrolls when it is taller than the window; the page routes the wheel to it while it is open. `.DisabledOptions(flags)` takes a `[]bool` you keep, indexed like the options: a true - entry is dimmed, takes no click or focus and is skipped by type-ahead. `.XSmall()` makes the trigger shorter, and `.Hint(text)` gives it a description for assistive technology. `ui.Combobox` takes the same arguments plus a label and filters as the user types. + entry is dimmed, takes no click or focus and is skipped by type-ahead. `.ButtonRecipe(fn)` gives one Button its own look (colors, radius, ring) where `PageConfig.Styles.Button` dresses them all; declare `fn` once, not as a closure per paint. `.XSmall()` makes the trigger shorter, and `.Hint(text)` gives it a description for assistive technology. `ui.Combobox` takes the same arguments plus a label and filters as the user types. ### Slots, grids and absolute placement diff --git a/ui/box.go b/ui/box.go index 53513a69c..d3e074f94 100644 --- a/ui/box.go +++ b/ui/box.go @@ -409,6 +409,26 @@ func (b Box) Small() Box { func (b Box) Large() Box { b.n().buttonSize = components.ButtonSizeLarge; return b } func (b Box) IconOnly() Box { b.n().buttonSize = components.ButtonSizeIcon; return b } +// ButtonRecipe gives one Button its own look: the function is asked for the colors, radius +// and ring of the button in each state, as PageConfig.Styles.Button is for every button of a +// page, and wins over it. Start from components.ButtonRecipe and change what differs: +// +// ui.Button(c, "Save").ButtonRecipe(func(t gfx.Theme, v components.ButtonVariant, s gfx.State) components.ButtonLook { +// t.Primary, t.PrimaryForeground = dark, light +// return components.ButtonRecipe(t, v, s) +// }) +// +// It is for a button whose look is not the theme's; a page that dresses all of them uses Styles, +// and a control with no theme look at all uses ButtonBase. Declare the function once (a +// package-level func or a method value kept in the model), as a closure made in each paint +// allocates. Other elements ignore it. +func (b Box) ButtonRecipe(recipe func(gfx.Theme, components.ButtonVariant, gfx.State) components.ButtonLook) Box { + if n := b.n(); n.kind == kindButton { + b.f.extra(b.i).buttonRecipe = recipe + } + return b +} + // Disabled(true) makes a Button, Checkbox, Switch or Tabs inert and dimmed, and an element // given Hit or HitWith (a Base among them) unavailable to the pointer, the keyboard and // assistive technology, with the look left to you; Disabled(false) diff --git a/ui/frame.go b/ui/frame.go index 8c285b79d..4172ac5c5 100644 --- a/ui/frame.go +++ b/ui/frame.go @@ -188,7 +188,8 @@ const ( type extra struct { hit gfx.HitOptions icon gfx.Icon - iconTransform gfx.IconTransform // moves the icon inside its box without moving the box + iconTransform gfx.IconTransform // moves the icon inside its box without moving the box + buttonRecipe func(gfx.Theme, components.ButtonVariant, gfx.State) components.ButtonLook // ButtonRecipe: this button's own look border Color shadow gfx.ShadowLevel ring Color // Ring: a line around the outside of the element diff --git a/ui/paint.go b/ui/paint.go index 2afb2d613..1d5aeac67 100644 --- a/ui/paint.go +++ b/ui/paint.go @@ -286,6 +286,9 @@ func (f *frame) paintButton(n *node) { if f.styles != nil && f.styles.Button != nil { button = button.Recipe(f.styles.Button) } + if extra.buttonRecipe != nil { + button = button.Recipe(extra.buttonRecipe) + } // A button is as tall as its size says unless the element was given more or less // room: a Height, or a Grow along a column. It then fills that room. if h := r.Height; h > 0 && math.Abs(float64(h-button.BoundsHeight())) > 0.01 { diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index 88dd5e60c..eeb4dc8a3 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -2,6 +2,7 @@ package ui_test import ( "fmt" + "github.com/vivaui/viva/components" "testing" "github.com/vivaui/viva/gfx" @@ -180,3 +181,49 @@ func TestFieldDisabledIsDimmedAndInert(t *testing.T) { t.Fatalf("hit: enabled.Disabled=%v disabled.Disabled=%v disabled.Focusable=%v", enabled.Disabled, disabled.Disabled, disabled.Focusable) } } + +var darkSaveRecipe = func(theme gfx.Theme, variant components.ButtonVariant, state gfx.State) components.ButtonLook { + theme.Primary, theme.PrimaryForeground = gfx.RGB(24, 24, 27), gfx.RGB(250, 250, 250) + return components.ButtonRecipe(theme, variant, state) +} + +// A Button given its own recipe is painted with it; the others on the page keep the theme's. +func TestButtonRecipeDressesOnlyThatButton(t *testing.T) { + d := openPage(t, page(func(c ui.C) { + ui.Button(c, "Plain") + ui.Button(c, "Dark").ButtonRecipe(darkSaveRecipe) + })) + fill := func(label string) gfx.Color { + var bounds gfx.Rect + for _, h := range d.driver.Snapshot().Hits { + if h.Label == label && !h.IsLabel { + bounds = h.Bounds + } + } + for _, p := range d.driver.Snapshot().Primitives { + if p.Bounds.X == bounds.X && p.Bounds.Y == bounds.Y && p.Bounds.Width == bounds.Width { + return p.Color + } + } + t.Fatalf("no fill for %s", label) + return gfx.Color{} + } + if fill("Plain") == fill("Dark") { + t.Fatal("the recipe did not change the button's fill") + } + if got, want := fill("Dark"), gfx.RGB(24, 24, 27); got != want { + t.Fatalf("dark button fill = %v, want %v", got, want) + } +} + +// Declaring a button with its own recipe allocates nothing once the page is warm. +func TestButtonRecipeDeclaresWithoutAllocating(t *testing.T) { + page2, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + view := func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { ui.Button(c, "Save").ButtonRecipe(darkSaveRecipe) }) + } + drawPage(page2, canvas, view) + if got := testing.AllocsPerRun(50, func() { drawPage(page2, canvas, view) }); got != 0 { + t.Fatalf("a warm paint of a button with its own recipe allocates %v times", got) + } +} From 9614365b861fa010cdbddaf7c7f25c86701496b0 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 21:25:49 +0800 Subject: [PATCH 11/15] feat(ui): FormField takes a Description and Field a Hint The shared field layout already places a description under the control, and components.Input already gives its hit a Hint; ui exposed neither. FormFieldState.Description paints the muted help line, Field.Hint feeds the snapshot's Hint. Tested: both are reached, and removing either wiring fails the test. Motty's local proxy port field needs both. --- ui/field.go | 5 ++++- ui/form_field.go | 4 +++- ui/select_disabled_test.go | 27 +++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/ui/field.go b/ui/field.go index 1ff5ddf03..894b025ea 100644 --- a/ui/field.go +++ b/ui/field.go @@ -37,6 +37,9 @@ type Field struct { // reach, as components.Input does for a disabled input. It is the application's to set // and clear, as Secure is. Disabled bool + // Hint is the description assistive technology reads after the field's name and value, for + // what they do not say. It is the application's to set and clear, as Secure is. + Hint string editor *text.Editor id gfx.ID @@ -171,7 +174,7 @@ func (field *Field) snapshot(f *frame, id gfx.ID, label, placeholder string) com focused := f.canvas != nil && f.canvas.Focused() == id selection := editor.Selection() snapshot := components.InputSnapshot{ - ID: id, Label: label, Value: value, Placeholder: placeholder, Secure: field.Secure, Invalid: field.Invalid, Disabled: field.Disabled, + ID: id, Label: label, Value: value, Placeholder: placeholder, Secure: field.Secure, Invalid: field.Invalid, Disabled: field.Disabled, Hint: field.Hint, Focused: focused, // The field paints its own text, caret, selection and composition, and the // platform's editor is only where input arrives. A platform that lays text out diff --git a/ui/form_field.go b/ui/form_field.go index f717a4c85..b9ef8efbc 100644 --- a/ui/form_field.go +++ b/ui/form_field.go @@ -18,6 +18,8 @@ type FormFieldState struct { Error string Invalid bool For gfx.ID + // Description is a line of help under the control, above Error, in the muted color. + Description string label string theme *Theme @@ -68,7 +70,7 @@ func FormField(c C, state *FormFieldState, label string) Box { // description and error rows, so the field and a painted BeginField have the // same height. func (state *FormFieldState) spec() field.Spec { - return field.Spec{Title: state.label, Error: state.Error, Invalid: state.Invalid, Control: state.For} + return field.Spec{Title: state.label, Description: state.Description, Error: state.Error, Invalid: state.Invalid, Control: state.For} } // MeasureWidth reports no preferred width: a form field takes the width its diff --git a/ui/select_disabled_test.go b/ui/select_disabled_test.go index eeb4dc8a3..86fef8bd6 100644 --- a/ui/select_disabled_test.go +++ b/ui/select_disabled_test.go @@ -227,3 +227,30 @@ func TestButtonRecipeDeclaresWithoutAllocating(t *testing.T) { t.Fatalf("a warm paint of a button with its own recipe allocates %v times", got) } } + +// A FormField paints its Description, and a Field's Hint reaches assistive technology. +func TestFormFieldDescriptionAndFieldHint(t *testing.T) { + var state ui.FormFieldState + state.Description = "Locked while connected." + var f ui.Field + f.Hint = "Locked while connected." + d := openPage(t, page(func(c ui.C) { + ui.FormField(c, &state, "Port").FillWidth().Height(90).Children(func() { + ui.TextFieldID(c, gfx.Item(9), &f, "Port", "") + }) + })) + snap := d.driver.Snapshot() + painted, hinted := false, false + for _, x := range snap.Texts { + painted = painted || x.Value == "Locked while connected." + } + for _, h := range snap.Hits { + hinted = hinted || (h.Role == gfx.RoleTextField && h.Hint == "Locked while connected.") + } + if !painted { + t.Fatal("the description is not painted") + } + if !hinted { + t.Fatal("the field's hint did not reach its hit") + } +} From 3ed35ad2ff5674a17f468827802a702e2250bdd2 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 21:34:43 +0800 Subject: [PATCH 12/15] fix(headless): do not report a selected run painted again in its highlight --- headless/layout.go | 5 +++++ headless/layout_test.go | 16 ++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/headless/layout.go b/headless/layout.go index c835c482c..0041e87a9 100644 --- a/headless/layout.go +++ b/headless/layout.go @@ -96,6 +96,11 @@ func CheckLayout(snapshot app.Snapshot) []LayoutProblem { if a.text.Layer != b.text.Layer { continue } + // A selected run is painted again inside its highlight: the same line at + // the same place, once under the selection and once over it. + if a.text.Value == b.text.Value && a.text.Bounds == b.text.Bounds && a.text.Style == b.text.Style && (a.text.HasClip || b.text.HasClip) { + continue + } common := intersection(a.visible, b.visible) if common.Width > layoutTolerance && common.Height > layoutTolerance { problems = append(problems, LayoutProblem{LayoutOverlap, common, a.text.Value, diff --git a/headless/layout_test.go b/headless/layout_test.go index 01ac45512..998e3fb2e 100644 --- a/headless/layout_test.go +++ b/headless/layout_test.go @@ -121,6 +121,22 @@ func TestCheckLayoutPrefersPaintedTextWidths(t *testing.T) { } } +func TestCheckLayoutIgnoresASelectedRunPaintedAgainInsideItsHighlight(t *testing.T) { + style := gfx.TextStyle{Size: 14, Color: gfx.Color{Alpha: 1}} + line := gfx.Rect{X: 10, Y: 20, Width: 200, Height: 20} + snapshot := app.Snapshot{Width: 320, Height: 100, Texts: []gfx.Text{ + {Value: "7897", Bounds: line, Style: style, HasClip: true, ClipOf: gfx.Rect{X: 10, Y: 16, Width: 200, Height: 28}}, + {Value: "7897", Bounds: line, Style: style, HasClip: true, ClipOf: gfx.Rect{X: 10, Y: 16, Width: 32, Height: 28}}, + }} + if problems := CheckLayout(snapshot); len(problems) != 0 { + t.Fatalf("problems = %+v", problems) + } + snapshot.Texts[1].Value = "7898" + if kinds := layoutKinds(CheckLayout(snapshot)); kinds[LayoutOverlap] == 0 { + t.Fatal("two different runs at one place must still overlap") + } +} + func TestCheckLayoutIgnoresALineThatAScrolledAreaShowsHalfOf(t *testing.T) { session := layoutSession(t, func(canvas *gfx.Canvas) { canvas.Clip(gfx.Rect{X: 0, Y: 0, Width: 320, Height: 100}) From e1bb4dae649d0f725ae296a2e034c1ce874b3595 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 22:34:06 +0800 Subject: [PATCH 13/15] fix(ui): give the keyboard back to a field after its action is pressed --- ui/field_addons.go | 9 +++++++-- ui/field_addons_test.go | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/ui/field_addons.go b/ui/field_addons.go index bb2f09177..3a6e11470 100644 --- a/ui/field_addons.go +++ b/ui/field_addons.go @@ -58,14 +58,19 @@ func (b Box) Action(icon gfx.Icon, label string) Box { return b } -// ActionClicked reports whether this paint delivers a press on the field's Action. +// ActionClicked reports whether this paint delivers a press on the field's Action. The +// keyboard goes back to the field then, so a clear or a reveal does not end the typing. func (b Box) ActionClicked() bool { n := b.n() if n.kind != kindInput || n.ext == 0 || b.f.exts[n.ext].addons == 0 || b.f.canvas == nil { return false } end := b.f.addons[b.f.exts[n.ext].addons-1].end - return end.Kind == components.InputGroupSlotButton && n.flags&flagDisabled == 0 && b.f.canvas.Clicked(end.ID) + if end.Kind != components.InputGroupSlotButton || n.flags&flagDisabled != 0 || !b.f.canvas.Clicked(end.ID) { + return false + } + b.f.canvas.RequestFocus(b.f.inputs[n.aux].ID) + return true } // actionID names a field's Action in the field's own scope. diff --git a/ui/field_addons_test.go b/ui/field_addons_test.go index 873fd9642..a0e0cb115 100644 --- a/ui/field_addons_test.go +++ b/ui/field_addons_test.go @@ -39,6 +39,10 @@ func TestFieldIconAndAction(t *testing.T) { if clears != 1 || query != "" { t.Fatalf("clears %d, query %q", clears, query) } + d.typeText("db") + if query != "db" { + t.Fatalf("typing after the action reached %q: the keyboard did not go back to the field", query) + } } func BenchmarkFieldAddons(b *testing.B) { From d97f2b666b48f1ec579b768670c03f5e9cf20fd7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 22:43:03 +0800 Subject: [PATCH 14/15] feat(audio): play PCM on the default output device --- README.md | 4 + audio/audio.go | 249 +++++++++++++++++++++++++++++++++++ audio/audio_test.go | 237 +++++++++++++++++++++++++++++++++ audio/device_test.go | 34 +++++ audio/output_darwin.c | 232 ++++++++++++++++++++++++++++++++ audio/output_darwin.go | 62 +++++++++ audio/output_linux.go | 205 +++++++++++++++++++++++++++++ audio/output_linux_other.go | 7 + audio/output_other.go | 9 ++ audio/output_windows.go | 255 ++++++++++++++++++++++++++++++++++++ docs/README.md | 2 + docs/audio.md | 106 +++++++++++++++ 12 files changed, 1402 insertions(+) create mode 100644 audio/audio.go create mode 100644 audio/audio_test.go create mode 100644 audio/device_test.go create mode 100644 audio/output_darwin.c create mode 100644 audio/output_darwin.go create mode 100644 audio/output_linux.go create mode 100644 audio/output_linux_other.go create mode 100644 audio/output_other.go create mode 100644 audio/output_windows.go create mode 100644 docs/audio.md diff --git a/README.md b/README.md index 23b258f85..a9c615ffd 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,10 @@ WebView and no bundled rendering runtime. - `Application.Post` hands work a background goroutine finished to the window thread: accepted functions run there in order, with no goroutine, timer or blocking wait added, and no "call the loop and wait" form that could deadlock. +- `audio.Open` plays interleaved 16-bit PCM on the system's default output + (AudioUnit on macOS, WASAPI shared mode on Windows, ALSA on Linux), with no + background work and no backend linked into an application that does not + import it. See [docs/audio.md](docs/audio.md). - `app/proxy.SystemProxy` reports the proxy the desktop selects for an HTTP URL: CFNetwork on macOS, WinHTTP's automatic proxy on Windows (PAC, WPAD and the static settings), and the environment on Linux. A policy the platform cannot diff --git a/audio/audio.go b/audio/audio.go new file mode 100644 index 000000000..7d4b12280 --- /dev/null +++ b/audio/audio.go @@ -0,0 +1,249 @@ +// Package audio plays PCM sound on the system's default output device. +// +// It is a small synchronous output: [Open] opens a stream for one format, +// [Output.Write] hands it interleaved frames, and [Output.Close] releases the +// device. The platform backend converts the stream to what the device plays +// (an AudioUnit on macOS, WASAPI shared mode on Windows, ALSA's default plugin +// on Linux), so a caller supplies the format it has — a remote desktop +// server's PCM — not the device's. +// +// An application that never imports this package links no backend and runs +// nothing. While an [Output] is open it holds one goroutine, a fixed ring +// buffer, and the device; an idle application holds none of them. +package audio + +import ( + "errors" + "fmt" + "runtime" + "sync" +) + +var ( + // ErrUnsupported reports that this build target, or the system, has no + // output that can play the stream: the package is not implemented for the + // platform, the system library is missing, or no default device exists. + ErrUnsupported = errors.New("audio: no output device is available") + // ErrClosed reports a Write after Close. + ErrClosed = errors.New("audio: output is closed") + // ErrFrame reports data that does not hold whole frames. + ErrFrame = errors.New("audio: the data does not hold whole frames") + // ErrFormat reports a format this package cannot play. + ErrFormat = errors.New("audio: unsupported format") +) + +// Format is the shape of a stream: signed 16-bit little-endian samples, +// interleaved frame by frame. The backend converts it to the device's own +// format and rate when they differ. +type Format struct { + // SampleRate is frames per second. + SampleRate int + // Channels is the number of interleaved samples in a frame: one or two. + Channels int +} + +const ( + minSampleRate = 8000 + maxSampleRate = 192000 +) + +func (f Format) valid() error { + if f.SampleRate < minSampleRate || f.SampleRate > maxSampleRate { + return fmt.Errorf("%w: %d samples per second", ErrFormat, f.SampleRate) + } + if f.Channels < 1 || f.Channels > 2 { + return fmt.Errorf("%w: %d channels", ErrFormat, f.Channels) + } + return nil +} + +// Output is a stream playing on the default output device. It implements +// io.Writer; each Write carries whole frames of the format given to Open. +// +// Write blocks while the device already holds enough sound, so a producer +// that reads from a network needs no buffer of its own beyond this one. +type Output struct { + format Format + align int + + mu sync.Mutex + cond *sync.Cond + ring []byte + read int64 // bytes the device has taken, as an absolute stream offset + wrote int64 // bytes accepted from the caller + closed bool + failed error + dev device + openErr error + done chan struct{} + ready chan struct{} +} + +// ringDurationScale divides a second into the ring's duration: the ring holds +// a fifth of a second of sound when the device falls behind. It absorbs a +// network burst without adding a fixed delay in steady state, where the device +// takes each write as it arrives. +const ringDurationScale = 5 + +// Open opens the default output device for format. It returns ErrUnsupported +// when the platform, the system library or the system's default device cannot +// play; the caller then has no sound and the rest of its work is unaffected. +func Open(format Format) (*Output, error) { + if err := format.valid(); err != nil { + return nil, err + } + ringBytes := format.SampleRate / ringDurationScale * format.Channels * 2 + if ringBytes < 4096 { + ringBytes = 4096 + } + o := &Output{ + format: format, + align: format.Channels * 2, + ring: make([]byte, ringBytes), + done: make(chan struct{}), + ready: make(chan struct{}), + } + o.cond = sync.NewCond(&o.mu) + go o.run() + <-o.ready + if o.openErr != nil { + return nil, o.openErr + } + return o, nil +} + +// Format returns the format given to Open. +func (o *Output) Format() Format { return o.format } + +// run owns the device. Platform device calls happen on this goroutine, whose +// operating-system thread is fixed: WASAPI's COM objects belong to the thread +// that created them, and CoreAudio and ALSA are happiest with one caller. +func (o *Output) run() { + runtime.LockOSThread() + defer close(o.done) + + dev, err := loadDevice(o.format) + o.mu.Lock() + o.openErr = err + if err != nil { + o.failed = err + } else { + o.dev = dev + } + o.mu.Unlock() + close(o.ready) + if err != nil { + return + } + + for { + o.mu.Lock() + for o.read == o.wrote && !o.closed && o.failed == nil { + o.cond.Wait() + } + if o.closed || o.failed != nil { + o.mu.Unlock() + break + } + start := o.read % int64(len(o.ring)) + n := min(o.wrote-o.read, int64(len(o.ring))-start) + chunk := o.ring[start : start+n] + o.mu.Unlock() + + err := dev.write(chunk) + + o.mu.Lock() + if err != nil { + o.failed = err + o.cond.Broadcast() + o.mu.Unlock() + break + } + o.read += n + o.cond.Broadcast() + o.mu.Unlock() + } + dev.close() +} + +// Write plays pcm, interleaved frames of the format given to Open, and blocks +// while the ring is full. It reports the whole of pcm or the error that ended +// the stream; a partial count means the device failed or Close interrupted it. +func (o *Output) Write(pcm []byte) (int, error) { + if len(pcm)%o.align != 0 { + return 0, ErrFrame + } + o.mu.Lock() + defer o.mu.Unlock() + if o.closed { + return 0, ErrClosed + } + if o.failed != nil { + return 0, o.failed + } + written := 0 + for written < len(pcm) { + for o.wrote-o.read == int64(len(o.ring)) && !o.closed && o.failed == nil { + o.cond.Wait() + } + if o.closed { + return written, ErrClosed + } + if o.failed != nil { + return written, o.failed + } + space := int64(len(o.ring)) - (o.wrote - o.read) + n := int(min(space, int64(len(pcm)-written))) + start := o.wrote % int64(len(o.ring)) + if start+int64(n) <= int64(len(o.ring)) { + copy(o.ring[start:start+int64(n)], pcm[written:written+n]) + } else { + first := copy(o.ring[start:], pcm[written:written+n]) + copy(o.ring[:n-first], pcm[written+first:written+n]) + } + o.wrote += int64(n) + written += n + o.cond.Broadcast() + } + return written, nil +} + +// Close stops the stream and releases the device; sound the device has not +// taken yet is discarded. It is safe to call more than once, and unblocks a +// Write waiting for room with ErrClosed. +func (o *Output) Close() error { + o.mu.Lock() + if o.closed { + o.mu.Unlock() + <-o.done + return nil + } + o.closed = true + o.cond.Broadcast() + o.mu.Unlock() + <-o.done + return nil +} + +// loadDevice opens the platform device, turning a backend panic (a missing +// library symbol, for example) into an ordinary error: sound is optional, and +// an application must not die because its machine has none. +func loadDevice(format Format) (dev device, err error) { + defer func() { + if recovered := recover(); recovered != nil { + dev, err = nil, fmt.Errorf("audio: %v", recovered) + } + }() + return openDevice(format) +} + +// device is one platform's output. write plays interleaved frames of the +// format given to openDevice and must copy pcm before returning: the ring may +// reuse it afterwards. It blocks while the device already holds enough. +type device interface { + write(pcm []byte) error + close() +} + +// openDevice is the platform's implementation. Tests replace it. +var openDevice = platformDevice diff --git a/audio/audio_test.go b/audio/audio_test.go new file mode 100644 index 000000000..5b4601445 --- /dev/null +++ b/audio/audio_test.go @@ -0,0 +1,237 @@ +package audio + +import ( + "bytes" + "errors" + "sync" + "testing" + "time" +) + +// fakeDevice records what the output goroutine hands it. wait makes write +// block until the test releases it, which fills the ring. +type fakeDevice struct { + mu sync.Mutex + data []byte + closed bool + fail error + wait chan struct{} + discard bool +} + +func (d *fakeDevice) write(pcm []byte) error { + if d.wait != nil { + <-d.wait + } + if d.fail != nil { + return d.fail + } + if !d.discard { + d.mu.Lock() + d.data = append(d.data, pcm...) + d.mu.Unlock() + } + return nil +} + +func (d *fakeDevice) close() { + d.mu.Lock() + d.closed = true + d.mu.Unlock() +} + +func (d *fakeDevice) played() []byte { + d.mu.Lock() + defer d.mu.Unlock() + return append([]byte(nil), d.data...) +} + +func withDevice(t testing.TB, d device, err error) { + t.Helper() + previous := openDevice + openDevice = func(Format) (device, error) { return d, err } + t.Cleanup(func() { openDevice = previous }) +} + +func testFormat() Format { return Format{SampleRate: 8000, Channels: 2} } + +func TestOpenRejectsBadFormats(t *testing.T) { + for _, format := range []Format{ + {SampleRate: 0, Channels: 2}, + {SampleRate: 7999, Channels: 2}, + {SampleRate: 8000, Channels: 0}, + {SampleRate: 8000, Channels: 3}, + } { + if _, err := Open(format); !errors.Is(err, ErrFormat) { + t.Errorf("Open(%+v) error = %v, want ErrFormat", format, err) + } + } +} + +func TestOpenReportsPlatformError(t *testing.T) { + withDevice(t, nil, ErrUnsupported) + if _, err := Open(testFormat()); !errors.Is(err, ErrUnsupported) { + t.Fatalf("Open error = %v, want ErrUnsupported", err) + } +} + +func TestWritePlaysInOrderAcrossRing(t *testing.T) { + dev := &fakeDevice{} + withDevice(t, dev, nil) + out, err := Open(testFormat()) + if err != nil { + t.Fatal(err) + } + // More than the 6400-byte ring, so the device drains it more than once. + var pcm []byte + for i := 0; i < 5000; i++ { + pcm = append(pcm, byte(i), byte(i>>8), byte(i>>16), byte(i>>24)) + } + if n, err := out.Write(pcm); err != nil || n != len(pcm) { + t.Fatalf("Write = %d, %v", n, err) + } + // The device takes the ring asynchronously; let it drain before Close, + // which stops the stream rather than waiting for the device. + time.Sleep(50 * time.Millisecond) + if err := out.Close(); err != nil { + t.Fatal(err) + } + if got := dev.played(); !bytes.Equal(got, pcm) { + t.Fatalf("played %d bytes, want %d identical bytes", len(got), len(pcm)) + } +} + +func TestWriteBlocksWhileRingIsFull(t *testing.T) { + dev := &fakeDevice{wait: make(chan struct{})} + withDevice(t, dev, nil) + out, err := Open(testFormat()) + if err != nil { + t.Fatal(err) + } + // The ring is 6400 bytes and the device holds its first write forever, so + // the second half of this write can only complete once the device takes + // the first. + pcm := make([]byte, 12800) + done := make(chan error, 1) + go func() { + _, err := out.Write(pcm) + done <- err + }() + select { + case err := <-done: + t.Fatalf("Write returned %v while the device held the ring", err) + case <-time.After(50 * time.Millisecond): + } + close(dev.wait) + if err := <-done; err != nil { + t.Fatalf("Write after the device drained: %v", err) + } + if err := out.Close(); err != nil { + t.Fatal(err) + } +} + +func TestCloseUnblocksWrite(t *testing.T) { + dev := &fakeDevice{wait: make(chan struct{})} + withDevice(t, dev, nil) + out, err := Open(testFormat()) + if err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { + _, err := out.Write(make([]byte, 12800)) + done <- err + }() + time.Sleep(50 * time.Millisecond) + close(dev.wait) + if err := out.Close(); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if !errors.Is(err, ErrClosed) && err != nil { + t.Fatalf("Write after Close = %v, want ErrClosed", err) + } + case <-time.After(time.Second): + t.Fatal("Write did not return after Close") + } +} + +func TestWriteAfterClose(t *testing.T) { + withDevice(t, &fakeDevice{}, nil) + out, err := Open(testFormat()) + if err != nil { + t.Fatal(err) + } + if err := out.Close(); err != nil { + t.Fatal(err) + } + if err := out.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } + if _, err := out.Write(make([]byte, 4)); !errors.Is(err, ErrClosed) { + t.Fatalf("Write after Close = %v, want ErrClosed", err) + } +} + +func TestWriteRejectsPartialFrames(t *testing.T) { + withDevice(t, &fakeDevice{}, nil) + out, err := Open(testFormat()) + if err != nil { + t.Fatal(err) + } + defer out.Close() + if _, err := out.Write(make([]byte, 6)); !errors.Is(err, ErrFrame) { + t.Fatalf("Write of 6 bytes = %v, want ErrFrame", err) + } +} + +func TestDeviceFailureReachesLaterWrites(t *testing.T) { + broken := errors.New("device gone") + dev := &fakeDevice{fail: broken} + withDevice(t, dev, nil) + out, err := Open(testFormat()) + if err != nil { + t.Fatal(err) + } + defer out.Close() + // More than the ring holds: the write waits for the device, which fails. + _, err = out.Write(make([]byte, 12800)) + if !errors.Is(err, broken) { + t.Fatalf("Write = %v, want the device error", err) + } +} + +func TestNothingIsPlayedWithoutWrite(t *testing.T) { + dev := &fakeDevice{} + withDevice(t, dev, nil) + out, err := Open(testFormat()) + if err != nil { + t.Fatal(err) + } + time.Sleep(20 * time.Millisecond) + if n := len(dev.played()); n != 0 { + t.Fatalf("device got %d bytes without a Write", n) + } + out.Close() +} + +func BenchmarkWrite(b *testing.B) { + dev := &fakeDevice{discard: true} + withDevice(b, dev, nil) + out, err := Open(testFormat()) + if err != nil { + b.Fatal(err) + } + defer out.Close() + pcm := make([]byte, 640) + b.SetBytes(int64(len(pcm))) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if _, err := out.Write(pcm); err != nil { + b.Fatal(err) + } + } +} diff --git a/audio/device_test.go b/audio/device_test.go new file mode 100644 index 000000000..74e092957 --- /dev/null +++ b/audio/device_test.go @@ -0,0 +1,34 @@ +package audio + +import ( + "os" + "testing" + "time" +) + +// TestOutputDevice plays silence on the machine's default output. Audio has +// no headless substitute, so it is opt-in: VIVA_AUDIO_TEST=1 runs it. +func TestOutputDevice(t *testing.T) { + if os.Getenv("VIVA_AUDIO_TEST") == "" { + t.Skip("set VIVA_AUDIO_TEST=1 to open the default output device") + } + for _, format := range []Format{ + {SampleRate: 48000, Channels: 2}, + {SampleRate: 44100, Channels: 2}, + {SampleRate: 48000, Channels: 1}, + } { + out, err := Open(format) + if err != nil { + t.Fatalf("Open(%+v): %v", format, err) + } + // 200 ms of silence, then let the device consume it. + silence := make([]byte, format.SampleRate/5*format.Channels*2) + if n, err := out.Write(silence); err != nil || n != len(silence) { + t.Fatalf("Write(%+v) = %d, %v", format, n, err) + } + time.Sleep(300 * time.Millisecond) + if err := out.Close(); err != nil { + t.Fatalf("Close(%+v): %v", format, err) + } + } +} diff --git a/audio/output_darwin.c b/audio/output_darwin.c new file mode 100644 index 000000000..a6b7abd37 --- /dev/null +++ b/audio/output_darwin.c @@ -0,0 +1,232 @@ +//go:build darwin + +#include +#include +#include +#include +#include + +typedef struct viva_audio viva_audio; + +// viva_audio is a ring buffer feeding the default output AudioUnit. The unit's +// render callback runs on CoreAudio's own thread and takes the lock only to +// move bytes; Go never runs on that thread. +struct viva_audio { + pthread_mutex_t mutex; + pthread_cond_t cond; + uint8_t *data; + size_t capacity; // bytes + size_t frame; // bytes per frame + size_t read; // byte offset of the oldest frame + size_t used; // bytes waiting to play + AudioUnit unit; + int started; + int closed; +}; + +static size_t viva_min(size_t a, size_t b) { return a < b ? a : b; } + +static OSStatus viva_audio_render(void *ref, AudioUnitRenderActionFlags *flags, + const AudioTimeStamp *timestamp, UInt32 bus, + UInt32 frames, AudioBufferList *buffers) { + (void)flags; + (void)timestamp; + (void)bus; + struct viva_audio *a = ref; + size_t need = (size_t)frames * a->frame; + + pthread_mutex_lock(&a->mutex); + // The input scope carries one interleaved buffer. Anything else is a + // format CoreAudio did not accept, and silence is the safe answer. + if (buffers->mNumberBuffers != 1) { + for (UInt32 i = 0; i < buffers->mNumberBuffers; i++) { + memset(buffers->mBuffers[i].mData, 0, buffers->mBuffers[i].mDataByteSize); + } + pthread_mutex_unlock(&a->mutex); + return noErr; + } + AudioBuffer *buffer = &buffers->mBuffers[0]; + size_t wanted = buffer->mDataByteSize; + size_t take = viva_min(wanted, viva_min(need, a->used)); + uint8_t *dst = buffer->mData; + size_t first = viva_min(take, a->capacity - a->read); + memcpy(dst, a->data + a->read, first); + if (take > first) { + memcpy(dst + first, a->data, take - first); + } + if (take < wanted) { + memset(dst + take, 0, wanted - take); + } + a->read = (a->read + take) % a->capacity; + a->used -= take; + pthread_cond_signal(&a->cond); + pthread_mutex_unlock(&a->mutex); + return noErr; +} + +viva_audio *viva_audio_open(double rate, uint32_t channels, int32_t *status) { + *status = 0; + if (rate < 8000 || rate > 192000 || channels < 1 || channels > 2) { + *status = kAudioUnitErr_InvalidParameter; + return NULL; + } + + AudioComponentDescription description = { + .componentType = kAudioUnitType_Output, + .componentSubType = kAudioUnitSubType_DefaultOutput, + .componentManufacturer = kAudioUnitManufacturer_Apple, + }; + AudioComponent component = AudioComponentFindNext(NULL, &description); + if (component == NULL) { + *status = -1; + return NULL; + } + + struct viva_audio *a = calloc(1, sizeof(*a)); + if (a == NULL) { + *status = kAudioUnitErr_NoConnection; + return NULL; + } + a->frame = (size_t)channels * 2; + a->capacity = (size_t)(rate / 5.0) * a->frame; + if (a->capacity < 4096) { + a->capacity = 4096; + } + a->capacity -= a->capacity % a->frame; + a->data = malloc(a->capacity); + if (a->data == NULL) { + free(a); + *status = kAudioUnitErr_NoConnection; + return NULL; + } + if (pthread_mutex_init(&a->mutex, NULL) != 0 || + pthread_cond_init(&a->cond, NULL) != 0) { + free(a->data); + free(a); + *status = kAudioUnitErr_NoConnection; + return NULL; + } + + OSStatus err = AudioComponentInstanceNew(component, &a->unit); + if (err != noErr) { + goto fail; + } + + AudioStreamBasicDescription format = { + .mSampleRate = rate, + .mFormatID = kAudioFormatLinearPCM, + .mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | + kLinearPCMFormatFlagIsPacked, + .mBytesPerPacket = (UInt32)a->frame, + .mFramesPerPacket = 1, + .mBytesPerFrame = (UInt32)a->frame, + .mChannelsPerFrame = channels, + .mBitsPerChannel = 16, + }; + err = AudioUnitSetProperty(a->unit, kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, 0, &format, + sizeof(format)); + if (err != noErr) { + goto fail; + } + + AURenderCallbackStruct callback = { + .inputProc = viva_audio_render, + .inputProcRefCon = a, + }; + err = AudioUnitSetProperty(a->unit, kAudioUnitProperty_SetRenderCallback, + kAudioUnitScope_Input, 0, &callback, + sizeof(callback)); + if (err != noErr) { + goto fail; + } + + err = AudioUnitInitialize(a->unit); + if (err != noErr) { + goto fail; + } + return a; + +fail: + *status = err; + AudioComponentInstanceDispose(a->unit); + pthread_mutex_destroy(&a->mutex); + pthread_cond_destroy(&a->cond); + free(a->data); + free(a); + return NULL; +} + +int64_t viva_audio_write(viva_audio *a, const void *pcm, uintptr_t len) { + if (len == 0) { + return 0; + } + const uint8_t *src = pcm; + size_t left = (size_t)len; + + pthread_mutex_lock(&a->mutex); + if (a->closed) { + pthread_mutex_unlock(&a->mutex); + return 0; + } + int start = !a->started && left > 0; + a->started = 1; + pthread_mutex_unlock(&a->mutex); + + if (start) { + OSStatus err = AudioOutputUnitStart(a->unit); + if (err != noErr) { + pthread_mutex_lock(&a->mutex); + a->started = 0; + pthread_mutex_unlock(&a->mutex); + return err; + } + } + + pthread_mutex_lock(&a->mutex); + while (left > 0) { + while (a->used == a->capacity && !a->closed) { + pthread_cond_wait(&a->cond, &a->mutex); + } + if (a->closed) { + pthread_mutex_unlock(&a->mutex); + return 0; + } + size_t write = (a->read + a->used) % a->capacity; + size_t room = a->capacity - a->used; + size_t first = viva_min(viva_min(left, room), a->capacity - write); + memcpy(a->data + write, src, first); + if (left > first && first < room) { + size_t second = viva_min(left - first, room - first); + memcpy(a->data, src + first, second); + first += second; + } + a->used += first; + src += first; + left -= first; + } + pthread_mutex_unlock(&a->mutex); + return (int64_t)len; +} + +void viva_audio_close(viva_audio *a) { + if (a == NULL) { + return; + } + pthread_mutex_lock(&a->mutex); + a->closed = 1; + pthread_cond_broadcast(&a->cond); + int started = a->started; + a->started = 0; + pthread_mutex_unlock(&a->mutex); + + if (started) { + AudioOutputUnitStop(a->unit); + } + AudioUnitUninitialize(a->unit); + AudioComponentInstanceDispose(a->unit); + pthread_mutex_destroy(&a->mutex); + pthread_cond_destroy(&a->cond); + free(a->data); + free(a); +} diff --git a/audio/output_darwin.go b/audio/output_darwin.go new file mode 100644 index 000000000..02350392e --- /dev/null +++ b/audio/output_darwin.go @@ -0,0 +1,62 @@ +//go:build darwin + +package audio + +/* +#cgo darwin LDFLAGS: -framework AudioToolbox -framework CoreAudio +#include + +typedef struct viva_audio viva_audio; + +viva_audio *viva_audio_open(double rate, uint32_t channels, int32_t *status); +int64_t viva_audio_write(viva_audio *a, const void *pcm, uintptr_t len); +void viva_audio_close(viva_audio *a); +*/ +import "C" + +import ( + "fmt" + "runtime" + "unsafe" +) + +// darwinDevice plays through the default output AudioUnit. The unit's input +// scope takes the stream's own format, so CoreAudio resamples and remixes it +// to the device's when they differ. +type darwinDevice struct { + handle *C.viva_audio +} + +func platformDevice(format Format) (device, error) { + var status C.int32_t + handle := C.viva_audio_open(C.double(format.SampleRate), C.uint32_t(format.Channels), &status) + if handle == nil { + if status == -1 { + return nil, fmt.Errorf("audio: the default output unit is missing: %w", ErrUnsupported) + } + return nil, fmt.Errorf("audio: open the default output unit: OSStatus %d", int32(status)) + } + return &darwinDevice{handle: handle}, nil +} + +func (d *darwinDevice) write(pcm []byte) error { + if len(pcm) == 0 { + return nil + } + written := C.viva_audio_write(d.handle, unsafe.Pointer(&pcm[0]), C.uintptr_t(len(pcm))) + runtime.KeepAlive(pcm) + if written < 0 { + return fmt.Errorf("audio: play on the output unit: OSStatus %d", int64(written)) + } + if int(written) != len(pcm) { + return fmt.Errorf("audio: play on the output unit: %d of %d bytes", int64(written), len(pcm)) + } + return nil +} + +func (d *darwinDevice) close() { + if d.handle != nil { + C.viva_audio_close(d.handle) + d.handle = nil + } +} diff --git a/audio/output_linux.go b/audio/output_linux.go new file mode 100644 index 000000000..fee369b1c --- /dev/null +++ b/audio/output_linux.go @@ -0,0 +1,205 @@ +//go:build linux && (amd64 || arm64) + +package audio + +import ( + "fmt" + "time" + "unsafe" + + "github.com/ebitengine/purego" +) + +// ALSA constants (alsa/pcm.h). +const ( + alsaPlayback = 0 + alsaNoWait = 1 // SND_PCM_NONBLOCK, deliberately not used + alsaAccessRWInter = 3 // SND_PCM_ACCESS_RW_INTERLEAVED + alsaFormatS16LE = 2 // SND_PCM_FORMAT_S16_LE + alsaRecoverRetries = 4 +) + +// alsaDevice plays through ALSA's "default" PCM, which on a desktop is the +// sound server (PipeWire or PulseAudio) or dmix/plug: the plugin converts the +// stream's format and rate to what the hardware takes. +type alsaDevice struct { + library uintptr + pcm uintptr + frame int // bytes per frame of the stream + api *alsaAPI +} + +type alsaAPI struct { + open func(pcm *uintptr, name *byte, stream int32, mode int32) int32 + close func(pcm uintptr) int32 + drop func(pcm uintptr) int32 + prepare func(pcm uintptr) int32 + recover func(pcm uintptr, err int32, silent int32) int32 + writei func(pcm uintptr, buf unsafe.Pointer, frames uintptr) int64 + strerror func(err int32) *byte + paramsMalloc func(params *uintptr) int32 + paramsFree func(params uintptr) + paramsAny func(pcm uintptr, params uintptr) int32 + setAccess func(pcm uintptr, params uintptr, access int32) int32 + setFormat func(pcm uintptr, params uintptr, format int32) int32 + setChannels func(pcm uintptr, params uintptr, channels uint32) int32 + setRate func(pcm uintptr, params uintptr, rate uint32, dir int32) int32 + setRateNear func(pcm uintptr, params uintptr, rate *uint32, dir *int32) int32 + params func(pcm uintptr, params uintptr) int32 +} + +func openALSA() (*alsaAPI, uintptr, error) { + var library uintptr + var err error + for _, name := range []string{"libasound.so.2", "libasound.so"} { + library = 0 + library, err = purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_LOCAL) + if err == nil { + break + } + } + if library == 0 { + return nil, 0, fmt.Errorf("audio: load libasound: %w", ErrUnsupported) + } + api := &alsaAPI{} + purego.RegisterLibFunc(&api.open, library, "snd_pcm_open") + purego.RegisterLibFunc(&api.close, library, "snd_pcm_close") + purego.RegisterLibFunc(&api.drop, library, "snd_pcm_drop") + purego.RegisterLibFunc(&api.prepare, library, "snd_pcm_prepare") + purego.RegisterLibFunc(&api.recover, library, "snd_pcm_recover") + purego.RegisterLibFunc(&api.writei, library, "snd_pcm_writei") + purego.RegisterLibFunc(&api.strerror, library, "snd_strerror") + purego.RegisterLibFunc(&api.paramsMalloc, library, "snd_pcm_hw_params_malloc") + purego.RegisterLibFunc(&api.paramsFree, library, "snd_pcm_hw_params_free") + purego.RegisterLibFunc(&api.paramsAny, library, "snd_pcm_hw_params_any") + purego.RegisterLibFunc(&api.setAccess, library, "snd_pcm_hw_params_set_access") + purego.RegisterLibFunc(&api.setFormat, library, "snd_pcm_hw_params_set_format") + purego.RegisterLibFunc(&api.setChannels, library, "snd_pcm_hw_params_set_channels") + purego.RegisterLibFunc(&api.setRate, library, "snd_pcm_hw_params_set_rate") + purego.RegisterLibFunc(&api.setRateNear, library, "snd_pcm_hw_params_set_rate_near") + purego.RegisterLibFunc(&api.params, library, "snd_pcm_hw_params") + return api, library, nil +} + +func platformDevice(format Format) (device, error) { + api, library, err := openALSA() + if err != nil { + return nil, err + } + name := []byte("default\x00") + var pcm uintptr + if status := api.open(&pcm, &name[0], alsaPlayback, 0); status < 0 { + message := alsaError(api, status) + purego.Dlclose(library) + return nil, fmt.Errorf("audio: open the ALSA default device: %s: %w", message, ErrUnsupported) + } + if err := configureALSA(api, pcm, format); err != nil { + api.close(pcm) + purego.Dlclose(library) + return nil, err + } + return &alsaDevice{library: library, pcm: pcm, frame: format.Channels * 2, api: api}, nil +} + +func configureALSA(api *alsaAPI, pcm uintptr, format Format) error { + var params uintptr + if status := api.paramsMalloc(¶ms); status < 0 { + return fmt.Errorf("audio: allocate ALSA parameters: %s", alsaError(api, status)) + } + defer api.paramsFree(params) + fail := func(step string, status int32) error { + return fmt.Errorf("audio: %s: %s", step, alsaError(api, status)) + } + if status := api.paramsAny(pcm, params); status < 0 { + return fail("read the ALSA device parameters", status) + } + if status := api.setAccess(pcm, params, alsaAccessRWInter); status < 0 { + return fail("set interleaved access", status) + } + if status := api.setFormat(pcm, params, alsaFormatS16LE); status < 0 { + return fail("set 16-bit PCM", status) + } + if status := api.setChannels(pcm, params, uint32(format.Channels)); status < 0 { + return fail("set the channel count", status) + } + if status := api.setRate(pcm, params, uint32(format.SampleRate), 0); status < 0 { + // A device without the plug plugin may still have a nearby rate; take + // it only if it is the one we asked for, since this package does not + // resample. + rate := uint32(format.SampleRate) + var dir int32 + if near := api.setRateNear(pcm, params, &rate, &dir); near < 0 || rate != uint32(format.SampleRate) { + return fail("set the sample rate", status) + } + } + if status := api.params(pcm, params); status < 0 { + return fail("apply the ALSA parameters", status) + } + if status := api.prepare(pcm); status < 0 { + return fail("prepare the ALSA device", status) + } + return nil +} + +func (d *alsaDevice) write(pcm []byte) error { + frame := d.frame + frames := len(pcm) / frame + offset := 0 + for offset < frames { + written := d.api.writei(d.pcm, unsafe.Pointer(&pcm[offset*frame]), uintptr(frames-offset)) + if written > 0 { + offset += int(written) + continue + } + if written == 0 { + // Blocking mode should not accept nothing; do not spin if it does. + time.Sleep(time.Millisecond) + continue + } + recovered := false + for range alsaRecoverRetries { + if status := d.api.recover(d.pcm, int32(written), 1); status < 0 { + return fmt.Errorf("audio: play on the ALSA device: %s", alsaError(d.api, status)) + } + written = d.api.writei(d.pcm, unsafe.Pointer(&pcm[offset*frame]), uintptr(frames-offset)) + if written >= 0 { + offset += int(written) + recovered = true + break + } + } + if !recovered { + return fmt.Errorf("audio: the ALSA device stopped accepting sound: %s", alsaError(d.api, int32(written))) + } + } + return nil +} + +func (d *alsaDevice) close() { + if d.pcm != 0 { + d.api.drop(d.pcm) + d.api.close(d.pcm) + d.pcm = 0 + } + if d.library != 0 { + purego.Dlclose(d.library) + d.library = 0 + } +} + +func alsaError(api *alsaAPI, status int32) string { + if message := api.strerror(status); message != nil { + return goString(message) + } + return fmt.Sprintf("status %d", status) +} + +func goString(text *byte) string { + if text == nil { + return "" + } + var length int + for ptr := unsafe.Pointer(text); *(*byte)(unsafe.Add(ptr, length)) != 0; length++ { + } + return string(unsafe.Slice(text, length)) +} diff --git a/audio/output_linux_other.go b/audio/output_linux_other.go new file mode 100644 index 000000000..34855d5b2 --- /dev/null +++ b/audio/output_linux_other.go @@ -0,0 +1,7 @@ +//go:build linux && !amd64 && !arm64 + +package audio + +// platformDevice on Linux architectures without the purego ABI support the +// rest of Viva uses. +func platformDevice(Format) (device, error) { return nil, ErrUnsupported } diff --git a/audio/output_other.go b/audio/output_other.go new file mode 100644 index 000000000..e0d684d44 --- /dev/null +++ b/audio/output_other.go @@ -0,0 +1,9 @@ +//go:build !darwin && !windows && !linux + +package audio + +// platformDevice is the build targets Viva does not give an audio backend: +// WebAssembly, and anything else Go can target. The package still compiles so +// that an application shared with a supported target does not need its own +// build tags. +func platformDevice(Format) (device, error) { return nil, ErrUnsupported } diff --git a/audio/output_windows.go b/audio/output_windows.go new file mode 100644 index 000000000..751e215be --- /dev/null +++ b/audio/output_windows.go @@ -0,0 +1,255 @@ +//go:build windows + +package audio + +import ( + "fmt" + "runtime" + "syscall" + "unsafe" + + "golang.org/x/sys/windows" +) + +// WASAPI constants (audioclient.h). +const ( + wasapiShareModeShared = 0 + wasapiEventCallback = 0x00040000 + wasapiAutoConvertPCM = 0x80000000 + wasapiSRCDefaultQuality = 0x08000000 + wasapiRender = 0 // eRender + wasapiConsole = 0 // eConsole + coinitMultithreaded = 0x0 + clsctxAll = 0x17 + coinitSFalse = 0x1 + hresultChangedMode = 0x80010106 + wasapiBufferDuration100ns = 100 * 10000 // 100 ms + waveFormatPCM = 1 +) + +type guid struct { + Data1 uint32 + Data2, Data3 uint16 + Data4 [8]byte +} + +var ( + clsidMMDeviceEnumerator = guid{0xBCDE0395, 0xE52F, 0x467C, [8]byte{0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}} + iidMMDeviceEnumerator = guid{0xA95664D2, 0x9614, 0x4F35, [8]byte{0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}} + iidAudioClient = guid{0x1CB9AD4C, 0xDBFA, 0x4C32, [8]byte{0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}} + iidAudioRenderClient = guid{0xF294ACFC, 0x3146, 0x4483, [8]byte{0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}} +) + +// waveFormatEx is WAVEFORMATEX (mmreg.h). cbSize stays zero for PCM. +type waveFormatEx struct { + FormatTag uint16 + Channels uint16 + SamplesPerSec uint32 + AvgBytesPerSec uint32 + BlockAlign uint16 + BitsPerSample uint16 + Size uint16 +} + +var ( + ole32 = windows.NewLazySystemDLL("ole32.dll") + coInitializeEx = ole32.NewProc("CoInitializeEx") + coUninitialize = ole32.NewProc("CoUninitialize") + coCreateInstance = ole32.NewProc("CoCreateInstance") +) + +// pointer and vtable read a COM interface the way the Windows platform package +// does: the object points at its vtable, and each method is one slot. +func pointer(address uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&address)) } + +func vtable(object uintptr, index int) uintptr { + return *(*uintptr)(unsafe.Add(pointer(*(*uintptr)(pointer(object))), index*int(unsafe.Sizeof(uintptr(0))))) +} + +//go:uintptrescapes +func comCall(object uintptr, index int, arguments ...uintptr) uintptr { + var values [16]uintptr + if len(arguments) >= len(values) { + panic("audio: COM call exceeds argument limit") + } + values[0] = object + copy(values[1:], arguments) + result, _, _ := syscall.SyscallN(vtable(object, index), values[:len(arguments)+1]...) + return result +} + +func release(object *uintptr) { + if *object != 0 { + comCall(*object, 2) // IUnknown::Release + *object = 0 + } +} + +func hresult(step string, result uintptr) error { + if int32(uint32(result)) < 0 { + return fmt.Errorf("audio: %s: HRESULT %#x", step, uint32(result)) + } + return nil +} + +// wasapiDevice plays through the default render endpoint in shared mode. The +// stream is initialized with its own PCM format and AUTOCONVERTPCM, so the +// audio engine resamples and remixes it to the device's mix format. +type wasapiDevice struct { + enumerator uintptr + endpoint uintptr + client uintptr + render uintptr + event windows.Handle + frames uint32 + started bool + format waveFormatEx +} + +func platformDevice(format Format) (device, error) { + result, _, _ := coInitializeEx.Call(0, coinitMultithreaded) + switch uint32(result) { + case 0, coinitSFalse: + case hresultChangedMode: + return nil, fmt.Errorf("audio: the audio thread is already in a COM apartment of another mode: %w", ErrUnsupported) + default: + return nil, hresult("initialize COM", result) + } + d := &wasapiDevice{} + if err := d.open(format); err != nil { + d.close() + return nil, err + } + return d, nil +} + +func (d *wasapiDevice) open(format Format) error { + r, _, _ := coCreateInstance.Call( + uintptr(unsafe.Pointer(&clsidMMDeviceEnumerator)), + 0, + clsctxAll, + uintptr(unsafe.Pointer(&iidMMDeviceEnumerator)), + uintptr(unsafe.Pointer(&d.enumerator)), + ) + runtime.KeepAlive(&clsidMMDeviceEnumerator) + runtime.KeepAlive(&iidMMDeviceEnumerator) + if err := hresult("create the audio endpoint enumerator", r); err != nil { + return fmt.Errorf("%w: %v", ErrUnsupported, err) + } + // IMMDeviceEnumerator::GetDefaultAudioEndpoint. + if r := comCall(d.enumerator, 4, wasapiRender, wasapiConsole, uintptr(unsafe.Pointer(&d.endpoint))); int32(uint32(r)) < 0 { + return fmt.Errorf("audio: no default output device: %w", ErrUnsupported) + } + // IMMDevice::Activate(IID_IAudioClient, ...). + if r := comCall(d.endpoint, 3, uintptr(unsafe.Pointer(&iidAudioClient)), clsctxAll, 0, uintptr(unsafe.Pointer(&d.client))); int32(uint32(r)) < 0 { + return hresult("activate the audio client", r) + } + + d.format = waveFormatEx{ + FormatTag: waveFormatPCM, + Channels: uint16(format.Channels), + SamplesPerSec: uint32(format.SampleRate), + BlockAlign: uint16(format.Channels * 2), + BitsPerSample: 16, + } + d.format.AvgBytesPerSec = d.format.SamplesPerSec * uint32(d.format.BlockAlign) + // IAudioClient::Initialize in shared mode. AUTOCONVERTPCM lets the engine + // accept this format whatever the device mixes at. + const flags = wasapiEventCallback | wasapiAutoConvertPCM | wasapiSRCDefaultQuality + if r := comCall(d.client, 3, + wasapiShareModeShared, + flags, + wasapiBufferDuration100ns, + 0, + uintptr(unsafe.Pointer(&d.format)), + 0, + ); int32(uint32(r)) < 0 { + return hresult("initialize the audio client", r) + } + runtime.KeepAlive(&d.format) + + if r := comCall(d.client, 4, uintptr(unsafe.Pointer(&d.frames))); int32(uint32(r)) < 0 { + return hresult("read the audio buffer size", r) + } + if d.frames == 0 { + return fmt.Errorf("audio: the audio client reported an empty buffer") + } + // IAudioClient::GetService(IID_IAudioRenderClient). + if r := comCall(d.client, 14, uintptr(unsafe.Pointer(&iidAudioRenderClient)), uintptr(unsafe.Pointer(&d.render))); int32(uint32(r)) < 0 { + return hresult("get the audio render client", r) + } + event, err := windows.CreateEvent(nil, 0, 0, nil) + if err != nil { + return fmt.Errorf("audio: create the audio event: %w", err) + } + d.event = event + // IAudioClient::SetEventHandle. + if r := comCall(d.client, 13, uintptr(event)); int32(uint32(r)) < 0 { + return hresult("set the audio event", r) + } + // IAudioClient::Start. + if r := comCall(d.client, 10); int32(uint32(r)) < 0 { + return hresult("start the audio client", r) + } + d.started = true + return nil +} + +func (d *wasapiDevice) write(pcm []byte) error { + frameBytes := int(d.format.BlockAlign) + if frameBytes == 0 { + frameBytes = 4 + } + for len(pcm) > 0 { + var padding uint32 + if r := comCall(d.client, 6, uintptr(unsafe.Pointer(&padding))); int32(uint32(r)) < 0 { + return hresult("read the audio buffer padding", r) + } + free := d.frames + if padding < free { + free -= padding + } else { + free = 0 + } + if free == 0 { + windows.WaitForSingleObject(d.event, 200) + continue + } + frames := free + if want := uint32(len(pcm) / frameBytes); want < frames { + frames = want + } + if frames == 0 { + return nil + } + var data unsafe.Pointer + // IAudioRenderClient::GetBuffer. + if r := comCall(d.render, 3, uintptr(frames), uintptr(unsafe.Pointer(&data))); int32(uint32(r)) < 0 { + return hresult("get an audio buffer", r) + } + bytes := int(frames) * frameBytes + copy(unsafe.Slice((*byte)(data), bytes), pcm[:bytes]) + // IAudioRenderClient::ReleaseBuffer. + if r := comCall(d.render, 4, uintptr(frames), 0); int32(uint32(r)) < 0 { + return hresult("release an audio buffer", r) + } + pcm = pcm[bytes:] + } + return nil +} + +func (d *wasapiDevice) close() { + if d.client != 0 && d.started { + comCall(d.client, 11) // Stop + d.started = false + } + release(&d.render) + release(&d.client) + release(&d.endpoint) + release(&d.enumerator) + if d.event != 0 { + windows.CloseHandle(d.event) + d.event = 0 + } + coUninitialize.Call() +} diff --git a/docs/README.md b/docs/README.md index e4f5bf82c..231e2b9d2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -39,6 +39,8 @@ mentions every exported method and theme field. accessibility. - [system-integrations.md](system-integrations.md) — tray, menus, notifications, file drops, and the rest of the native surface. +- [audio.md](audio.md) — PCM output on the three native targets, what it does + not do, and its measured cost. - [web-deployment.md](web-deployment.md) — the browser build, its capability matrix, lifecycle mapping, static-hosting headers and security limits. - [diagnostics.md](diagnostics.md) — the structured event stream, its slog diff --git a/docs/audio.md b/docs/audio.md new file mode 100644 index 000000000..0123be2d1 --- /dev/null +++ b/docs/audio.md @@ -0,0 +1,106 @@ +# Audio output + +`audio` plays PCM on the system's default output device. It exists for a +stream an application receives from elsewhere — a remote desktop's sound, a +synthesized prompt — not for the system's own beeps, which `app.PlaySystemSound` +already covers. + +```go +out, err := audio.Open(audio.Format{SampleRate: 48000, Channels: 2}) +if err != nil { + // No device on this machine: carry on without sound. +} +defer out.Close() +for block := range blocks { + out.Write(block) // interleaved signed 16-bit little-endian frames +} +``` + +`Output` implements `io.Writer`. `Write` blocks while the device holds enough +sound, so a producer reading from a socket needs no buffer of its own. `Close` +stops the stream and releases the device; sound the device has not taken yet is +discarded. It is safe to call more than once. + +## What it is not + +- It does not decode. It accepts signed 16-bit little-endian PCM, one or two + channels. +- It has no volume control. The stream follows the system's output volume and + mute, which is what a remote desktop wants: the machine's own controls stay + authoritative. +- It does not capture the microphone. Audio input is a separate capability and + is not implemented. +- It does not exist on WebAssembly. `Open` returns `ErrUnsupported`. + +## Backends + +| Target | Backend | Format handling | +| --- | --- | --- | +| macOS | `AudioUnit` (`kAudioUnitSubType_DefaultOutput`), cgo | The unit's input scope is set to the stream's format; CoreAudio resamples and remixes to the device. | +| Windows | WASAPI shared mode, COM through `syscall`/`purego`, no cgo | The client is initialized with `AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` and the stream's format, so the audio engine converts to the device mix format. Requires Windows 7 or newer. | +| Linux | ALSA `default` PCM through `dlopen("libasound.so.2")`, `purego`, no cgo | The `plug`/sound-server path converts the format and rate. Only `amd64` and `arm64` have the purego ABI path; other architectures return `ErrUnsupported`. | + +The device is opened when `Open` is called and stays open until `Close`. +While an `Output` is open it owns one goroutine (whose OS thread is fixed for +WASAPI's COM apartment), a 200 ms ring buffer, and the platform player. An +application that never imports `audio` links none of it; one that imports it +but never opens an `Output` starts no goroutine and opens no device. + +`Write` copies into the ring and returns; the device drains it on the output +goroutine. The ring holds a fifth of a second, which absorbs a burst from a +network without adding a fixed delay in steady state, where the device takes +each block as it arrives. + +## Verification + +- `go test ./audio` covers format validation, ordering across the ring, a full + ring blocking and `Close` unblocking it, device errors, partial frames, and + the no-write path. The ring path is allocation-free. +- `VIVA_AUDIO_TEST=1 go test ./audio -run TestOutputDevice` opens the real + default device on macOS and plays 200 ms of silence at 48 kHz/44.1 kHz, + stereo and mono. Audio has no headless substitute, so this is opt-in. +- The Windows backend was run on a real Windows 11 machine from inside an RDP + session, which gives the session a "Remote Audio" endpoint: `Open` at + 44.1 kHz stereo, a 200 ms write, and `Close` all succeeded. The same build + outside a session, on a machine with no audio device, returned + `ErrUnsupported` from `GetDefaultAudioEndpoint`. +- Linux was run on a Ubuntu 22.04.3 machine: the test binary opened ALSA's + `default` PCM (PulseAudio's `auto_null` sink, 44.1 kHz stereo), wrote 200 ms + at 48 kHz/44.1 kHz stereo and mono, and closed, all successfully. That is the + full ALSA path through the sound server, not a physical device: + + ```sh + GOOS=linux GOARCH=amd64 go test -c -o /tmp/audio-linux.test ./audio + tools/testenv/upload.sh linux /tmp/audio-linux.test /home/user/audio.test + tools/testenv/exec.sh linux 'VIVA_AUDIO_TEST=1 XDG_RUNTIME_DIR=/run/user/1000 \ + /home/user/audio.test -test.run TestOutputDevice -test.v' + ``` +- `go vet` cross-compiles the package for `windows/amd64`, `linux/amd64`, + `darwin/arm64` and `js/wasm`. + +Measured on an Apple M2 Pro, macOS 24.5.0, Go 1.26.0: + +``` +BenchmarkWrite-10 1179094 1070 ns/op 598.06 MB/s 0 B/op 0 allocs/op +``` + +Stripped binary size, `-trimpath -ldflags="-s -w"`, compared with a minimal +Viva application that imports `app` and does not import `audio` (the marginal +cost an application pays only if it uses this package): + +| Target | Without `audio` | With `audio` | Delta | +| --- | ---: | ---: | ---: | +| darwin/arm64 | 2,588,594 B | 2,639,330 B | +50,736 B | +| linux/amd64 | 2,093,321 B | 2,121,993 B | +28,672 B | +| windows/amd64 | 3,065,856 B | 3,185,152 B | +119,296 B | + +The Windows delta includes the WASAPI COM call path that a minimal `app` +build does not otherwise reference. A standalone program's delta is larger +(about 0.5–0.7 MB) because it then also links `purego` and the parts of +`golang.org/x/sys/windows` the backend uses; that is not the cost a Viva +application pays. + +Windows playback has been exercised through a real RDP session's audio +endpoint, and Linux playback through PulseAudio's null sink. Neither has been +run on a machine with a physical output device; cross-compilation and `go vet` +cover the builds until one is. From d36f87e2234ab57122e86044463c63e20ad998d4 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 22:43:08 +0800 Subject: [PATCH 15/15] chore(testenv): move the Linux harness to its new machine --- tools/conformance/run.sh | 19 ++++++++++++++++--- tools/testenv/README.md | 28 ++++++++++++++++------------ tools/testenv/env.sh | 11 +++++++++-- tools/testenv/go-test.sh | 7 ++++++- tools/visualparity/run_all.sh | 3 ++- 5 files changed, 49 insertions(+), 19 deletions(-) diff --git a/tools/conformance/run.sh b/tools/conformance/run.sh index db68da555..36223ff2e 100755 --- a/tools/conformance/run.sh +++ b/tools/conformance/run.sh @@ -13,6 +13,7 @@ # FAIL or could not be reached. set -u root=$(cd "$(dirname "$0")/../.." && pwd) +. "$root/tools/testenv/env.sh" linux_env=${VIVA_LINUX_ENV:-} export no_proxy="${no_proxy:-},localhost,127.0.0.1" out=$(mktemp -d) @@ -42,9 +43,21 @@ run_linux() { fi (cd "$root" && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -o "$out/linux" ./cmd/viva-conformance) || return 1 upload "$linux_env" /home/user/viva-conformance "$out/linux" || return 1 - # The container's X server is :1; its GPU is software Vulkan (lavapipe). The session bus - # address changes with each login, so it is read from the desktop shell's environment. - execute "$linux_env" '{"command":["bash","-c","chmod +x /home/user/viva-conformance; export DISPLAY=:1 XAUTHORITY=/home/user/.Xauthority; pid=$(pgrep -u user plasmashell | head -1); if [ -r /proc/$pid/environ ]; then export $(xargs -0 -n1 -a /proc/$pid/environ | grep ^DBUS_SESSION_BUS_ADDRESS=); fi; if [ -f /tmp/viva-vulkan/lvp-local.json ]; then export VK_ICD_FILENAMES=/tmp/viva-vulkan/lvp-local.json LD_LIBRARY_PATH=/tmp/viva-vulkan/root/usr/lib/x86_64-linux-gnu; fi; cd /tmp && timeout 50 /home/user/viva-conformance"],"shell":false}' + # The desktop's display comes from VIVA_LINUX_DISPLAY (GNOME on X at :0 on the + # current machine). Its GPU is software Vulkan (lavapipe). The session bus + # address changes with each login; the standard per-user socket is used, with + # the desktop shell's environment as a fallback. + remote_env="HOME=/home/user DISPLAY=$VIVA_LINUX_DISPLAY XDG_RUNTIME_DIR=$VIVA_LINUX_RUNTIME_DIR" + if [ -n "$VIVA_LINUX_XAUTHORITY" ]; then + remote_env="$remote_env XAUTHORITY=$VIVA_LINUX_XAUTHORITY" + fi + remote_command="chmod +x /home/user/viva-conformance +bus=/run/user/\$(id -u)/bus +if [ -S \"\$bus\" ]; then export DBUS_SESSION_BUS_ADDRESS=unix:path=\$bus; else pid=\$(pgrep -u user 'gnome-shell|plasmashell' | head -1); if [ -r /proc/\$pid/environ ]; then export \$(xargs -0 -n1 -a /proc/\$pid/environ | grep ^DBUS_SESSION_BUS_ADDRESS=); fi; fi +if [ -f /tmp/viva-vulkan/lvp-local.json ]; then export VK_ICD_FILENAMES=/tmp/viva-vulkan/lvp-local.json LD_LIBRARY_PATH=/tmp/viva-vulkan/root/usr/lib/x86_64-linux-gnu; fi +cd /tmp && env $remote_env timeout 50 /home/user/viva-conformance" + payload=$(python3 -c 'import json,sys; print(json.dumps({"command":["bash","-c",sys.argv[1]],"shell":False}))' "$remote_command") + execute "$linux_env" "$payload" } run() { diff --git a/tools/testenv/README.md b/tools/testenv/README.md index f9eb68750..05c939f65 100644 --- a/tools/testenv/README.md +++ b/tools/testenv/README.md @@ -19,10 +19,11 @@ machine and record what was not automated. | | Linux | | --- | --- | -| System | Debian 12 x86_64 desktop container, Xvnc 1920x1080, `DISPLAY=:1` | -| Graphics | no Vulkan or discrete GPU: software rendering only (the CPU rasterizer; a software Vulkan build may be installed separately) | +| System | Ubuntu 22.04.3 x86_64 desktop VM, GNOME on X, 1920x1080, `DISPLAY=:0` (set by `VIVA_LINUX_DISPLAY`) | +| Graphics | no discrete GPU; software Vulkan (lavapipe) is installed | +| Audio | PulseAudio with an `auto_null` sink; ALSA's `default` PCM plays there | | API | `${VIVA_LINUX_ENV}` | -| Watch the screen | a VNC view served beside the API, self-signed | +| Watch the screen | a web desktop at the port beside the API (no password), and a native VNC port on the other side; `local.sh` records both | | User | an ordinary desktop user with sudo (`user`, password in `local.sh`) | ## HTTP API @@ -55,15 +56,18 @@ Set `VIVA_LINUX_ENV` when calling `tools/conformance/run.sh` or ## Linux notes -- GUI programs need `DISPLAY=:1` and `XAUTHORITY=/home/user/.Xauthority`. A - changed `HOME` loses the latter. -- The session bus is the one in `/proc//environ`. -- Software Vulkan is either a private copy under a private `/tmp` directory (the variables - are in `tools/conformance/run.sh`) or, on a freshly rebuilt machine, the - system's. Install it with `sudo apt-get update` followed by - `apt-get install mesa-vulkan-drivers`, as a `setsid nohup` script; the package - index is stale until updated. -- `xdotool` is installed. +- GUI programs need `DISPLAY=$VIVA_LINUX_DISPLAY` (currently `:0`) and + `XDG_RUNTIME_DIR=$VIVA_LINUX_RUNTIME_DIR`. The current machine needs no X + authority file; `VIVA_LINUX_XAUTHORITY` is empty. An older Xvnc machine used + `:1` and `/home/user/.Xauthority`; both scripts read the variables so neither + is hard-coded. +- The session bus is `/run/user/1000/bus`. The conformance script falls back to + the desktop shell's environment (`gnome-shell` or `plasmashell`) if the socket + is absent. +- Software Vulkan is the system's lavapipe (the ICD is in + `/usr/share/vulkan/icd.d`). The private `/tmp/viva-vulkan` copy remains a + fallback for machines without it. +- `xdotool` and `vulkaninfo` are not installed on the current machine. - Many threads in a Viva process there are lavapipe's pool, not Viva's. ## Platform conformance diff --git a/tools/testenv/env.sh b/tools/testenv/env.sh index fb1834fe5..18766d62a 100755 --- a/tools/testenv/env.sh +++ b/tools/testenv/env.sh @@ -1,9 +1,16 @@ # Address of your own Linux test environment. Source this file. # Export VIVA_LINUX_ENV, or put that export in tools/testenv/local.sh, which is # ignored by git. -here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +here=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) if [ -f "$here/local.sh" ]; then . "$here/local.sh"; fi VIVA_LINUX_ENV=${VIVA_LINUX_ENV:-} -export VIVA_LINUX_ENV +# The desktop's display and X authority file. The current machine runs GNOME on +# X at :0 and needs no authority file; an older Xvnc machine used :1 and +# /home/user/.Xauthority. +VIVA_LINUX_DISPLAY=${VIVA_LINUX_DISPLAY:-:0} +VIVA_LINUX_XAUTHORITY=${VIVA_LINUX_XAUTHORITY:-} +# The session's runtime directory (PulseAudio and the session bus live in it). +VIVA_LINUX_RUNTIME_DIR=${VIVA_LINUX_RUNTIME_DIR:-/run/user/1000} +export VIVA_LINUX_ENV VIVA_LINUX_DISPLAY VIVA_LINUX_XAUTHORITY VIVA_LINUX_RUNTIME_DIR # Keep a developer proxy out of the way when the environment is on the LAN. export no_proxy="${no_proxy:-},localhost,127.0.0.1" diff --git a/tools/testenv/go-test.sh b/tools/testenv/go-test.sh index f3b39b3cf..9fddad89c 100755 --- a/tools/testenv/go-test.sh +++ b/tools/testenv/go-test.sh @@ -9,6 +9,7 @@ # one, otherwise the system's (mesa-vulkan-drivers). With neither, graphics tests skip. set -eu here=$(dirname "$0") +. "$here/env.sh" platform=$1 package=$2 shift 2 name=$(echo "$package" | tr '/.' '__') @@ -17,7 +18,11 @@ case "$platform" in linux) GOOS=linux GOARCH=amd64 go test -c -o "$out/t" "$package" "$here/upload.sh" linux "$out/t" "/home/user/gotest-$name" - "$here/exec.sh" linux "chmod +x /home/user/gotest-$name; mkdir -p /tmp/gotest-home /tmp/gotest-run-$name; cd /tmp/gotest-run-$name; export HOME=/tmp/gotest-home SHELL=/bin/bash DISPLAY=:1 XAUTHORITY=/home/user/.Xauthority; if [ -f /tmp/viva-vulkan/lvp-local.json ]; then export VK_ICD_FILENAMES=/tmp/viva-vulkan/lvp-local.json LD_LIBRARY_PATH=/tmp/viva-vulkan/root/usr/lib/x86_64-linux-gnu; fi; timeout 100 /home/user/gotest-$name -test.count=1 $* 2>&1 | tail -40" + remote_env="HOME=/tmp/gotest-home SHELL=/bin/bash XDG_RUNTIME_DIR=$VIVA_LINUX_RUNTIME_DIR DISPLAY=$VIVA_LINUX_DISPLAY" + if [ -n "$VIVA_LINUX_XAUTHORITY" ]; then + remote_env="$remote_env XAUTHORITY=$VIVA_LINUX_XAUTHORITY" + fi + "$here/exec.sh" linux "chmod +x /home/user/gotest-$name; mkdir -p /tmp/gotest-home /tmp/gotest-run-$name; cd /tmp/gotest-run-$name; if [ -f /tmp/viva-vulkan/lvp-local.json ]; then export VK_ICD_FILENAMES=/tmp/viva-vulkan/lvp-local.json LD_LIBRARY_PATH=/tmp/viva-vulkan/root/usr/lib/x86_64-linux-gnu; fi; env $remote_env timeout 100 /home/user/gotest-$name -test.count=1 $* 2>&1 | tail -40" ;; *) echo "first argument is linux" >&2 diff --git a/tools/visualparity/run_all.sh b/tools/visualparity/run_all.sh index 58646b97e..aaaa27fea 100755 --- a/tools/visualparity/run_all.sh +++ b/tools/visualparity/run_all.sh @@ -31,7 +31,8 @@ for platform in "${platforms[@]}"; do #!/bin/bash chmod +x /home/user/$TAG rm -rf /tmp/$TAG-out; mkdir -p /tmp/$TAG-home /tmp/$TAG-run; cd /tmp/$TAG-run -export HOME=/tmp/$TAG-home SHELL=/bin/bash DISPLAY=:1 XAUTHORITY=/home/user/.Xauthority +export HOME=/tmp/$TAG-home SHELL=/bin/bash XDG_RUNTIME_DIR=$VIVA_LINUX_RUNTIME_DIR DISPLAY=$VIVA_LINUX_DISPLAY +if [ -n "$VIVA_LINUX_XAUTHORITY" ]; then export XAUTHORITY=$VIVA_LINUX_XAUTHORITY; fi if [ -f /tmp/viva-vulkan/lvp-local.json ]; then export VK_ICD_FILENAMES=/tmp/viva-vulkan/lvp-local.json LD_LIBRARY_PATH=/tmp/viva-vulkan/root/usr/lib/x86_64-linux-gnu; fi timeout 600 /home/user/$TAG run -out /tmp/$TAG-out -scales 1,1.5,2 > /tmp/$TAG.log 2>&1 echo exit=\$? >> /tmp/$TAG.log