From 9107119326c017941e112c6135176927ae4e2d01 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 16 Nov 2026 20:26:26 +0800 Subject: [PATCH 01/12] docs(release): v0.6.5 notes --- docs/releases/0.6.5.md | 51 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 docs/releases/0.6.5.md diff --git a/docs/releases/0.6.5.md b/docs/releases/0.6.5.md new file mode 100644 index 000000000..0cb99d989 --- /dev/null +++ b/docs/releases/0.6.5.md @@ -0,0 +1,51 @@ +v0.6.5 是 v0.6.4 之后的 patch 版本:修复 Linux 上窗口出现前投递的工作丢失、Windows 更新下载与替换、文本输入组合与剪贴板等问题,并新增 `Application.Post`、应用自有的 macOS 菜单栏、原子文件保存、上下文菜单定位、系统代理读取、防止休眠与 RPM 包等能力。macOS 是参考平台。升级需要注意一处行为变化,见"注意 · Caveats"。 + +v0.6.5 is a patch release after v0.6.4: it fixes work posted before the first Linux window being lost, Windows update download and replacement, and text composition and clipboard issues, and adds `Application.Post`, an application's own macOS menu bar, atomic file saves, context menus at captured points, system proxy reading, sleep prevention and RPM packages. macOS is the reference platform. One behaviour change needs a look before upgrading; see "注意 · Caveats". + +## 拿到它 · Getting it + +`go get github.com/vivaui/viva@v0.6.5`,需要 Go 1.26 或更新;系统依赖与 v0.6.4 相同。每个 Release 附带 `viva` 命令的预编译压缩包、`SHA256SUMS`,以及 Homebrew 与 Scoop 清单(`brew install vivaui/tap/viva`,或 `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` 后 `scoop install viva`);压缩包没有代码签名或公证,浏览器下载的 macOS 版会被 Gatekeeper 拦下,brew、curl 与 `go install` 不受影响。 + +`go get github.com/vivaui/viva@v0.6.5` needs Go 1.26 or newer; the system requirements are those of v0.6.4. Every Release carries prebuilt archives of the `viva` command, `SHA256SUMS`, and Homebrew and Scoop manifests (`brew install vivaui/tap/viva`, or `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` then `scoop install viva`); the archives are not code-signed or notarized, so a browser download on macOS is stopped by Gatekeeper while brew, curl and `go install` are not affected. + +## 有什么 · What is in it + +- `Application.Post` 把工作从任意 goroutine 交给拥有窗口的事件循环线程,按投递顺序执行,不额外启动 goroutine 或定时器。 +- `Application.SetMenuBar` 为应用安装自己的 macOS File、Edit、View 菜单,快捷键、勾选、子菜单与动作都在循环线程上派发。 +- `document` 包的 `Read` 与 `Save` 原子地读写文件并返回 SHA-256 版本,`Changed` 报告文件是否已被其他程序改动。 +- `ContextMenuAt` 在画布单元格、表头和编辑器这类没有命中目标的位置打开上下文菜单,并在窗口边缘夹住,不翻到指针另一侧。 +- `PreventSleep` 在应用需要时阻止系统空闲休眠:macOS 用 IOKit 断言,Windows 用电源请求,Linux 用 logind 抑制器。 +- `SystemProxy` 报告桌面为某个 HTTP 地址选择的代理;需要时导入 `app/proxy`,不使用的应用不会链接它的网络栈。 +- `gfx.FitLineMiddle` 截断长文本时保留两端,适合路径这类末尾相同、差异在中间的文本。 +- `TreeItem.Dragging` 与 `TreeState.DragSource` 标出被拖动的行和指针位置,拖放到行上与行间各有可见的位置标记。 +- `Styles` 让页面一处替换按钮、复选框、开关和文本输入的外观;菜单可以声明 `Unpainted`,由页面自己绘制面板与行,键盘与焦点行为不变。 +- 双击选中单词、三击选中整行,拖动时按单位扩展选区;`text.LineRange` 给出这一行的范围。 +- `viva package --format rpm` 生成 Fedora、RHEL 与 openSUSE 的 `.rpm`;`--cgo` 为原生包启用 cgo 构建。 +- 文本输入的组合阶段可以按需开启,macOS、Windows、Linux 的 IBus 与 GTK 都会发出阶段事件,应用可以拿到组合所有权。 +- Windows 上可以分别选择界面字体与等宽字体的字重。 +- Windows 剪贴板保留列选择的元数据,粘贴到表格类目标时能还原列。 +- 应用可以让系统在传输等工作期间保持唤醒,由应用决定哪些工作需要它。 + +- `Application.Post` runs work from any goroutine on the thread that owns the windows, in the order it was accepted, without starting a goroutine or timer. +- `Application.SetMenuBar` installs the application's own File, Edit and View menus on macOS; shortcuts, check marks, submenus and actions dispatch on the loop thread. +- `Read` and `Save` in the `document` package write files atomically and return a SHA-256 revision; `Changed` reports whether another program has changed the file. +- `ContextMenuAt` opens a context menu at a point the application captured, such as a canvas cell, a column header or an editor, and clamps it at the window edge instead of flipping it to the other side of the pointer. +- `PreventSleep` keeps the machine awake while the application needs it: an IOKit assertion on macOS, a power request on Windows and a logind inhibitor on Linux. +- `SystemProxy` reports the proxy the desktop selects for an HTTP URL; import `app/proxy` for it, so an application that does not ask for a proxy does not link the network stack. +- `gfx.FitLineMiddle` shortens a long line by keeping both ends, for paths whose difference is in the middle. +- `TreeItem.Dragging` and `TreeState.DragSource` mark the carried row and the pointer, and drops into a row or between rows each have a visible mark. +- `Styles` lets a page replace the button, checkbox, switch and text-entry looks in one place; a menu can be declared `Unpainted`, so the page paints its panel and rows while keyboard and focus behaviour stay the same. +- Double-click selects a word and triple-click a line, and a drag extends the selection by that unit; `text.LineRange` returns the line range. +- `viva package --format rpm` writes `.rpm` packages for Fedora, RHEL and openSUSE; `--cgo` enables cgo for native packages. +- Text composition phases can be turned on per input, and IBus, GTK, Windows and macOS emit them, so an application can take composition ownership. +- On Windows the interface and fixed-pitch font weights can be chosen separately. +- The Windows clipboard keeps column selection metadata, so a table paste target can restore the columns. +- An application can keep the machine awake while work such as a file transfer needs it; the application decides which work that is. + +## 注意 · Caveats + +- `KeyEvent.Text` 不再把 Shift 应用到字符上:Control+Shift+C 的 `Text` 现在是 `"c"`,按下的修饰键放在 `Modifiers` 中。依赖大写 `Text` 的代码需要改为读取 `Modifiers`。 +- 超出条目范围的列表键现在会 panic,这是对调用方错误的显式检查。 + +- `KeyEvent.Text` no longer applies Shift to the character: Control+Shift+C now carries `"c"`, and the held modifiers are in `Modifiers`. Code that reads an uppercase `Text` should read `Modifiers` instead. +- A list key outside the item range now panics, as an explicit check on a caller's error. From 3b4114f18168f8f214fdb6d46f5a5eb8de9267ce Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 16 Nov 2026 20:41:58 +0800 Subject: [PATCH 02/12] docs: point at v0.6.5 --- README.md | 2 +- README.zh-CN.md | 2 +- website/content/guides/en/getting-started.md | 2 +- website/content/guides/zh/getting-started.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f45ef0f73..79ab7dbe3 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Viva reaches Cocoa and Metal through cgo; on Linux, X11 with the system XCB and Vulkan loaders; on Windows, Win32 with Direct3D 11 and DirectWrite. Viva loads the system libraries at runtime and bundles none of them. -The current release is `v0.6.4`; name it explicitly (`@v0.6.4`) to pin it. Guides, +The current release is `v0.6.5`; name it explicitly (`@v0.6.5`) to pin it. Guides, the API reference, and a component catalog with live previews live in [`website/`](website/); run it with `npm run dev` there, or read them on [vivaui.dev](https://vivaui.dev/en/), which is also available in diff --git a/README.zh-CN.md b/README.zh-CN.md index 431ed7d25..33bf0a240 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -34,7 +34,7 @@ viva dev . # hot reload: save a file, the window updates and keeps its st 环境要求:Go 1.26 或更新版本(缺失时 viva 会自己下载)。macOS 上需要 Xcode 命令行工具,因为 Viva 通过 cgo 访问 Cocoa 和 Metal;Linux 上需要带系统 XCB 和 Vulkan 加载库的 X11;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 -当前版本是 `v0.6.4`;要固定版本就写明(`@v0.6.4`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 +当前版本是 `v0.6.5`;要固定版本就写明(`@v0.6.5`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 下面的一切描述的都是这个仓库:它的测量、它自己的程序,以及如何开发框架本身,而不是如何用框架。 diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md index bbc5530ca..b563f972c 100644 --- a/website/content/guides/en/getting-started.md +++ b/website/content/guides/en/getting-started.md @@ -22,7 +22,7 @@ go mod init example.com/hello go get github.com/vivaui/viva ``` -`go get` without a version resolves to the latest tagged release, which is `v0.6.4`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.4`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading. +`go get` without a version resolves to the latest tagged release, which is `v0.6.5`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.5`. Viva is not yet at 1.0, so the API in `go.mod` can still change between minor releases; read the release notes before upgrading. If you are working on Viva itself rather than using it, `replace` it with your checkout instead: diff --git a/website/content/guides/zh/getting-started.md b/website/content/guides/zh/getting-started.md index cdefa9343..9f8267b1b 100644 --- a/website/content/guides/zh/getting-started.md +++ b/website/content/guides/zh/getting-started.md @@ -22,7 +22,7 @@ go mod init example.com/hello go get github.com/vivaui/viva ``` -`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.4`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.4`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 +`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.5`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.5`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 如果你是在 Viva 仓库里改框架本身、而不是使用它,改用 `replace` 指向检出目录: From f93eda352a28f979790c41f543eb425828977a74 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 16 Nov 2026 23:45:40 +0800 Subject: [PATCH 03/12] feat(gfx): let a disabled control take secondary presses A disabled control is skipped by hit testing, so a right click on one never reached the application. A toolbar button the user can hide or move still needs its context menu, and the application had to hit-test its own geometry to find it. Add HitOptions.SecondaryWhenDisabled: a disabled control that declares it becomes the target of a secondary press only. Primary presses, keys and activation still pass over it. The router resolves the hover for a secondary press with the new flag, so the press target and the application's PointerDown delivery both see the control. Plain PointerAt callers pass false and keep the old hit rules. Used by motty#940 for the SFTP toolbar and the dock tools. --- app/painter.go | 4 +++- gfx/canvas.go | 18 +++++++++++---- internal/input/input.go | 17 ++++++++++++-- internal/input/input_test.go | 19 ++++++++++++---- internal/interaction/focus.go | 29 ++++++++++++------------ internal/interaction/interaction_test.go | 21 +++++++++++++++++ internal/platform/web/painter.go | 3 ++- 7 files changed, 84 insertions(+), 27 deletions(-) diff --git a/app/painter.go b/app/painter.go index 1ee870c63..687bca8be 100644 --- a/app/painter.go +++ b/app/painter.go @@ -367,7 +367,8 @@ func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.Eve painter.pointer.SetHoveredRole(gfx.Role(0)) painter.onSurface = false if event.Kind != platform.PointerExit { - if target, ok, onSurface := painter.focus.Router().PointerAt(event.X, event.Y); ok || onSurface { + secondaryPress := event.Kind == platform.PointerDown && event.Button == gfx.PointerButtonSecondary + if target, ok, onSurface := painter.focus.Router().PointerAt(event.X, event.Y, secondaryPress); ok || onSurface { painter.pointer.SetHovered(target.Target) painter.pointer.SetHoveredRole(target.Role) painter.onSurface = onSurface @@ -1964,6 +1965,7 @@ func sameRegionHit(published, current *gfx.Hit) bool { published.Focusable == current.Focusable && published.Disabled == current.Disabled && published.FocusableDisabled == current.FocusableDisabled && + published.SecondaryWhenDisabled == current.SecondaryWhenDisabled && published.SkipTab == current.SkipTab && published.Block == current.Block && published.BlockSurface == current.BlockSurface && diff --git a/gfx/canvas.go b/gfx/canvas.go index 302de9ebd..88c241698 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -452,6 +452,11 @@ type HitOptions struct { // focusable, as Base UI's accordion, collapsible and tab triggers do; it // never activates. Pointer presses still skip it. FocusableWhenDisabled bool + // SecondaryWhenDisabled, with Disabled, keeps the control the target of a + // secondary press, so a context menu can still open on it. It stays inert to + // primary presses, keys and activation. Use it where the disabled control + // still has its own menu, such as a toolbar button the user can hide or move. + SecondaryWhenDisabled bool Checked bool // Mixed marks a checkbox in the indeterminate state (aria-checked="mixed"). Mixed bool @@ -596,10 +601,12 @@ type Hit struct { Disabled bool // FocusableDisabled is HitOptions.FocusableWhenDisabled. FocusableDisabled bool - Checked bool - Mixed bool - Selected bool - Expanded bool + // SecondaryWhenDisabled is HitOptions.SecondaryWhenDisabled. + SecondaryWhenDisabled bool + Checked bool + Mixed bool + Selected bool + Expanded bool // Expandable is HitOptions.Expandable. Expandable bool Multiline bool @@ -1647,7 +1654,8 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H Value: options.Value, Hint: options.Hint, Scope: canvas.currentFocusScope(), Layer: canvas.currentLayer(), Role: role, Cursor: options.Cursor, CursorImage: options.CursorImage, Disabled: options.Disabled, FocusableDisabled: options.Disabled && options.FocusableWhenDisabled, - Checked: options.Checked, Mixed: options.Mixed, + SecondaryWhenDisabled: options.Disabled && options.SecondaryWhenDisabled, + Checked: options.Checked, Mixed: options.Mixed, Selected: options.Selected, Expanded: options.Expanded, Expandable: options.Expandable || options.Expanded, Multiline: options.Multiline, ReadOnly: options.ReadOnly, Secure: options.Secure, Description: options.Description, Level: options.Level, PosInSet: options.PosInSet, SetSize: options.SetSize, diff --git a/internal/input/input.go b/internal/input/input.go index c17dbf236..79b55079a 100644 --- a/internal/input/input.go +++ b/internal/input/input.go @@ -27,6 +27,9 @@ type Region struct { // FocusableDisabled keeps a disabled region focusable (but inert), as a // disabled accordion or tab trigger is. FocusableDisabled bool + // SecondaryWhenDisabled lets a disabled region take a secondary press (see + // gfx.HitOptions.SecondaryWhenDisabled). No other press or key reaches it. + SecondaryWhenDisabled bool // Role is the semantic role the region declared. The router uses it to // decide which keys activate the focused control: a button takes Enter and // Space, a checkbox only Space, a slider neither. @@ -195,7 +198,10 @@ func (router *Router) HitTestRegion(x float32, y float32) (Region, bool) { // pointer is on, and whether it is on a surface that says so (see // Region.BlockSurface) rather than on a control. Both answers come from the same // search, so a move costs one scan of the regions, as HitTestRegion alone did. -func (router *Router) PointerAt(x float32, y float32) (Region, bool, bool) { +// A secondary press also finds a disabled region that declares +// SecondaryWhenDisabled; the press that starts a context menu is the only one +// that does. +func (router *Router) PointerAt(x float32, y float32, secondaryPress bool) (Region, bool, bool) { for index := len(router.regions) - 1; index >= 0; index-- { region := router.regions[index] if !contains(region.Bounds, x, y) { @@ -209,7 +215,7 @@ func (router *Router) PointerAt(x float32, y float32) (Region, bool, bool) { } continue } - if router.hitAvailable(region) { + if router.hitAvailable(region) || secondaryPress && router.secondaryAvailable(region) { return region, true, false } } @@ -508,6 +514,13 @@ func (router *Router) hitAvailable(region Region) bool { (router.activeScope.IsZero() || region.Scope == router.activeScope) } +// secondaryAvailable is hitAvailable for a secondary press: a disabled region +// that declares SecondaryWhenDisabled is also a target of one. +func (router *Router) secondaryAvailable(region Region) bool { + return region.Disabled && region.SecondaryWhenDisabled && !region.Target.IsZero() && + (router.activeScope.IsZero() || region.Scope == router.activeScope) +} + func (router *Router) focusAvailableRegion(region Region) bool { if !region.Focusable || region.Target.IsZero() { return false diff --git a/internal/input/input_test.go b/internal/input/input_test.go index b351da3c3..90d09114e 100644 --- a/internal/input/input_test.go +++ b/internal/input/input_test.go @@ -122,6 +122,17 @@ func TestPassesSecondaryOnlyOnTheFrontMostPassingBackdrop(t *testing.T) { } } +func TestSecondaryPressFindsADisabledRegionWithoutAllocating(t *testing.T) { + var router Router + router.SetRegions([]Region{ + {Target: gfx.Item(1), Bounds: Rect{Width: 100, Height: 100}}, + {Target: gfx.Item(2), Bounds: Rect{Width: 50, Height: 50}, Disabled: true, SecondaryWhenDisabled: true}, + }) + if allocs := testing.AllocsPerRun(100, func() { router.PointerAt(20, 20, true) }); allocs != 0 { + t.Fatalf("secondary PointerAt allocates %v times per call, want 0", allocs) + } +} + func BenchmarkPassesSecondary10K(b *testing.B) { regions := make([]Region, 10_000) for index := range regions { @@ -167,7 +178,7 @@ func BenchmarkPointerAt10KMiss(b *testing.B) { b.ReportAllocs() b.ResetTimer() for range b.N { - router.PointerAt(-1, -1) + router.PointerAt(-1, -1, false) } } @@ -315,18 +326,18 @@ func TestBlockSurfaceReportsThePointerButTakesNoPress(t *testing.T) { // Over the panel's padding the surface reports itself, and a press still // reaches nothing. - if _, ok, onSurface := router.PointerAt(70, 70); !onSurface || ok { + if _, ok, onSurface := router.PointerAt(70, 70, false); !onSurface || ok { t.Fatal("the panel's padding did not report its surface") } if target, ok := router.HitTest(70, 70); ok { t.Fatalf("panel padding = %d, %v; the press must reach nothing", target, ok) } // Over a control on the panel it is the control's place, not the surface's. - if _, _, onSurface := router.PointerAt(40, 40); onSurface { + if _, _, onSurface := router.PointerAt(40, 40, false); onSurface { t.Fatal("a control on the panel reported the surface instead of itself") } // Outside the panel there is no surface at all, only the dismiss backdrop. - if _, _, onSurface := router.PointerAt(5, 5); onSurface { + if _, _, onSurface := router.PointerAt(5, 5, false); onSurface { t.Fatal("the dismiss backdrop reported itself as a surface") } } diff --git a/internal/interaction/focus.go b/internal/interaction/focus.go index 5d057e6ea..1444360fb 100644 --- a/internal/interaction/focus.go +++ b/internal/interaction/focus.go @@ -109,20 +109,21 @@ func (f *Focus) Sync(canvas *gfx.Canvas) { continue // semantic regions are not interaction targets } f.regions = append(f.regions, input.Region{ - Target: input.Target(hit.ID), - Bounds: input.Rect{X: hit.Bounds.X, Y: hit.Bounds.Y, Width: hit.Bounds.Width, Height: hit.Bounds.Height}, - Scope: hit.Scope, - Focusable: hit.Focusable, - Role: hit.Role, - SkipTab: hit.SkipTab, - Disabled: hit.Disabled, - FocusableDisabled: hit.FocusableDisabled, - Blocks: hit.Block, - BlockSurface: hit.BlockSurface, - Label: hit.IsLabel, - Backdrop: hit.Backdrop, - MovesWindow: hit.MovesWindow, - PassSecondary: hit.PassSecondary, PassPrimary: hit.PassPrimary, + Target: input.Target(hit.ID), + Bounds: input.Rect{X: hit.Bounds.X, Y: hit.Bounds.Y, Width: hit.Bounds.Width, Height: hit.Bounds.Height}, + Scope: hit.Scope, + Focusable: hit.Focusable, + Role: hit.Role, + SkipTab: hit.SkipTab, + Disabled: hit.Disabled, + FocusableDisabled: hit.FocusableDisabled, + SecondaryWhenDisabled: hit.SecondaryWhenDisabled, + Blocks: hit.Block, + BlockSurface: hit.BlockSurface, + Label: hit.IsLabel, + Backdrop: hit.Backdrop, + MovesWindow: hit.MovesWindow, + PassSecondary: hit.PassSecondary, PassPrimary: hit.PassPrimary, Layer: hit.Layer, }) } diff --git a/internal/interaction/interaction_test.go b/internal/interaction/interaction_test.go index 2b1c7e7c9..20808bcd5 100644 --- a/internal/interaction/interaction_test.go +++ b/internal/interaction/interaction_test.go @@ -28,6 +28,27 @@ func TestFocusRegionsSkipContainersAndOrderByLayer(t *testing.T) { } } +func TestSecondaryPressReachesOnlyDisabledControlsThatDeclareIt(t *testing.T) { + var canvas gfx.Canvas + canvas.BeginFrame() + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{Width: 100, Height: 100}, "", gfx.HitOptions{}) + canvas.HitWithOptions(gfx.Item(2), gfx.Rect{X: 10, Y: 10, Width: 40, Height: 40}, "", gfx.HitOptions{Disabled: true, SecondaryWhenDisabled: true}) + canvas.HitWithOptions(gfx.Item(3), gfx.Rect{X: 60, Y: 10, Width: 40, Height: 40}, "", gfx.HitOptions{Disabled: true}) + canvas.EndFrame() + var focus Focus + focus.Sync(&canvas) + router := focus.Router() + if region, ok, _ := router.PointerAt(20, 20, true); !ok || region.Target != gfx.Item(2) { + t.Fatalf("secondary press on a declared disabled control = %v/%v, want item 2", region.Target, ok) + } + if region, ok, _ := router.PointerAt(20, 20, false); !ok || region.Target != gfx.Item(1) { + t.Fatalf("primary press over a declared disabled control = %v/%v, want item 1", region.Target, ok) + } + if region, ok, _ := router.PointerAt(70, 20, true); !ok || region.Target != gfx.Item(1) { + t.Fatalf("secondary press over a disabled control without the declaration = %v/%v, want item 1", region.Target, ok) + } +} + func TestFocusKeepsAFocusedTargetAcrossRepaints(t *testing.T) { var canvas gfx.Canvas canvas.BeginFrame() diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index 4d489520f..a61d10323 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -708,7 +708,8 @@ func (p *painter) pointerStep(event gfx.PointerEvent) (result gfx.EventResult, f p.pointer.SetHoveredRole(gfx.Role(0)) p.onSurface = false if event.Kind != gfx.PointerExit { - if target, ok, onSurface := p.focus.Router().PointerAt(event.X, event.Y); ok || onSurface { + secondaryPress := event.Kind == gfx.PointerDown && event.Button == gfx.PointerButtonSecondary + if target, ok, onSurface := p.focus.Router().PointerAt(event.X, event.Y, secondaryPress); ok || onSurface { p.pointer.SetHovered(target.Target) p.pointer.SetHoveredRole(target.Role) p.onSurface = onSurface From 93ab37d73f53e4a3c77ea84227a9f918b5b3acb7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 00:06:41 +0800 Subject: [PATCH 04/12] docs(agents): index the guide by task and guard it in tests The generated AGENTS.md is the only document tools/aieval sends, and the skill is what an external agent installs. Both were long undivided prose with copy-paste mistakes. - add a task index, an error-to-fix table and a headless check list to the generated guide, and split the duplicated sections - rewrite the skill as a task router with a verification loop - split the 9k-character declarative-layout paragraph (en and zh), add a tested table example, and install recipes.md with the skill - add go tests for symbols, links, quoted panics and eval-task coverage --- cmd/viva/agents_test.go | 216 +++++++++++ cmd/viva/initfiles/AGENTS.md.txt | 361 +++++++++++++----- docs/README.md | 18 +- docs/skills/building-with-viva/SKILL.md | 124 ++++-- docs/skills/building-with-viva/recipes.md | 10 +- examples/guides/table/main.go | 73 ++++ examples/guides/table/main_test.go | 61 +++ tools/aieval/aieval_test.go | 53 +++ ui/focus_bind.go | 5 +- website/astro.config.mjs | 5 + .../content/guides/en/build-and-package.md | 2 +- website/content/guides/en/coding-agents.md | 4 +- .../content/guides/en/declarative-layout.md | 129 ++++++- .../content/guides/zh/build-and-package.md | 2 +- website/content/guides/zh/coding-agents.md | 4 +- .../content/guides/zh/declarative-layout.md | 130 ++++++- website/site.test.mjs | 9 + website/src/lib/site.test.ts | 12 +- website/src/lib/skills.ts | 19 +- website/src/pages/skills/[name]/SKILL.md.ts | 10 - website/src/pages/skills/[name]/[file].md.ts | 11 + 21 files changed, 1086 insertions(+), 172 deletions(-) create mode 100644 cmd/viva/agents_test.go create mode 100644 examples/guides/table/main.go create mode 100644 examples/guides/table/main_test.go delete mode 100644 website/src/pages/skills/[name]/SKILL.md.ts create mode 100644 website/src/pages/skills/[name]/[file].md.ts diff --git a/cmd/viva/agents_test.go b/cmd/viva/agents_test.go new file mode 100644 index 000000000..b8f85331f --- /dev/null +++ b/cmd/viva/agents_test.go @@ -0,0 +1,216 @@ +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "testing" +) + +// The agent-facing documents are read by a coding assistant that cannot run the +// compiler first. These tests keep them tied to the code: a name they show must +// exist, a link must resolve, and a quoted panic must be one the framework +// really raises. They are deliberately one-directional: they do not require the +// documents to mention every symbol, only that what they do mention is real. + +var agentDocuments = []string{ + "initfiles/AGENTS.md.txt", + "../../docs/skills/building-with-viva/SKILL.md", + "../../docs/skills/building-with-viva/recipes.md", + "../../docs/README.md", +} + +var agentPackages = map[string]string{ + "ui": "../../ui", + "gfx": "../../gfx", + "app": "../../app", + "components": "../../components", + "headless": "../../headless", + "field": "../../field", + "text": "../../text", +} + +// Names the documents mention to say they do not exist. +var knownAbsent = map[string]bool{ + "gfx.Handled": true, +} + +var qualified = regexp.MustCompile(`\b(ui|gfx|app|components|headless|field|text)\.([A-Z][A-Za-z0-9_]*)\b`) + +func TestAgentDocsNameRealSymbols(t *testing.T) { + symbols := map[string]map[string]bool{} + for name, dir := range agentPackages { + set, err := exportedTopLevel(dir) + if err != nil { + t.Fatal(err) + } + symbols[name] = set + } + for _, document := range agentDocuments { + text := readDocument(t, document) + for _, match := range qualified.FindAllStringSubmatch(text, -1) { + reference := match[0] + if knownAbsent[reference] { + continue + } + if symbols[match[1]][match[2]] { + continue + } + t.Errorf("%s names %s, which %s does not export", document, reference, match[1]) + } + } +} + +func exportedTopLevel(dir string) (map[string]bool, error) { + entries, err := os.ReadDir(dir) + if err != nil { + return nil, err + } + fset := token.NewFileSet() + set := map[string]bool{} + for _, entry := range entries { + name := entry.Name() + if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + file, err := parser.ParseFile(fset, filepath.Join(dir, name), nil, 0) + if err != nil { + return nil, err + } + for _, declaration := range file.Decls { + switch d := declaration.(type) { + case *ast.FuncDecl: + if d.Recv == nil && d.Name.IsExported() { + set[d.Name.Name] = true + } + case *ast.GenDecl: + for _, spec := range d.Specs { + switch s := spec.(type) { + case *ast.TypeSpec: + if s.Name.IsExported() { + set[s.Name.Name] = true + } + case *ast.ValueSpec: + for _, ident := range s.Names { + if ident.IsExported() { + set[ident.Name] = true + } + } + } + } + } + } + } + return set, nil +} + +func TestAgentDocsLinksResolve(t *testing.T) { + link := regexp.MustCompile(`\]\(([^)]+)\)`) + for _, document := range agentDocuments { + text := readDocument(t, document) + dir := filepath.Dir(document) + for _, match := range link.FindAllStringSubmatch(text, -1) { + target := strings.TrimSpace(match[1]) + if target == "" || strings.HasPrefix(target, "#") || strings.Contains(target, "://") || strings.HasPrefix(target, "mailto:") { + continue + } + // A type-parameter or call in a code span also reads as "](", in + // ui.State[bool](c, "open"); a real link target has no spaces and + // names a path or a file. + if strings.ContainsAny(target, " \t\"") { + continue + } + if !strings.ContainsAny(target, "./") { + continue + } + if filepath.Base(document) == "AGENTS.md.txt" { + t.Errorf("%s links %q; it is installed alone, so use an absolute URL", document, target) + continue + } + path := strings.SplitN(target, "#", 2)[0] + if _, err := os.Stat(filepath.Join(dir, path)); err != nil { + t.Errorf("%s links %q, which does not exist", document, target) + } + } + } +} + +// The guide's repair table is the assistant's path out of a failed compile or a +// panic. A row that quotes a message the framework does not raise sends it the +// wrong way, so every quoted ui: message must appear in a panic literal. +func TestAgentGuideQuotesRealPanics(t *testing.T) { + guide := readDocument(t, "initfiles/AGENTS.md.txt") + start := strings.Index(guide, "## If it does not compile or panics") + if start < 0 { + t.Fatal("the guide has no error table") + } + section := guide[start:] + if end := strings.Index(section[1:], "\n## "); end >= 0 { + section = section[:1+end] + } + var sources strings.Builder + entries, err := os.ReadDir("../../ui") + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".go") { + continue + } + data, err := os.ReadFile(filepath.Join("../../ui", entry.Name())) + if err != nil { + t.Fatal(err) + } + sources.Write(data) + } + for _, match := range regexp.MustCompile("`(ui: [^`]+)`").FindAllStringSubmatch(section, -1) { + if !strings.Contains(sources.String(), match[1]) { + t.Errorf("the error table quotes %q, which no ui panic contains", match[1]) + } + } +} + +func TestAgentGuideIsScannable(t *testing.T) { + guide := readDocument(t, "initfiles/AGENTS.md.txt") + headings := map[string]int{} + inFence := false + for number, line := range strings.Split(guide, "\n") { + if strings.HasPrefix(strings.TrimSpace(line), "```") { + inFence = !inFence + continue + } + if inFence { + continue + } + if strings.HasPrefix(line, "## ") || strings.HasPrefix(line, "### ") { + headings[line]++ + } + if len(line) > 1500 && !strings.HasPrefix(line, "|") && !strings.Contains(line, "://") { + t.Errorf("line %d is %d characters; split it into a subsection or a bullet", number+1, len(line)) + } + } + var repeated []string + for heading, count := range headings { + if count > 1 { + repeated = append(repeated, heading) + } + } + sort.Strings(repeated) + if len(repeated) > 0 { + t.Errorf("headings repeat, so a cross-reference is ambiguous: %s", strings.Join(repeated, ", ")) + } +} + +func readDocument(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(data) +} diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index ecc45173e..4e3607599 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -11,6 +11,45 @@ viva build # a release program in build/ viva help # every command ``` +## Start here + +Read this file out of order: find your task in the table below, then read that section. +When a name is uncertain, ask the source instead of guessing: + +```sh +go doc github.com/vivaui/viva/ui # every exported element and call +go doc github.com/vivaui/viva/ui.Button # one of them, with its comment +``` + +A symbol that `go doc` does not show does not exist. The compiler is the second check; +`viva vet` is the third. + +The loop for every change: + +1. Write the page in main.go. Keep state in the model; handle a click where its control is declared. +2. `gofmt -w ./*.go && go vet ./... && viva vet` — fix every finding before running the app. +3. `go test ./... -count=1` — main_test.go drives the real page with no window; extend it. +4. Check the picture headlessly: build with `-tags vivahead`, run with `VIVA_HEADLESS=1` + and a throwaway `HOME`, then `layout` and `expect` (see "Check it without a window"). +5. Say what you did not verify. A unit test does not prove IME, focus loss, a window-manager + close or a real GPU. + +## What are you building? + +| You are building | Read | Main calls | +| --- | --- | --- | +| Settings, preferences, login, a wizard, steppers, a search box | Forms and fields | `ui.FormField`, `ui.TextField`, `ui.Switch`, `ui.Choice`, `ui.Button`, `viva form` | +| A list: todo, cart, inbox, notifications, a log, kanban, master-detail | Lists, trees and scrolling | `ui.List`, `ui.ListState`, `ui.Scroll`, `c.KeyInt`, `ui.Row` | +| A table with sortable columns | Tables | `ui.Table`, `ui.TableSpec`, `ui.TableRows`, `components.TableColumn` | +| Tabs or a navigation strip | Tabs and select | `ui.Tabs`, `ui.Choice`, a `switch` on the value | +| A tree, a file tree, a gallery, a calendar grid | Lists, trees and scrolling | `ui.Tree`, `ui.TreeState`, `ui.Grid`, `ui.Flow` | +| A dialog, menu, popup, drawer or dashboard | Menus, dialogs and popups | `ui.Modal`, `ui.ModalWith`, `ui.Dialog`, `ui.Menu`, `ui.PopoverWith`, `ui.Drawer` | +| Animation, a progress bar, a timer, a media player | Animation and time | `c.Canvas().Now()`, `c.Canvas().RequestFrame()`, `ui.Progress`, `ui.Spinner` | +| Light/dark, a color picker, custom colors | The theme | `gfx.LightTheme()`, `gfx.DarkTheme()`, `PageConfig.Theme`, `c.Theme()` | +| A split pane, a divider, drag and drop | Keys, drag and the mouse | `ui.Splitter`, `ui.DragState`, `.DragSource`, `.DropTarget` | +| A chat or a log that follows its end | Lists, trees and scrolling | `ui.Scroll(...).Follow(true)`, `MaxWidthPercent`, `Justify` | +| A second window, a tray window | Several windows | `app.RunApplication`, `a.OpenWindow`, `page.Config` | + ## How a window works The window's page is a function, `page(c ui.C)` in main.go, which `ui.Run` paints. @@ -57,6 +96,8 @@ func (m *model) page(c ui.C) { } ``` +### Names, keys and state + - `c.Key("text")` / `c.KeyInt(id)` name the next element (a row); `c.Part("word")` names a part of a component. Everything else is named by its place in its parent: no names to declare. - Bind fields of the model (`&h.Done`). A copy (`v := m.viewed[id]; ui.Checkbox(c, &v, ...)`) works too: @@ -64,6 +105,12 @@ func (m *model) page(c ui.C) { - `Changed()` reports the paint in which a bound control changed its value; `Clicked()` on a `Button`. `Popover` and `Modal` set their `*bool` to false when dismissed (Escape, a press outside, the close button) and give the focus back. +- `ui.ID(c)` names the next element of the page (a `Hit` box, a `Control`, a recipe); `c.Theme()` is the + theme; `c.Bounds()` and `c.Canvas()` are for measuring. +- In a test, find controls by their name (`Hit.Label`), as main_test.go does. + +### Lists, trees and scrolling + - Long lists: `ui.List(c, &m.list, len(items), func(row ui.ListRow) { row.Element.PadX(8).Children(...) })` declares only the rows on screen; style the row with `row.Element`, declare what is in it with `row.C`, name the list with `.Label("Files")`. A click chooses a row (`m.list.Selected()`, `Changed()`), the arrows, Home, End and Page Up/Down move, Enter or a double click is @@ -81,6 +128,27 @@ func (m *model) page(c ui.C) { them there, in the model. `m.list.RowWidth = 900` makes the rows at least that wide and the list scrolls sideways (the horizontal wheel, or the wheel with Shift); a column header above it follows with `ui.Row(c).Clip().Children(func() { ui.Row(c).Width(900).ScrollWith(&m.list).Children(titles) })`. +- A tree: keep a `ui.TreeState` with `Node` describing each visible row, `ui.Tree(c, &m.tree, n, label, nil)`, + then `m.tree.Toggled()` (open or close that branch, give the tree its new rows) and `m.tree.Chosen()`. + Typing the start of a name moves to that row. To drag rows, set `m.tree.CanDrop = func(from, to int, + where ui.TreeDrop) bool` (`TreeDropBefore`, `TreeDropInside`, `TreeDropAfter`) and read `m.tree.Dropped()`; + change the rows in `c.After`, since the paint that reports the drop is declaring them. + `m.tree.RowID(i)` (`DisclosureID(i)` for the chevron; `ListState` has `RowID`) is a row's identity, to focus it or find its hit. +- To read or move a page's scroll area: `area := ui.Scroll(c).Grow(1)` then `area.ScrollState()` has `Offset`, + `Content`, `Viewport`, `Max()`, `AtEnd()`, `Pinned()`, `Dragging()`, `ScrollTo(px)` and `ScrollToEnd()` (also for the + area a `ui.List` or `ui.Tree` returns); ask for it in each paint and do not keep the pointer. The page gives the + wheel to the area under the pointer (the innermost, or the next one out when that is at its end), so side-by-side + columns and nested lists each scroll alone. `.Follow(true)` keeps a log or chat at its end until the user scrolls + up (and again when they scroll back down; `.Follow(m.autoScroll)` makes it a switch); `Pinned()` says the next + layout puts it at its end before `Offset` has caught up. `.Sideways()` scrolls left and right too (`OffsetX`, + `ContentWidth`, `ViewportWidth`, `MaxX()` and `ScrollToX(px)`), and `.Scrollbars()` draws draggable bars over the + overflowing edges. The bars are the hover style: they appear while the pointer is over the area, and + `.ScrollbarSize(px)` sets their thickness (a right `Pad` leaves the gutter they sit in instead of covering the + content). `PageConfig.ScrollbarSize` sets the page's default thickness for every bar that does not set its own. + An area a paint does not declare forgets its offset (a closed dialog, another tab). + +### Menus, dialogs and popups + - `.Tooltip("Delete")` on a control is the tip shown while the pointer rests on it (and its description). - A menu of actions off a button: `ui.Menu(c, more, &m.menu, func(menu *ui.MenuItems) { if menu.Item("Rename").Clicked() { ... } })`; `menu.Separator()`, `menu.Label("Group")`, `.Destructive()`, `.Disabled(x)`. Choosing an item closes it. @@ -88,34 +156,36 @@ func (m *model) page(c ui.C) { (opens as the pointer rests on it, on a click, or on Right/Enter/Space; Left goes back), in a ContextMenu too. - A right-click menu: `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` (Shift+F10 opens it too); items take `.Icon(icon)`, `.Keys(ui.Primary, "c")` (shown, not bound), `.Checked(on)` and `.Chosen(on)`. -- A search field: `ui.TextField(c, &m.query, "Search", "").Icon(search).Action(cross, "Clear")`, and - `.ActionClicked()` for the button. - A side panel: `ui.Drawer(c, &m.open, "Title", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)`; an empty title gives the body the whole panel, `NonModal` keeps the keyboard on the page, `Swipe` adds a handle that a drag toward the edge closes it by (past half its size, or thrown). -- To read or move a page's scroll area: `area := ui.Scroll(c).Grow(1)` then `area.ScrollState()` has `Offset`, `Content`, - `Viewport`, `Max()`, `Pinned()`, `Dragging()`, `ScrollTo(px)` and `ScrollToEnd()` (also for the area a `ui.List` or `ui.Tree` returns); ask for it - in each paint and do not keep the pointer. `.Sideways()` scrolls left and right too (`OffsetX`, `ContentWidth`, `ViewportWidth`, - `MaxX()` and `ScrollToX(px)`), and `.Scrollbars()` draws draggable bars over the overflowing edges. The bars are - the hover style: they appear while the pointer is over the area, and `.ScrollbarSize(px)` sets their thickness - (a right `Pad` leaves the gutter they sit in instead of covering the content). `PageConfig.ScrollbarSize` sets the - page's default thickness for every bar that does not set its own. +- A modal dialog: declare it while it is open, `ui.Modal(c, &m.confirm, "Delete host?", body, footer)`; the title is + required because it names the dialog for screen readers, and `body`/`footer` may be nil. It is centered over a scrim, + keeps the keyboard while open and gives it back as it closes; a press on the scrim, the close button and Escape set + `m.confirm` to false. `ui.ModalWith(c, &m.confirm, "Delete host?", ui.ModalSpec{Description: "...", Width: 400}, body, footer)` + adds a description, a size, `NoClose` or `InitialFocus`. For a dialog whose identities the application names itself, use + `ui.Dialog(c, ui.DialogSpec{...})`: `Scope`, `DismissID`, `CloseID` and `InitialFocusID` are yours, `.Header(fn)`, + `.Body(fn)` and `.Footer(fn)` declare it, and `.Dismissed()` reports the closing click. Do not write an Escape handler + for any of these; they dismiss themselves. +- A popup of your own: `ui.Popover(c, anchor, &m.open, body)` or + `ui.PopoverWith(c, anchor, ui.PopoverSpec{Width: 220, Align: ui.Start}, &m.open, body)`; it opens off its anchor, + flips when there is no room, closes on Escape or an outside press, and gives the focus back. A floating region that + is none of these is `ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: r})` (or `ui.LayerDrag` for a + drag ghost): it takes no room, paints after the page and below Viva's menus and dialogs, and its children are page + elements. Its empty surface lets presses through unless a `Canvas.Block` covers it. Do not build a popup from a + `Slot` and a `Hit`; the page's overlays keep the pointer, focus and dismissal a popup needs. A component author who + declares the underlying popup places it with `Beside(rect, gap, align)` or `BesideBox(box, gap, align)` to the right + of an anchor (a submenu), `BesideLeft`/`BesideLeftBox` to its left, and `Within(rect)` to keep it inside a region + instead of the window; `ui.PopoverWith`'s `Side` is the application-level form of the same placement. + `Below`/`BelowBox` and `Above`/`AboveBox` place below and above. + +### Choices, toasts and shortcuts + - `ui.Choice` (a segmented single choice) and `ui.Tabs` are one tab stop each; the arrow keys, Home and End move to an option and choose it, so do not wire `components.SegmentedControlKeyDown` or `TabsKeyDown` yourself. -- A tree: keep a `ui.TreeState` with `Node` describing each visible row, `ui.Tree(c, &m.tree, n, label, nil)`, - then `m.tree.Toggled()` (open or close that branch, give the tree its new rows) and `m.tree.Chosen()`. - Typing the start of a name moves to that row. To drag rows, set `m.tree.CanDrop = func(from, to int, - where ui.TreeDrop) bool` (`TreeDropBefore`, `TreeDropInside`, `TreeDropAfter`) and read `m.tree.Dropped()`; - change the rows in `c.After`, since the paint that reports the drop is declaring them. - `m.tree.RowID(i)` (`DisclosureID(i)` for the chevron; `ListState` has `RowID`) is a row's identity, to focus it or find its hit. -- Any other box drags and drops with a `ui.DragState` in the model: declare a `Hit` box with - `.DragSource(&m.drag)` and another with `.DropTarget(&m.drag, accept, drop)`. The page routes the pointer; - `m.drag.Dragging()`, `Source()`, `Target()` and `At()` paint the gesture, `accept(source, target)` decides, - `drop(source, target)` runs on release, and Escape lets go. A press that does not move is still a click. - Save the callbacks in the model and do not declare the boxes in a `Memo`. Inside a - `ui.Control`'s `Draw`, a part (a card of a custom grid) is a source or target of the same state with - `d.DragSource(&m.drag, part, r)` and `d.DropTarget(&m.drag, part, r, accept, drop)`, declared beside - `d.Canvas.Hit(part, r)`; a target part needs no `Hit`. + `Choice`, `Tabs` and `Select` write the value in the declaration, so disable them with an `if`, not a chained + `.Disabled`: `if !m.locked { if ui.Tabs(c, &m.tab, tabs, nil).Changed() { ... } }`. `Tabs` and `Select` also honor a + chained `.Disabled` for input; `Choice` ignores it, so never rely on it there. - A long list to choose from by typing: `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` (Select's arguments plus a label); it filters as the user types. `.Clearable()` adds a clear button, `.Empty("No zone")` is what an empty list says, `.Creatable("")` offers what was typed as a new choice, read with `.Created()`. @@ -124,17 +194,38 @@ func (m *model) page(c ui.C) { `ui.Toasts(c, &m.toaster)` once, last in the page. `ShowAction(title, "", kind, "Undo")` adds a button, `m.toaster.Acted()` (after `Toasts`) reports its press; a `ui.ToastLoading` toast stays until `m.toaster.Done(id, title, "", ui.ToastSuccess)` replaces it; `Toaster.Position` picks the corner. -- `ui.TextField(...).AutoFocus()` focuses a field as it appears; `.Submitted()` is Enter pressed in it. - `ui.TextField(...).Secure()` is a password field. Focus that lives in the model is - `ui.FocusBind(ui.TextField(...), &m.focus, FocusSearch)`: setting `m.focus` moves the focus, a user's - focus writes back, and `ui.FocusedValue(c, &m.focus)` reads the committed one. The element needs a - control or a Hit, and the binding is not for a Memo. - Keyboard shortcuts are declared where they act: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }` (Primary is Command on macOS, Control elsewhere); `list.Shortcut(0, "delete")` on a container or control acts only while the focus is in it, the innermost one winning. A chord without Primary, Ctrl or Alt is left to a field being typed in. - `ui.TextArea(c, &m.notes, "Notes", "").Height(120)` is several rows. + +### Forms and fields + +- Text fields that just work: `ui.TextField(c, &m.name, "Name", "placeholder")` binds a string of the model, and + `ui.TextField(c, &m.query, "Search", "")` binds a `ui.Field` when the program reads the caret or selection too + (`m.query.Secure = true` for that field). Typing, caret, selection, clipboard and input methods work; the page's + `Config` gives the platform the editor, so no `Config.TextInput` is needed for them. Read a string as `m.name`; + read a field with `m.query.Text()` and set it with `SetText("x")`. Do not build `text.Editor`s or snapshots by hand. + In a `Row` a field has no width of its own: give it `Grow(1)` or `Width`, or it is invisible. + Enter in a field: `if ui.TextField(c, &m.draft, "Message", "Type").Submitted() { m.send(); m.draft = "" }` (true only in the + repaint that delivers Enter, not for a click; `OnKey` is not needed). The label (first string) is never empty. +- Several rows: `ui.TextArea(c, &m.notes, "Notes", "").Height(120)` (Enter is a new line). Arrow keys and Page Up/Down + move by row while the platform edits it, and the page routes them; no `OnKey` is needed. +- Other fields: `ui.TextField(...).Icon(plus)` puts an icon before the text, `.Action(cross, "Clear")` a button at its end + (`.ActionClicked()` reads it), `.AutoFocus()` takes the focus as it appears and `.Secure()` makes it a password field. + A search box is a TextField with `.Icon(search)` and `.Action(cross, "Clear")`, as above. +- A form row declared by hand is `ui.FormField(c, &m.proxyField, "Proxy").FillWidth().Children(func() { ... })`: the title + and exactly one control child sit in the slot `components.BeginField` uses, at the same rhythm. Keep the + `ui.FormFieldState` in the model beside the value; it neither binds the value nor labels the control. +- A settings form from tags: tag the struct's fields (`form:"Label"`, `choices:"options,nameFunc"`, `placeholder:"..."`) + and run `go tool viva form` (or `//go:generate go tool viva form`); it writes `Form(c ui.C) ui.Box`. +- Focus that lives in the model: `ui.FocusBind(ui.TextField(...), &m.focus, focusSearch)`, where `focusSearch` is a value + of the model's own (`const focusSearch = "search"`): setting `m.focus` moves the focus, a user's focus writes back, and + `ui.FocusedValue(c, &m.focus)` reads the committed one. The element needs a control or a Hit, and the binding is not for a `Memo`. + +### Custom controls, looks and components + - A control of your own (terminal, editor, drawing canvas): `ui.Control(c, "Label", &m.handlers).Grow(1).Draw(m.draw)`; - `ui.Handlers` has Key, Pointer, Scroll and, with Role RoleTerminal or RoleTextField, Text for typing + `ui.Handlers` has Key, Pointer, Scroll and, with Role `gfx.RoleTerminal` or `gfx.RoleTextField`, Text for typing and input methods. Keep the Handlers and the draw function in the model; declare no identities. A control with several interactive parts (the stars of a rating, a graph's nodes) declares them as it draws: `d.Canvas.HitWithOptions(m.handlers.Parts().At(i), rect, "Star 3", opts)`; a key, press or wheel on a part reaches @@ -151,11 +242,29 @@ func (m *model) page(c ui.C) { reads), not a counter you must remember to bump. - Your own component is a function of the same shape: `func Card(c ui.C, title string, body func()) ui.Box`. Its own small state (whether it is open) is `ui.State[bool](c, "open")`; the application's state stays in the model. -- A settings form: tag the struct's fields (`form:"Label"`, `choices:"options,nameFunc"`, `placeholder:"..."`) - and run `go tool viva form` (or `//go:generate go tool viva form`); it writes `Form(c ui.C) ui.Box`. + A component that places its children by its own rule uses `ui.CustomLayout(c, &m.layout)` and implements `ui.Layout` + (`MeasureWidth`, `PlaceWidth`, `MeasureHeight`, `PlaceHeight`); the page keeps identity, focus, hits and clipping. - An independent window is a page: `ui.Run` or `ui.NewPage(...).Config(base)` wires its input. A pane of a window is a keyed container in the same page, not a second `Page`; do not draw a page into a slot in application code. -- `ui.ID(c)` names a custom control of your own (see Identities and clicks); `c.Theme()` is the theme; `c.Bounds()` and `c.Canvas()` are for measuring. -- In a test, find controls by their name (`Hit.Label`), as main_test.go does. +- A page of the system's web engine (WebKitGTK on Linux, WKWebView on macOS, WebView2 on Windows): put an + `app.WebHost` in `Config.Web`, open the page in its `OnReady` (`host.Open(app.WebViewConfig{URL: ...})`, or `HTML` + with a `Scheme` that serves your own resources), keep the `*app.WebView`, and in the page give it the room of a slot: + `ui.Slot(c).Grow(1).NativeView(m.view.ID())`. It fills the slot inside its clips and scrolls with it; menus, popovers + and dialogs are painted above it automatically. The page talks to the app with `window.viva.postMessage(text)` / + `viva.onmessage`, and the app with `OnMessage` and `view.PostMessage(text)`. Calls on the host and the page run on the + window thread. `Open` fails with `app.ErrUnsupported` when the platform or the installed engine cannot host pages: show + something else then. + +### Drag and drop + +- Any box drags and drops with a `ui.DragState` in the model: declare a `Hit` box with + `.DragSource(&m.drag)` and another with `.DropTarget(&m.drag, accept, drop)`. The page routes the pointer; + `m.drag.Dragging()`, `Source()`, `Target()` and `At()` paint the gesture, `accept(source, target)` decides, + `drop(source, target)` runs on release, and Escape lets go. A press that does not move is still a click. + Save the callbacks in the model and do not declare the boxes in a `Memo`. Inside a + `ui.Control`'s `Draw`, a part (a card of a custom grid) is a source or target of the same state with + `d.DragSource(&m.drag, part, r)` and `d.DropTarget(&m.drag, part, r, accept, drop)`, declared beside + `d.Canvas.Hit(part, r)`; a target part needs no `Hit`. +- For a divider between two panes, use `ui.Splitter` (see "Keys, drag and the mouse"), not a `DragState`. ## Mistakes that compile (and how each is reported) @@ -174,6 +283,30 @@ running anything; a test under `app.NewDriver` panics on them where they happen, A line, or the line above it, with `// viva:ignore unkeyed-button` (or `kept-context`, `memo-value`) silences one finding you have checked. +## If it does not compile or panics + +Read the first line of the error, find it here, and change the declaration. The message is the +framework telling you which rule you crossed; do not work around it by moving the call. + +| The error or panic | What to write instead | +| --- | --- | +| `ui: a Box is used after its paint` | Keep a `gfx.ID` or the page's name across paints, not the `Box`; re-declare to get a new one. | +| `ui: Modal needs a title` | Pass a non-empty title; it is the dialog's name for assistive technology. | +| `ui: FormField needs its FormFieldState` | Keep one `ui.FormFieldState` per field in the model and pass `&m.proxyField`, not the value. | +| `ui: FormField takes one control child` | Wrap the controls in a `Row` or `Column`; the field has one slot. | +| `ui: a Row, Column or Stack given Hit` | A container with `Hit` needs `Children`, a size, a background or a border, or it is empty. | +| `ui: two siblings have the key` | Key each row by its item (`c.KeyInt(item.ID)`), not by a constant. | +| `ui: an element was declared after the page was laid out` | Declare elements in the page function, not in a `Draw` callback or after `End`. | +| `ui: Effect in a Memo` | Declare the `ui.Effect` outside the `Memo`; a copied part is not declared. | +| `ui: FocusBind needs an element with an identity` | Give the element a `Control`, a `Hit` or a key before `FocusBind`. | +| `ui: AutoFocus needs an element with an identity` | The same: a control, or a container after `Hit`. | +| `ui: Tooltip needs an element with an identity` | The same: a control, or a container after `Hit`. | +| `cannot use n (variable of type int) as float32` | Every length is a `float32`: `Width(float32(n))`, `Pad(float32(n))`, `Gap(float32(n))`. | +| `undefined: FocusSearch` / `RoleTerminal` | Define your own focus value (`const focusSearch = "search"`); roles are `gfx.RoleTerminal`, `gfx.RoleTextField`. | +| `cannot use c (variable of type ui.C) as gfx.Color` | `Ring` takes a color: `Ring(3, theme.Ring)`, not `Ring(3, c)`. | +| a text field in a `Row` is invisible | A field has no preferred width: give it `Grow(1)` or `Width(...)`. | +| `undefined: ui.Box` as a constructor | There is no `Box` constructor; a control call returns one: `b := ui.Button(c, "Filter")`. | + ## Laying a page out (package github.com/vivaui/viva/ui) Describe the page; do not compute coordinates. @@ -197,6 +330,8 @@ func (m *model) page(c ui.C) { } ``` +### Page, containers and space + - The window's `*ui.Page` is made by `ui.Run` or `ui.NewPage` and lives with the window; the page function only declares with `c`. A `ui.C` and the `Box`es of one paint are valid only while that paint runs. @@ -220,9 +355,12 @@ func (m *model) page(c ui.C) { `ui.Start`/`ui.End`/`ui.Stretch` changes that; `ui.Baseline` lines a Row's children up on their first line of text; `Self(...)` for one child; `Justify(ui.Center|End|Between)` places what is left along it; `Center()` does both. + +### Look, effects and states + - Look: `Background`, `Radius`, `Border(width, color)`, `Shadow(gfx.ShadowMD)` (a drop shadow under the fill; `ShadowXS` to `ShadowLG`), `Clip`. A circle (an avatar, a dot) is a square box with `Radius(size/2)` and `Center()`: `ui.Row(c).Size(32, 32).Radius(16).Background(theme.Primary).Center().Children(func() { ui.Text(c, "AB") })`. -- Effects, all typed and checked by the compiler (there is no class string): `Ring(3, c)` draws a line around the +- Effects, all typed and checked by the compiler (there is no class string): `Ring(3, theme.Ring)` draws a line around the outside without taking room (a focus ring); `Opacity(0.5)` fades the element and everything in it (it is still laid out and clickable); `Gradient(ui.ToBottomRight, from, to)` and `GradientStops(angle, gfx.Stop(0, a), gfx.Stop(1, b), ...)` fill the element, corners included, over `Background` and under `Border`; `Dashed()` breaks the `Border` line into @@ -249,6 +387,9 @@ func (m *model) page(c ui.C) { when a glyph needs its own motion. `BindIconHover` only moves the glyph inside its box. - Window: in a `WindowCustomTitlebar` window nothing moves the window unless you say where: `ui.Row(c).Height(36).MovesWindow().Children(...)` on the top bar (controls inside it still take their own clicks; a menu or dialog open over it is dismissed by a click there and the window moves once the pointer drags). + +### Text and icons + - Text: `FontSize`, `Weight`, `Bold`, `Color`, `Muted`, `Mono`, `MonoFace`, `TextCenter`, `TextEnd`, `TextDirection`, `LineHeight`; `Ellipsis()` keeps a Text to one line and ends it with … when it does not fit; `MaxLines(n)` lets a Text break into at most n lines (the last ends with …), `ui.Wrap(c, text)` into as many as the width needs. Lines @@ -261,6 +402,9 @@ func (m *model) page(c ui.C) { the same on every platform, and draws the platform's glyphs at that width: a button as wide as its label, a tab, a table column sized to content and every line break are the same on macOS, Windows and Linux, so do not size by a platform's font (or special-case a platform) to make text fit. + +### Buttons and controls + - Buttons (the plain one is the primary; there is no `Primary()`): `Secondary`, `Outline`, `Ghost`, `Link`, `Destructive`, `DestructiveOutline`, `XSmall`, `Small`, `Large`, `IconOnly`, `Disabled(cond bool)` (so `ui.Button(c, "-").Disabled(m.n <= 0)`, no `if`). - A control call returns a `ui.Box` (there is no `ui.Box` constructor); keep it when you need it later: `filter := ui.Button(c, "Filter")`. @@ -269,21 +413,6 @@ func (m *model) page(c ui.C) { `Label` is the name a screen reader or a test finds the control by, so give one to every control that has no text of its own, and put the visible caption in a `ui.Text` beside it. A header row of named controls is a `Row` of `Button`s (`.Ghost()`) or `Hit` boxes; each is found by its label. -- Text fields that just work: `ui.TextField(c, &m.name, "Name", "placeholder")` binds a string of the model, and - `ui.TextField(c, &m.query, "Search", "")` binds a `ui.Field` when the program reads the caret or selection too - (`m.query.Secure = true` for that field). Typing, caret, selection, clipboard and input methods work; the page's - `Config` gives the platform the editor, so no `Config.TextInput` is needed for them. Read a string as `m.name`; - read a field with `m.query.Text()` and set it with `SetText("x")`. Do not build `text.Editor`s or snapshots by hand. - In a `Row` a field has no width of its own: give it `Grow(1)` or `Width`, or it is invisible. - Enter in a field: `if ui.TextField(c, &m.draft, "Message", "Type").Submitted() { m.send(); m.draft = "" }` (true only in the - repaint that delivers Enter, not for a click; `OnKey` is not needed). The label (first string) is never empty. -- Several rows: `ui.TextArea(c, &m.notes, "Notes", "").Height(120)` (Enter is a new line). Arrow keys and Page Up/Down - move by row while the platform edits it, and the page routes them; no `OnKey` is needed. -- Other fields: `ui.TextField(...).Icon(plus)` puts an icon before the text, `.Action(cross, "Clear")` a button at its end - (`.ActionClicked()` reads it), `.AutoFocus()` takes the focus as it appears and `.Secure()` makes it a password field. - A search box is a TextField with `.Icon(search)` and `.Action(cross, "Clear")`. `ui.Choice(c, &m.theme, themes, nil)` is a - segmented choice and `ui.Tabs(c, &m.tab, tabs, nil)` a tab strip; each writes the chosen value itself. For a control - that only `components` paints, declare a `ui.Slot(c)` and paint it in the slot's `Draw` callback (see Components). - Controls with your own look: every control with the theme's look has a Base, the same control without one, and the look is then the element's own. `ui.ButtonBase(c, "name")` (give it `Children`), `ui.TextFieldBase(c, &m.cell, "Cell", "")` for a single-line field without a look, and `ui.TextArea` for the multi-row field, `ui.CheckboxBase(c, &m.on, "name")`, `ui.SwitchBase` and `ui.ToggleBase(c, &m.bold, "Bold")` the @@ -313,7 +442,11 @@ func (m *model) page(c ui.C) { `ChosenIndex()` reports the option index a click chose on a `ui.Choice` strip (the call the bound form uses itself), for a caller that needs the index. `ui.Tabs(c, &m.tab, tabs, nil)` is a tab strip with the same write; declare the active tab's content after it, for the value it wrote, and `TabClicked()` reports the tab index a click chose when you need the - index rather than the value. A vertical divider is just `ui.Divider(c)` inside a `Row` (there is no `.Vertical()` on a Divider). + index rather than the value. `ui.Divider(c)` has no vertical mode: put it in a `Row` to divide horizontally + (`Box.Vertical()` is for tabs, not a Divider). + +### Tables + - A table: the data is a `ui.TableRows` in the model (`[][]string`, passed as `&m.data`) or your own pointer type with `Len() int` and `Cell(row, col int) string`; not a plain slice of structs. `ui.Table` makes its row and header scopes from the state when the spec leaves them zero: @@ -338,32 +471,21 @@ func (m *model) page(c ui.C) { and an explicitly identified draggable `Scrollbar` are unchanged. The page gives the wheel to a self-scrolling table under the pointer; give the `app.Config` passed to `page.Config` `OnKey: m.table.Key` for Up/Down/Page/Home/End selection (a host that routes its own scroll gives `m.table.Wheel` the wheel). + +### Tabs and select + - Tabs: `if ui.Tabs(c, &m.tab, tabs, nil).Line().Changed() { ... }`, then declare the active tab's content under it with an - ordinary `switch m.tab`. `Line()` is the underlined variant (it draws 5 px under the strip), `Vertical()` stacks the tabs, - `Disabled(true)` makes them inert. + ordinary `switch m.tab`. `Line()` is the underlined variant (it draws 5 px under the strip), `Vertical()` stacks the tabs. + `Choice`, `Tabs` and `Select` write the value in the declaration, so disable them with an `if`, not a chained + `.Disabled`: `if !m.locked { if ui.Tabs(c, &m.tab, tabs, nil).Changed() { ... } }`. `Tabs` and `Select` also honor a + chained `.Disabled` for input; `Choice` ignores it, so never rely on it there. - A drop-down select: keep the value in the model; whether the list is open is the Select's own state: `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. `ui.Combobox` takes the same arguments plus a label and filters as the user types. -- A modal dialog: declare it while it is open, `ui.Modal(c, &m.confirm, "Delete host?", body, footer)`; the title is - required because it names the dialog for screen readers, and `body`/`footer` may be nil. It is centered over a scrim, - keeps the keyboard while open and gives it back as it closes; a press on the scrim, the close button and Escape set - `m.confirm` to false. `ui.ModalWith(c, &m.confirm, "Delete host?", ui.ModalSpec{Description: "...", Width: 400}, body, footer)` - adds a description, a size, `NoClose` or `InitialFocus`. For a dialog whose identities the application names itself, use - `ui.Dialog(c, ui.DialogSpec{...})`: `.Header(fn)`, `.Body(fn)` and `.Footer(fn)` declare it and `.Dismissed()` reports - the closing click. -- Menus, tooltips and select lists: a menu of actions is `ui.Menu(c, anchor, &m.menuOpen, func(menu *ui.MenuItems) { ... })` - off a button's `Box`; its items, submenus, keys and dismissal are the menu's. `.Tooltip("text")` on the - control it describes is the tip shown while the pointer rests on it. `ui.Select`, `ui.Combobox` and `ui.Drawer` place their own lists and panels. Your own panel is - `ui.Popover(c, anchor, &m.open, body)` or `ui.PopoverWith(c, anchor, ui.PopoverSpec{Width: 220, Align: ui.Start}, &m.open, body)`; - it opens off its anchor, flips when there is no room, closes on Escape or an outside press, and gives the focus back. - A floating region that is none of these is `ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: r})` (or - `ui.LayerDrag` for a drag ghost): it takes no room, paints after the page and below Viva's menus and dialogs, and its - children are page elements. Do not build a popup from a `Slot` and a `Hit`; the page's overlays keep the pointer, focus - and dismissal a popup needs. A component author who declares the underlying popup places it with `Beside(rect, gap, align)` - or `BesideBox(box, gap, align)` to the right of an anchor (a submenu), `BesideLeft`/`BesideLeftBox` to its left, and - `Within(rect)` to keep it inside a region instead of the window; `ui.PopoverWith`'s `Side` is the application-level form of - the same placement. `Below`/`BelowBox` and `Above`/`AboveBox` place below and above. + +### Slots, grids and absolute placement + - A page of the system's web engine inside the window (WebKitGTK on Linux, WKWebView on macOS, WebView2 on Windows): put an `app.WebHost` in `Config.Web`, open the page in its `OnReady` (`host.Open(app.WebViewConfig{URL: ...})`, or `HTML` with a `Scheme` that serves your own resources), keep the `*app.WebView`, and in the page give it the room of a slot: @@ -385,22 +507,18 @@ func (m *model) page(c ui.C) { the element's `Rect` in its place, or use the rectangle in the same event pass after the page function returns; do not keep the `Box` for a later paint. `c.Canvas()` is the canvas for measuring or reading pointer and focus state, and `c.Bounds()` is the rectangle the whole page was laid out in, known before the page returns. + +### Sliders and scrolling + - A slider (volume, zoom, a threshold): a `ui.SliderState` in the model holds the number in `Value` (set it before the first paint), and `if ui.Slider(c, &m.volume).Range(0, 1).Step(0.05).Label("Volume").Changed() { m.player.SetVolume(m.volume.Value) }` draws it (`Range` defaults to 0..100, `Step` is optional, `Vertical()` makes it tall, `Disabled(cond)` dims it, 16 high and as wide as its column or 160 in a row unless given a `Width`). A drag, a click on the track and the arrow keys all keep `Value` inside the range; the page routes the focused slider's keys, so no `Config.OnKey` is needed. `Changed()` is true in the one paint that delivers a user's change, so call it last in the chain. Do not draw a track from a `Slot` and `Progress` by hand. -- Scrolling needs nothing in the model: `area := ui.Scroll(c).Grow(1)`, then `area.ScrollState()` has `Offset`, `Content`, - `Viewport`, `Max()`, `AtEnd()`, `Pinned()`, `ScrollTo(px)` and `ScrollToEnd()` (also for the area a `ui.List` or `ui.Tree` returns); - ask for it in each paint and do not keep the pointer. The page gives the wheel to the area under the pointer (the innermost, or the - next one out when that is at its end), so side-by-side columns and nested lists each scroll alone. A log or chat that grows at the - bottom: `.Follow(true)` keeps the area at its end until the user scrolls up (and again when they scroll back down; `.Follow(m.autoScroll)` - makes it a switch); `Pinned()` says the next layout puts it at its end before `Offset` has caught up, and `ScrollToEnd()` after adding - the item holds in the paint that grows the content. `.Sideways()` adds horizontal scrolling (`OffsetX`, `ContentWidth`, - `ViewportWidth`, `MaxX()`, `ScrollToX(px)`), and `.Scrollbars()` draws the draggable bars (hover-revealed; `.ScrollbarSize(px)` - sets their thickness). An area a paint does not declare forgets - its offset (a closed dialog, another tab). + +### Coordinates + - Do not write `gfx.Rect{X: ..., Y: ...}` arithmetic for ordinary parts of a page. It breaks when a label gets longer or the window gets narrower; a page laid out with ui does not. @@ -411,17 +529,6 @@ It composes the same `ui` elements as the application, keeps its own small state declares a `gfx.Tree`, opens a window or holds a `C` past the paint. A hit or a test names it with `ui.ID(c)` (the next element's identity) or `c.Part("word")` when the name must be stable. -- A control you paint yourself is `ui.Control(c, "Label", &m.handlers)`; `ui.Handlers` receives its keys, pointer, wheel - and, with `RoleTextField` or `RoleTerminal`, the platform's typing and input methods through `Text`. Give it a size or - `Grow(1)`, paint it with `.Draw(m.draw)`, and declare its interactive parts inside that Draw with `d.Canvas.Hit(part, r)`: - an event on a part reaches the same `Handlers` with the part as its target, and `event.Target.In(m.handlers.Parts())` - gives its index. -- A component that places its children by its own rule uses `ui.CustomLayout(c, &m.layout)` and implements `ui.Layout` - (`MeasureWidth`, `PlaceWidth`, `MeasureHeight`, `PlaceHeight`). The page keeps identity, focus, hits and clipping; the - layout owns its children's sizes and positions. Wrap it in `Scroll`, `List` or `Tree` to scroll it. -- Chrome that floats over the page without being a menu or dialog is - `ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: r})` (or `ui.LayerDrag`); its children are page elements, - and a `Canvas.Block` over its empty surface stops presses to the page behind it. - A component from `github.com/vivaui/viva/components` with no `ui` wrapper is painted in a slot: declare `ui.Slot(c)` and paint the component's `Paint...` function in the slot's `Draw` callback (`components.PaintInput(d.Canvas, *d.Theme, d.Rect, snapshot)`). For a control whose input the page must route, declare its `ui` element or its Base (`ui.ButtonBase`, `ui.TextFieldBase`, ...). @@ -454,16 +561,6 @@ ui.Row(c).Fill().Children(func() { (`Splitter` in a `Column` divides top and bottom; the first pane then gets `Height(m.split.Pos)`.) -A drag of your own is a `ui.DragState` in the model, declared with `.DragSource` and `.DropTarget` on `Hit` boxes, or with -`d.DragSource` and `d.DropTarget` inside a `Control`'s `Draw` (see Pages); the page follows the press and the release. - -## A modal dialog - -Use `ui.Modal(c, &m.open, title, body, footer)` or `ui.ModalWith` (see Laying a page out): it dims the page and keeps the -keyboard while `m.open` is true, and Escape, a press on the dim and the close button all set it to false, so there is no -Escape handler to write. For a dialog whose identities the application names, `ui.Dialog(c, ui.DialogSpec{...})` gives you -`Scope`, `DismissID`, `CloseID` and `InitialFocusID`, with `.Header`, `.Body`, `.Footer` and `.Dismissed()`. - ## Animation and time Nothing runs by itself. A paint that must be followed by another (a progress bar, a spinner) calls @@ -593,6 +690,64 @@ labels, hits and rectangles painted. main_test.go clicks a control by its name a the labels; copy it. Test behaviour a user sees (the count changed, the row opened), not pixel positions. +## Check it without a window + +A test is the first check; the picture is the second. Add a file guarded by the tag so +release builds never contain it: + +```go +//go:build vivahead + +package main + +import _ "github.com/vivaui/viva/headless/auto" +``` + +```sh +go build -tags vivahead -o /tmp/app . +VIVA_HEADLESS=1 HOME=$(mktemp -d) /tmp/app +``` + +The program then reads one command per line from stdin. The ones that find mistakes fastest: + +| Command | What it tells you | +| --- | --- | +| `layout` | text clipped, spilling out of its control, or over other text | +| `tree` | every control with role, name, value and state (`focused`, `disabled`, `covered`, ...) | +| `texts` | every painted string, to see what the frame actually says | +| `click "Save"` | click the control with that accessible name (also `id:...`, `role:name`) | +| `expect text "Saved" within 1000` | wait for a text; fails with what the frame has instead | +| `expect layout clean` | no clipped or overlapping text at the current size | +| `expect named` | every interactive control has an accessible name | +| `shot /tmp/a.png` | the frame as an image, when the look itself matters | + +When a step fails: a control is not found, run `tree`; text is cut off, run `layout`; the +focus is wrong, run `focus`; a press does nothing, look for `covered` in `tree`. Prefer a +script ending in `expect` lines to one you read by eye. The complete command list is the +comment above `Serve` in `headless/control.go`; do not copy it into your own docs. + +## Examples + +The complete programs under `examples/guides` are compiled and tested; read the nearest one +before composing from scratch: + +- `hello` — the smallest window and a click. +- `layout` — rows, columns, growth, padding and alignment. +- `textfield` — a bound field, typing, Enter and focus. +- `input` — pointer, keyboard, a list with a context menu and a splitter. +- `overlay` — a modal, a popover and a drawer. +- `theming` — light and dark themes and theme tokens. +- `table` — a fixed header, sortable columns, a selected row and a scrolling body. +- `windows` — a custom title bar and a second window. +- `drawing` — slots, a canvas and custom painting. +- `page` — a filter, a scrolling list of hosts and a progress bar, written as a page. +- `background` — a `ui.Effect` and a goroutine that reports through an `Invalidator`. +- `webview` — the system web engine in a slot. + +The finished components (settings row, list row, avatar, badge, stat card, hero, icon button, +empty state, dimmable section) are under +, with `recipes.md` beside the skill. + ## Rules - Allocation-conscious: no `fmt.Sprintf` per frame for text that has not changed if it is in a diff --git a/docs/README.md b/docs/README.md index 251683054..0e1a3cc63 100644 --- a/docs/README.md +++ b/docs/README.md @@ -10,9 +10,25 @@ can run its programs. | Look up an API | the API reference on that site, generated from the Go source and its comments | | Build the framework itself | [../CONTRIBUTING.md](../CONTRIBUTING.md) and [../README.md](../README.md) | | Check platform behaviour | [conformance.md](conformance.md) | -| Have a coding agent build on Viva | [skills/building-with-viva](skills/building-with-viva/SKILL.md), published on the website as the [coding agents guide](../website/content/guides/en/coding-agents.md) and at `/skills/building-with-viva/SKILL.md`: copy or symlink the directory into your project's `.claude/skills` or `.agents/skills` | +| Have a coding agent build on Viva | [skills/building-with-viva](skills/building-with-viva/SKILL.md): `SKILL.md` is the task router, the rejected rules and the verification loop; `recipes.md` says which finished example to start from. Both are published under `/skills/building-with-viva/`, and the [coding agents guide](../website/content/guides/en/coding-agents.md) installs them into `.claude/skills` or `.agents/skills` | | See what was measured | [benchmarks/](benchmarks/) | +## Agent-facing documents + +Three files teach an agent to write Viva, and each has one job: + +- [skills/building-with-viva/SKILL.md](skills/building-with-viva/SKILL.md) — the briefing an + external agent loads: the loop, the rules review rejects, where to find an API, how to verify. +- [skills/building-with-viva/recipes.md](skills/building-with-viva/recipes.md) — the visual + composition catalog, backed by the compiled `examples/recipes`. +- [../cmd/viva/initfiles/AGENTS.md.txt](../cmd/viva/initfiles/AGENTS.md.txt) — the guide + `viva init` writes into every project: the task index, the API reference, the error table and + the headless check list. `tools/aieval` measures a model against this file. + +Keep them consistent: `cmd/viva/agents_test.go` checks that every `ui.`/`gfx.`/`app.` symbol they +name exists and that their links resolve, and `ui/guide_test.go` checks that the generated guide +mentions every exported method and theme field. + ## What is here - [conformance.md](conformance.md) — the scenarios that need a real window on a diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index 0db5c5297..7848cda8e 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -1,11 +1,21 @@ --- name: building-with-viva -description: Write, change or debug a desktop application built on the Viva framework (github.com/vivaui/viva), or check its UI without opening a window. Use when the code imports github.com/vivaui/viva/app, ui, gfx or components, or when asked to add a window, control, layout, input handling or a headless test to a Viva app. +description: Write, change or debug a desktop application built on the Viva framework (github.com/vivaui/viva), or check its UI without opening a window. Use when the code imports github.com/vivaui/viva/app, ui, gfx, components or headless, or when asked to add a window, control, form, list, table, dialog, layout, input handling, animation or a headless test to a Viva app. --- # Building with Viva -Viva is a Go-first, GPU-native desktop framework. It draws its own UI: there is no WebView, HTML, CSS or JavaScript, and nothing is redrawn while the app is idle. Most mistakes come from writing it like a web or retained-mode toolkit. Read this before writing code, and read the guides it points to before guessing an API. +Viva is a Go-first, GPU-native desktop framework. It draws its own UI: there is no WebView, HTML, CSS or JavaScript, and nothing is redrawn while the app is idle. Most mistakes come from writing it like a web or retained-mode toolkit. Read this before writing code, then read the nearest example or `go doc` before guessing an API. + +## 0. The loop + +1. **Find the closest existing code.** `go doc github.com/vivaui/viva/ui` lists every element; `go doc github.com/vivaui/viva/ui.Button` shows one with its comment. The example nearest the task is under `examples/guides`: `hello` (smallest window), `layout`, `textfield`, `input` (list, context menu, splitter), `overlay` (modal, popover, drawer), `theming`, `windows` (custom title bar, second window), `drawing`, `page` (filter, list, progress), `background` (effects), `webview`. +2. **Write the page** in `main.go`. Keep state in the model; handle a click where its control is declared. +3. **Fix it before running it.** `gofmt -w . && go vet ./... && viva vet`. `viva vet` reports page mistakes that compile: an unkeyed `Button` in a loop, a `ui.C`/`ui.Box` kept past its paint, a `ui.Memo` whose value misses a field its function reads. +4. **Check behaviour and the picture.** `go test ./... -count=1`, then the headless build with `layout`, `tree` and `expect` (section 5). +5. **Say what you did not verify.** A unit test does not prove IME, focus loss, a window-manager close or a real GPU. + +A symbol that `go doc` does not show does not exist. Do not invent an API and wrap it in a workaround. ## 1. Decide whose code it is @@ -28,34 +38,100 @@ If you are in a checkout of Viva itself, its `AGENTS.md` is the authority and ov ## 3. How a screen is written -The painting function is the UI. It runs again on every redraw, declares what is on screen with value types, and keeps no layout cache. The smallest complete program is [`hello/main.go`](https://github.com/vivaui/viva/blob/main/examples/guides/hello/main.go); the others in [`examples/guides`](https://github.com/vivaui/viva/tree/main/examples/guides) show one concept each (layout, input, text field, overlays, windows, theming, drawing, background). +A page is `func (m *model) page(c ui.C)`, opened with `ui.Run(config, m.page)` or `ui.NewPage(ui.PageConfig{View: m.page}).Config(base)`. It runs again on every redraw, declares what is on screen with value types, and keeps no layout cache. State lives in the model; a click changes it where the control is declared. -- A page imports `github.com/vivaui/viva/ui` alone: colors, geometry and the theme are re-exported there (`ui.RGB`, `ui.Rect`, `ui.Theme`, `ui.LightTheme()`). `gfx` is the layer below (Canvas, paths, input events, keys, identities); reach for it only to draw or handle input yourself. -- Write an application page as `func (m *model) page(c ui.C)` and open it with `ui.Run(config, m.page)` or `ui.NewPage(ui.PageConfig{View: m.page}).Config(base)`. Every element is a function of `ui` taking `c` first, and controls write into your values: `ui.Checkbox(c, &m.done, "Done")`, `ui.Choice(c, &m.tab, tabs, nil)`, `ui.TextField(c, &m.name, "Name", "")`, `ui.Modal(c, &m.open, "Title", body, footer)`, `ui.Popover(c, anchor, &m.menu, body)` (`ui.PopoverWith` takes a `PopoverSpec`: `Width`, `Title`, `Description` and `TitleWeight` for the header, and a `Height` on the body fixes the panel's height). A list whose rows hold a `Button` declares each row with `c.Key(item.Name)` or `c.KeyInt(item.ID)`: `ui.Row(c.KeyInt(h.ID)).Children(...)`. A long list is `ui.List(c, &m.list, n, func(row ui.ListRow) { ... })`, which declares only the rows on screen and chooses, moves, submits (`Submitted()`), types ahead (`ListState.Label`) and, with `ListState.Selection`, chooses several, with `ScrollTo`/`ScrollIntoView`/`Visible` to scroll and `box.ClickModifiers()` for any click's modifier keys; `ListState.Header` pins section headings, `Reorder` lets rows be dragged, `RowWidth` scrolls wide rows sideways (`box.ScrollWith(&list)` for a header above); a part that rarely changes is `ui.Memo(c, *row, fn)`, which copies it while that value compares equal. Work that belongs to the page is a `ui.NewEffect[Result, Key](run)` declared with `ui.Effect(c, state, key)` and read once with `state.Take()`: a new key cancels and restarts, a paint that stops declaring it or a closing window cancels it (`NewEffectKeyed` passes the key to the run; `.Sequential()` waits for a cancelled run to return before the next starts). An element's own small state is `ui.State[T](c, "open")`, found by its name in its container. `ui.TextArea(c, &m.notes, label, "")` is several rows. A control of your own (terminal, editor, canvas) is `ui.Control(c, label, &m.handlers).Draw(m.draw)`, its `ui.Handlers` taking keys, pointer, wheel and (RoleTerminal/RoleTextField) typing through `Text`; it needs no identities or window-level dispatch. `ui.TextField(...).AutoFocus()` focuses a field as it appears and `.Submitted()` reports Enter in it; `.Secure()` makes it a password field and `.OnKey(fn)` lets it claim keys such as Up, Down and Enter while it is being typed in. `.Tooltip("Delete")` is a control's tip. `ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { if menu.Item("Rename").Clicked() { ... } })` is a dropdown menu of actions (typing a letter goes to its item; `menu.Sub(label, body)` is a submenu); `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` is a Select the user filters by typing (`.Clearable()`, `.Empty(text)`, `.Creatable("")` with `.Created()`); toasts are a `ui.Toaster` in the model, `m.toaster.Show(title, description, ui.ToastSuccess)`, painted by `ui.Toasts(c, &m.toaster)` declared once; `ShowAction(..., "Undo")` and `Acted()` give one a button, `ui.ToastLoading` stays until `Done(id, ...)`, `Toaster.Position` picks the corner. `ui.Button(c, "New").Icon(plus)` is a button with an icon. `ui.ContextMenu(c, target, func(menu *ui.MenuItems) { ... })` is a right-click menu (items take `.Icon`, `.Keys`, `.Checked`, `.Chosen`). `ui.TextField(...).Icon(search).Action(cross, "Clear")` is a search field, `.ActionClicked()` its button. `ui.Drawer(c, &m.open, title, ui.DrawerSpec{...}, body, footer)` is a side panel (`Swipe: true` adds a handle that dragging toward the edge closes it by). `ui.Tree(c, &m.tree, n, label, content)` is a virtualized tree whose `TreeState.Node` describes each visible row (typeahead by name; `CanDrop` plus `Dropped()` for drag and drop, the move done in `c.After`); `Toggled()` and `Chosen()` report what the user did; a part of a row that needs an identity, such as the name that carries the row's `ContextMenu`, is `ui.Text(c, name).LabelFor(m.tree.RowID(i))`, a label of the row that clicks, hover and right clicks reach as the row, not a `Hit` box, which would take the row's clicks. Any other box drags and drops with a `ui.DragState` in the model: `.DragSource(&m.drag)` on a `Hit` box and `.DropTarget(&m.drag, accept, drop)` on another; a part declared in a `Control`'s `Draw` with `d.Canvas.Hit(part, r)` is a source or target with `d.DragSource(&m.drag, part, r)` and `d.DropTarget(&m.drag, part, r, accept, drop)`, and a target part needs no Hit; The page routes the pointer, `Dragging()`/`Source()`/`Target()`/`At()` paint the gesture, and a press that does not move stays a click. A shortcut is declared where it acts: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }` for the page, `box.Shortcut(0, "delete")` while the focus is in that element (the innermost wins; a List's rows count as in the List its box names); plain keys stay with a field being typed in. A form row is `ui.FormField(c, &m.proxy, "Proxy").FillWidth().Children(func() { ... })`, with the title and one control child in the slot `components.BeginField` uses, at the same rhythm; the `ui.FormFieldState` is kept in the model beside the value. An application overlay is `ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: r})` (or `ui.LayerDrag` for a drag ghost): a floating page region painted after the page on a band below Viva's menus and dialogs, with no dismissal or focus trap; its children are page elements, and a `Canvas.Block` over its empty surface keeps presses from the page behind. A settings struct gets its form from tags: `form:"Label"` on its fields and `//go:generate go tool viva form` write `func (v *T) Form(c ui.C) ui.Box` (see `viva help form`). [`page/main.go`](https://github.com/vivaui/viva/blob/main/examples/guides/page/main.go) is a complete page. -- A custom layout is `ui.CustomLayout(c, &m.layout).Children(...)`: implement `ui.Layout`'s `MeasureWidth`, `PlaceWidth`, `MeasureHeight` and `PlaceHeight`; the page keeps identity, focus and hits, and the layout owns its children's sizes and positions. PlaceHeight may move a child after heights are measured: the page moves its subtree and re-places its popups. Wrap it in `Scroll`, `List` or `Tree` for scrolling; it is not declared in a `Memo`. `c.Bounds()` and `c.Canvas()` are the page rectangle and canvas for measuring and interaction state. A drag of your own reads `ListState.RowHeightAt(i)` (also on a `TreeState`) for the height the last paint gave row i; `RowID(i)` is a row's identity for focus and hit lookups (`TreeState.DisclosureID(i)` its chevron's). -- An application-named dialog is `ui.Dialog(c, ui.DialogSpec{...})`: `Scope`, `DismissID`, `CloseID`, `InitialFocusID` and `Layer` are yours; `.Header(fn)` declares controls in the title row, `.Body(fn)` the content and `.Footer(fn)` the buttons, and `.Dismissed()` reports the closing click. `ui.Modal`/`ModalWith` remain the generated-identity form. -- Put a strip of controls in one Tab stop with `ui.Row(c).FocusGroup(ui.FocusHorizontal)`; the arrows move between them. `.FocusOrder` gives a custom grid row/column order instead of declaration order. -- Handle a click where the control is declared: `ui.Button(c, label).Clicked()` is true for the one paint that delivers the click, and only then may state change. A handler that changes the list being declared, or may block, goes in `c.After(func() { ... })`. `Choice`, `Tabs` and `Select` write as they are declared: disable them with an `if`, not a `Disabled` after them. -- A component is a function of the page: `func Name(c ui.C) ui.Box`, declared where it is used. `ui.ID(c)` names a custom control by its place (or the Key or `c.Part("word")` before it); `ui.Control` + `ui.Handlers` takes input for a control you paint yourself. A component does not reach a lower layout engine, and it does not declare a `gfx.Tree`. +```go +type model struct { + name string + notify bool +} -- Layout is `ui` either way. Components are source-distributed, typed Go, one file per component; read the file rather than looking for a hidden style engine. -- Make it look finished by taking, not inventing: colors from the theme (`theme.Card`, `theme.MutedForeground`, `theme.Border`), radii from `theme.Metrics`, lengths in multiples of 4, and state from looks (`Hover`, `Pressed`, `Focus`, `Transition`) rather than hand-read canvas state. [`examples/recipes`](https://github.com/vivaui/viva/tree/main/examples/recipes) holds nine finished components written that way (settings row, list row with a hover pencil, avatar with presence dot, badge, stat card, gradient hero, toolbar icon button, empty state, dimmable section), each tested in both themes: copy the nearest one and change it before composing from scratch. [`recipes.md`](recipes.md) says which to start from and what to avoid. -- Prefer a few intention-revealing parameters. When same-typed positional arguments pile up, use a small struct or chainable options. +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + ui.Text(c, "Settings").FontSize(20).Bold() + ui.TextField(c, &m.name, "Name", "Your name") + ui.Switch(c, &m.notify, "Notify me") + if ui.Button(c, "Save").Clicked() { + m.save() + } + }) +} +``` -## 4. Verify without opening a window +- A page imports `github.com/vivaui/viva/ui` alone: colors, geometry and the theme are re-exported there (`ui.RGB`, `ui.Rect`, `ui.Theme`, `ui.LightTheme()`). `gfx` is the layer below (canvas, paths, input events, keys, identities); reach for it only to draw or handle input yourself. +- Everything is a function of `ui` taking `c` first, and the chain is the same everywhere: `.Pad`, `.Gap`, `.Grow`, `.Width`, `.Background`, `.Children(func() { ... })`. Containers: `Row`, `Column`, `Stack`, `Grid`, `Flow`, `Scroll`. Leaves: `Text`, `Paragraph`, `Wrap`, `Spacer`, `Divider`, `Icon`, `Image`, `Button`, `Checkbox`, `Switch`, `Select`, `Choice`, `Tabs`, `Slider`, `Progress`, `Spinner`, `Splitter`, `Slot`. +- Lengths are `float32`; sizes are border boxes. A child is as big as its content unless told `Width`/`Height`/`Size`, `Fill`, or `Grow(n)`. In a `Row`, a text field needs `Grow(1)` or `Width`, or it is invisible. -Do not open a real window unless the user agrees; it interrupts them and depends on which display it lands on. Use these in order of cost. +### Lists, tables and trees + +- A long list is `ui.List(c, &m.list, n, func(row ui.ListRow) { ... })`: only the rows on screen are declared. The row's container is `row.Element`, its content is declared with `row.C`. `Selected()`, `Changed()`, `Submitted()`, `ListState.Label` (typeahead), `Selection` (multi-select), `ScrollTo`/`ScrollIntoView`/`Visible`, `Header` (pinned sections), `Reorder` (drag rows), `RowWidth` (sideways scrolling), `ClickModifiers()`. Key rows that hold a `Button`: `ui.Row(c.KeyInt(item.ID))`. +- A table is `ui.Table(c, &m.table, ui.TableSpec{Headers, Sortable, Source, Columns})`; the data is a `ui.TableRows` (`[][]string`) or your own `Len() int` / `Cell(row, col int) string`. `RowClicked()`, `HeaderClicked()`, `SortBy`, `Select`. +- A tree is `ui.Tree(c, &m.tree, n, label, content)` with a `TreeState.Node` per visible row; `Toggled()` and `Chosen()` report the user's action; `CanDrop` + `Dropped()` for drag and drop. `RowID(i)` is a row's identity; a part of a row is `ui.Text(c, name).LabelFor(m.tree.RowID(i))`. +- A part that rarely changes is `ui.Memo(c, *row, fn)`: it copies the declaration while that value compares equal. Pass the row (or what the function reads), not a counter. +- Scrolling: `area := ui.Scroll(c).Grow(1)`; `area.ScrollState()` has `Offset`, `Content`, `Viewport`, `Max()`, `AtEnd()`, `Pinned()`, `ScrollTo`, `ScrollToEnd`; `.Follow(true)` keeps a log or chat at its end; `.Sideways()` and `.Scrollbars()` add horizontal movement and bars. + +### Dialogs, menus and popups + +- `ui.Modal(c, &m.open, "Title", body, footer)` or `ui.ModalWith(..., ui.ModalSpec{...}, ...)`. The title is required; Escape, the close button and a press on the scrim set `m.open` to false, so do not write an Escape handler. `ui.Dialog(c, ui.DialogSpec{...})` is the form whose identities you name: `Scope`, `DismissID`, `CloseID`, `InitialFocusID`, `.Header`, `.Body`, `.Footer`, `.Dismissed()`. +- `ui.Popover(c, anchor, &m.open, body)` / `ui.PopoverWith(c, anchor, ui.PopoverSpec{...}, &m.open, body)`; `ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { ... })` with `menu.Item("Rename").Clicked()`, `menu.Sub(label, body)`; `ui.ContextMenu(c, target, func(menu *ui.MenuItems) { ... })`; `ui.Drawer(c, &m.open, title, ui.DrawerSpec{...}, body, footer)`. +- An application overlay is `ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: r})` (or `ui.LayerDrag`): it takes no room, paints below Viva's menus and dialogs, and a `Canvas.Block` over its empty surface keeps presses from the page behind. +- Toasts: keep a `ui.Toaster`, `m.toaster.Show(title, text, ui.ToastSuccess)`, paint `ui.Toasts(c, &m.toaster)` once; `ShowAction(..., "Undo")` + `Acted()`, `ToastLoading` + `Done(id, ...)`, `Toaster.Position`. + +### Forms and fields + +- `ui.TextField(c, &m.name, "Name", "placeholder")` binds a `string`; `&m.query` can bind a `ui.Field` when the caret or selection matters. `.Submitted()` is Enter, `.Secure()` a password, `.AutoFocus()`, `.Icon(icon).Action(icon, "Clear")` with `.ActionClicked()`. `ui.TextArea(c, &m.notes, "Notes", "").Height(120)` is several rows. `Config.TextInput` is not needed for typing, caret, selection, clipboard or IME. +- `ui.FormField(c, &m.proxyField, "Proxy").FillWidth().Children(func() { ... })` is a form row: one title and one control child, in the slot `components.BeginField` uses. Keep the `ui.FormFieldState` beside the value. Tagged structs get the same form from `//go:generate go tool viva form`. +- `ui.Choice(c, &m.theme, themes, nil)` is a segmented choice and `ui.Tabs(c, &m.tab, tabs, nil)` a tab strip. Both write the value as they are declared; disable them with an `if`, not a chained `.Disabled`. `Tabs`/`Select` also honor `.Disabled` for input; `Choice` does not. + +### Background work and animation -1. **`app.Driver`** in a Go test: runs your real painter, router and focus rules from explicit calls (`Click`, `Key`, `Type`, `Scroll`, `Advance`) and returns a `Snapshot` of labels, hit regions and focus; `app.NewDriver(ui.NewPage(ui.PageConfig{View: m.page}).Config(base), nil)` drives a page, whose controls a test finds by their name (`Hit.Label`). See [`hello/main_test.go`](https://github.com/vivaui/viva/blob/main/examples/guides/hello/main_test.go). Test behavior a user depends on, not pixel offsets or exact primitive counts. -2. **Headless build and line protocol**: import `github.com/vivaui/viva/headless/auto` from a file guarded by `//go:build vivahead`, so release builds never contain it. Build with `-tags vivahead` and start the program with `VIVA_HEADLESS=1` and a throwaway `HOME`: `RunCanvas` then reads one command per line from stdin instead of opening a window (`click "Label"`, `type`, `key`, `waitfor`, `shot`, `texts`, `layout` ...). Each reply ends in one `ok` or `error` line. The complete command list is the comment above `Serve` in [`headless/control.go`](https://github.com/vivaui/viva/blob/main/headless/control.go); do not copy it elsewhere, it would go stale. -3. **`layout`** lists text that is clipped, spills out of its control or lies over other text. It is faster to read than a screenshot; use `shot` when the look itself matters. - **`tree`** lists every control with its role, identity, accessible name, value and state (focused, disabled, checked, covered ...); read it first to learn what the frame can do. A control with no name is reached by identity or role: `click id:home/auto`, `click checkbox:`, `click "button:Save"`. **`expect`** turns a look into a check that fails with what the frame has instead: `expect text "Connected" within 5000`, `expect state id:home/auto checked`, `expect layout clean`, `expect named`. Prefer a script that ends in `expect` lines to one you read by eye, and put `expect` lines in the Go test for anything a user depends on (`Session.Expect` takes the same words). When a step fails: not found, run `tree`; text cut off, `layout`; focus wrong, `focus`; a press does nothing, look for `covered` in `tree`. -4. **Real windows** on each target platform for anything the above cannot see: IME, focus loss, window-manager close, physical keyboard, high-DPI. Say plainly what you did not test. +- Page work is a `ui.Effect`, never a goroutine started in the page: `var load = ui.NewEffect[Result, Key](run)`, declared with `ui.Effect(c, m.load, key)` and read with `m.load.Take()`. A new key cancels and restarts; `.Sequential()` waits for the cancelled run; `NewEffectKeyed` passes the key to the run. The run must not touch a `C`, `Box` or `Page`. +- A long-lived worker of your own stores its result under a lock, calls `Invalidator.Invalidate()`, and `Config.OnWake` copies it into the model on the window thread. +- Animation is a scheduled reason to draw, not a loop: read `c.Canvas().Now()`, call `c.Canvas().RequestFrame()` while it is still moving, and stop asking when it stops. `Progress` and `Spinner` schedule their own frames. -Before finishing, run `gofmt`, `go vet ./...`, `viva vet` (or `go tool viva vet`) and `go test ./... -count=1`. `viva vet` reports the page mistakes that compile: a constant-labeled `Button` in a loop whose rows have no `c.Key`/`c.KeyInt`, a `ui.C` or `ui.Box` kept in a struct/global or given to a goroutine, and a `ui.Memo` whose value misses a field its function reads; each finding says what to write instead. Run tests with `ui.MemoCheck(true)` (or `PageConfig.MemoCheck`) when a page uses `Memo`: it panics where the value misses something the part reads. For painting or input paths, report allocations per paint and steady-state time with `go test -bench`; for a change that affects linking, report the stripped binary size before and after. +### Custom controls, drawing and drag -## 5. Where to look +- A control you paint is `ui.Control(c, label, &m.handlers).Grow(1).Draw(m.draw)`. `ui.Handlers` receives keys, pointer, wheel and, with `gfx.RoleTextField` or `gfx.RoleTerminal`, typing and IME through `Text`. Its parts are declared in `Draw` with `d.Canvas.Hit(part, r)`; an event on a part reaches the same handlers with the part as its target. +- Custom layout: `ui.CustomLayout(c, &m.layout).Children(...)` with `ui.Layout`'s `MeasureWidth`, `PlaceWidth`, `MeasureHeight`, `PlaceHeight`. The page keeps identity, focus and hits; the layout owns the children's geometry. +- Drag and drop: a `ui.DragState` in the model, `.DragSource(&m.drag)` and `.DropTarget(&m.drag, accept, drop)` on `Hit` boxes, or `d.DragSource`/`d.DropTarget` inside a `Draw`. The page routes the pointer; `Dragging()`, `Source()`, `Target()`, `At()` paint the gesture. A press that does not move is still a click. A split pane is `ui.Splitter(c, &m.split)` with a `ui.SplitterState`, not a drag. +- Painting your own thing: `ui.Slot(c).Draw(func(d *ui.DrawContext) { ... })`, with `d.Canvas.Fill`, `Rounded`, `Border`, `RoundedBorder`, `Elevate`, `DrawPath`, `Label`, `LabelCenter`, `d.Fade`, `d.DashedBorder`. A circle is a `Rounded` square. `Box.Rect()` is only valid in the paint that declared it. +- A shortcut is declared where it acts: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }`; `box.Shortcut(0, "delete")` acts while the focus is inside that element. Plain keys stay with a field being typed in. -- Guides: (programming model, declarative layout, handling input, text input, overlays, theming, performance, testing, platforms). -- Platform behavior and what still needs a real window: [`docs/conformance.md`](https://github.com/vivaui/viva/blob/main/docs/conformance.md). +### Look finished + +Take, do not invent: + +- Colors and space come from the theme: `theme.Card`, `theme.MutedForeground`, `theme.Border`, radii from `theme.Metrics`, lengths in multiples of 4. +- Hover, pressed and focus are looks (`Hover`, `Pressed`, `Focus`, `Transition`), not hand-read canvas state. +- [`examples/recipes`](https://github.com/vivaui/viva/tree/main/examples/recipes) holds nine finished components (settings row, list row, avatar, badge, stat card, hero, icon button, empty state, dimmable section), each tested in both themes. Copy the nearest one and change it. +- [`recipes.md`](https://vivaui.dev/skills/building-with-viva/recipes.md) says which one to start from and what to avoid. +- Components are source-distributed, typed Go, one file per component: read the file rather than looking for a hidden style engine. + +A component is a function of the page: `func Name(c ui.C) ui.Box`, declared where it is used. `ui.ID(c)` names a custom control by its place (or the Key or `c.Part("word")` before it). A component does not reach a lower layout engine and does not declare a `gfx.Tree`. + +## 4. Where to look + +- The project's own `AGENTS.md`, written by `viva init`, is the compact API reference. Read it before inventing a name. +- Guides: — programming model, declarative layout, handling input, text input, overlays, theming, performance, testing, platforms. +- Platform behaviour and what still needs a real window: [`docs/conformance.md`](https://github.com/vivaui/viva/blob/main/docs/conformance.md). - Measurements and the machines they were taken on: [`docs/benchmarks/`](https://github.com/vivaui/viva/tree/main/docs/benchmarks). + +## 5. Verify without opening a window + +Do not open a real window unless the user agrees; it interrupts them and depends on which display it lands on. Use these in order of cost. + +1. **A Go test with `app.Driver`.** `driver, err := app.NewDriver(ui.NewPage(ui.PageConfig{View: m.page}).Config(base), nil)` runs the real painter, router and focus rules. Drive it with `Click`, `Key`, `Type`, `Scroll`, `Resize`, `Advance`, and read `driver.Snapshot()` for the labels, hit regions and focus. Find controls by their accessible name (`Hit.Label`), not by pixel. See `examples/guides/hello/main_test.go`. +2. **The headless line protocol.** Import `github.com/vivaui/viva/headless/auto` from a file guarded by `//go:build vivahead`, build with `-tags vivahead`, and start the program with `VIVA_HEADLESS=1` and a throwaway `HOME`. It reads one command per line: `click "Label"`, `type`, `key`, `waitfor`, `shot`, `texts`, `layout`, `tree`, `focus`, `expect`. Each reply ends in `ok` or `error`. The full command list is the comment above `Serve` in [`headless/control.go`](https://github.com/vivaui/viva/blob/main/headless/control.go); do not copy it elsewhere. +3. **Read the frame.** + - `layout` lists text that is clipped, spills or overlaps. + - `tree` lists every control with its role, identity, name, value and state (`focused`, `disabled`, `covered` ...). + - `expect` turns a look into a check that fails with what the frame has instead: `expect text "Connected" within 5000`, `expect state id:home/auto checked`, `expect layout clean`, `expect named`. `Session.Expect` takes the same words in a Go test. + - When a step fails: not found → `tree`; text cut off → `layout`; focus wrong → `focus`; a press does nothing → look for `covered`. +4. **A real window** on each target platform for IME, focus loss, window-manager close, physical keyboard and high-DPI. Say plainly what you did not test. + +## 6. Before you finish + +- `gofmt`, `go vet ./...`, `viva vet` (or `go tool viva vet`), `go test ./... -count=1`. +- If the page uses `Memo`, run the test with `ui.MemoCheck(true)` (or `PageConfig.MemoCheck`): it panics where the value misses something the part reads. +- For a painting or input path, report allocations per paint and steady-state time from `go test -bench`; for a linking change, report the stripped binary size before and after. +- State what you verified and what you did not: unit tests, headless `layout`/`expect`, and real-window behaviour are different claims. diff --git a/docs/skills/building-with-viva/recipes.md b/docs/skills/building-with-viva/recipes.md index 20c901c18..743347342 100644 --- a/docs/skills/building-with-viva/recipes.md +++ b/docs/skills/building-with-viva/recipes.md @@ -1,12 +1,12 @@ # Recipes: making a Viva screen look finished -Read after `SKILL.md`. The code is in [`examples/recipes`](../../../examples/recipes), compiled and tested in light and dark, so it cannot drift from the API. This page says when to use which, and what makes the result look designed instead of assembled. +Read after `SKILL.md`. The code is in [`examples/recipes`](https://github.com/vivaui/viva/tree/main/examples/recipes), compiled and tested in light and dark, so it cannot drift from the API. This page says when to use which, and what makes the result look designed instead of assembled. ## Start from the nearest recipe | You are building | Start from | | --- | --- | -| A page of preferences | `SettingsRow` inside `Section` (a card with a divider between rows: `ui.Divider(c)`) | +| A page of preferences | `SettingsRow` inside `Section`; `Section` is the card, insert `ui.Divider(c)` between rows yourself | | A list of hosts, files, mailboxes | `ListRow`: hover and keyboard focus reveal the trailing action | | A person or a host | `Avatar`, with the presence dot when it has one | | A tag, a count, a status | `Badge` with `ToneNeutral`, `ToneAccent` or `ToneDanger` | @@ -16,7 +16,7 @@ Read after `SKILL.md`. The code is in [`examples/recipes`](../../../examples/rec | A list with nothing in it | `EmptyState` | | Anything that reacts but is none of these | `Interactive(box, theme)` around your own `Row` (give it `Hit` first) | -The recipes take a `ui.C`, as every page component does, and return the Box the caller reacts from. They are page components: use them where you declare the row, give an interactive row `Hit(ui.ID(c), name)` before `Interactive`, and read `Clicked` from the result. They are not a separate Frame API. +The recipes take a `ui.C` and the theme — `func SettingsRow(c ui.C, theme gfx.Theme, ...) ui.Box` — as every page component does, and return the Box the caller reacts from. They are page components: use them where you declare the row, give an interactive row `Hit(ui.ID(c), name)` before `Interactive`, and read `Clicked` from the result. They are not a separate Frame API. ## What makes it look right @@ -24,7 +24,7 @@ The recipes take a `ui.C`, as every page component does, and return the Box the - **One scale for space.** Lengths are 4, 8, 12, 16, 24. A row of controls uses `Gap(8)`, a card `Pad(16)`, a page `Pad(24)`. Equal gaps between siblings read as order; mixed ones read as accident. - **Two radii.** Controls and rows take `theme.Metrics.RadiusControl`, cards and panels `RadiusSurface`, a circle is half its size or `gfx.RadiusFull`. Do not invent a third. - **Hierarchy by weight and color, not size.** A title is `Weight(gfx.WeightMedium)`, its explanation is `.Muted()` at `FontSizeS`. Reserve a large `FontSize` for one figure or heading per screen. -- **Every reactive thing has all three looks.** Hover to show it is live, Pressed to show it took the press, Focus with `Ring(3, ...)` so the keyboard user can see where they are. `Interactive` gives the standard set; `Transition()` makes them fade instead of snap. +- **Every reactive thing has all three looks.** Hover to show it is live, Pressed to show it took the press, Focus with `Ring(3, theme.Ring)` so the keyboard user can see where they are. `Interactive` gives the standard set; `Transition()` makes them fade instead of snap. - **Reveal with `StateFrom`.** Secondary actions that appear on hover (`Opacity(0)` at rest, `Hover(Look{}.Opacity(1))`, and `Focus` too so a keyboard user can find them) keep a list calm. Do not read `canvas.Hovered()` by hand. - **Shadow sparingly.** `ShadowXS` for a card on the page, `ShadowMD` for something lifted (a hero, a popover). Never on every row. - **Gradients are an accent.** A thin bar (`StatCard`), a hero, an avatar background. Two or three stops, hues close together; a large gradient behind body text needs white text and a contrast check. @@ -38,4 +38,4 @@ The recipes take a `ui.C`, as every page component does, and return the Box the ## Checking your own -Draw it in both themes and run `layout` (see `SKILL.md`, section 4). Add a test like `recipes_test.go`'s: every state you declared appears with the right trigger, nothing overflows its column, and a warm page allocates nothing. +Draw it in both themes and run `layout` (see the verification section of `SKILL.md`). Add a test like `recipes_test.go`'s: every state you declared appears with the right trigger, nothing overflows its column, and a warm page allocates nothing. diff --git a/examples/guides/table/main.go b/examples/guides/table/main.go new file mode 100644 index 000000000..34fde6668 --- /dev/null +++ b/examples/guides/table/main.go @@ -0,0 +1,73 @@ +// A table of servers: a fixed header, sortable columns, one selected row and a +// body that scrolls under the header when the window is short. +package main + +import ( + "log" + "sort" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/ui" +) + +type model struct { + table ui.TableState + rows ui.TableRows +} + +func newModel() *model { + return &model{rows: ui.TableRows{ + {"web-01", "Running", "eu-west"}, + {"web-02", "Running", "us-east"}, + {"db-primary", "Degraded", "eu-west"}, + {"cache", "Stopped", "us-east"}, + }} +} + +// page declares the table. A header click sorts the rows and a row click +// selects it; the table keeps the selection and the scroll position itself. +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + ui.Text(c, "Servers").FontSize(20).Bold() + table := ui.Table(c, &m.table, ui.TableSpec{ + Headers: []string{"Name", "State", "Region"}, + Sortable: []bool{true, true, true}, + Source: &m.rows, + Striped: true, + Columns: []components.TableColumn{{Width: 200}, {Width: 120}, {}}, + }) + if row, ok := table.RowClicked(); ok { + m.table.Select(row) + } + if column, ok := table.HeaderClicked(); ok { + m.table.SortBy(column) + m.sortRows() + } + if row := m.table.Selected(); row >= 0 { + ui.Text(c, "Selected: "+m.rows[row][0]).Muted() + } + }) +} + +// sortRows orders the rows by the column the table reports as sorted. The table +// paints the arrow; the application owns the data and its order. +func (m *model) sortRows() { + column, descending, ok := m.table.Sort() + if !ok { + return + } + sort.SliceStable(m.rows, func(i, j int) bool { + less := m.rows[i][column] < m.rows[j][column] + if descending { + return !less + } + return less + }) +} + +func main() { + if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, newModel().page); err != nil { + log.Fatal(err) + } +} diff --git a/examples/guides/table/main_test.go b/examples/guides/table/main_test.go new file mode 100644 index 000000000..1cb3d361d --- /dev/null +++ b/examples/guides/table/main_test.go @@ -0,0 +1,61 @@ +package main + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/app" + "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: 720, Height: 480}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + return driver +} + +// click presses the middle of the control a user would find by its name. +func click(t *testing.T, driver *app.Driver, name string) { + t.Helper() + for _, hit := range driver.Snapshot().Hits { + if strings.HasPrefix(hit.Label, name) { + b := hit.Bounds + if err := driver.Click(b.X+b.Width/2, b.Y+b.Height/2); err != nil { + t.Fatal(err) + } + return + } + } + t.Fatalf("no control named %q on screen", name) +} + +func shows(driver *app.Driver, want string) bool { + for _, label := range driver.Snapshot().Labels { + if strings.Contains(label.Value, want) { + return true + } + } + return false +} + +func TestTheTableSortsAndSelects(t *testing.T) { + m := newModel() + driver := open(t, m) + if !shows(driver, "web-01") || !shows(driver, "cache") { + t.Fatal("the rows should be painted") + } + click(t, driver, "Name") + column, descending, ok := m.table.Sort() + if !ok || column != 0 || descending { + t.Fatalf("sort = %d, %v, %v; the first header click sorts ascending", column, descending, ok) + } + click(t, driver, "web-02") + if got := m.table.Selected(); got < 0 || !strings.Contains(m.rows[got][0], "web-02") { + t.Fatalf("selected row = %d (%v)", got, m.rows) + } +} diff --git a/tools/aieval/aieval_test.go b/tools/aieval/aieval_test.go index 6a19fd0fe..4db0d3aa3 100644 --- a/tools/aieval/aieval_test.go +++ b/tools/aieval/aieval_test.go @@ -1,6 +1,8 @@ package main import ( + "os" + "path/filepath" "strings" "testing" ) @@ -39,3 +41,54 @@ func TestModelConfigAndFlag(t *testing.T) { t.Fatal("a model without a key variable must be refused") } } + +// Every task is a request a user would make; the generated project guide is the +// only document aieval sends, so each task must have a section there that tells +// the model where to start. A task whose group is missing from this map is a +// gap in the guide, not just in the test. +var taskRoutes = map[string]string{ + "form": "Forms and fields", "login": "Forms and fields", "wizard": "Forms and fields", + "settings": "Forms and fields", "steppers": "Forms and fields", "search": "Forms and fields", + "todo": "Lists, trees and scrolling", "cart": "Lists, trees and scrolling", + "inbox": "Lists, trees and scrolling", "notifications": "Lists, trees and scrolling", + "logviewer": "Lists, trees and scrolling", "kanban": "Lists, trees and scrolling", + "masterdetail": "Lists, trees and scrolling", "calendar": "Lists, trees and scrolling", + "filetree": "Lists, trees and scrolling", "gallery": "Lists, trees and scrolling", + "chat": "Lists, trees and scrolling", + "table": "Tables", + "tabs": "Tabs and select", + "modal": "Menus, dialogs and popups", "dashboard": "Menus, dialogs and popups", + "progress": "Animation and time", "pomodoro": "Animation and time", "mediaplayer": "Animation and time", + "darktheme": "The theme", "colorpicker": "The theme", + "splitter": "Keys, drag and the mouse", + "twowindows": "Several windows", +} + +func TestEveryTaskHasAGuideRoute(t *testing.T) { + guide, err := os.ReadFile("../../cmd/viva/initfiles/AGENTS.md.txt") + if err != nil { + t.Fatal(err) + } + files, err := filepath.Glob("tasks/*.md") + if err != nil { + t.Fatal(err) + } + seen := map[string]bool{} + for _, file := range files { + task := strings.TrimSuffix(filepath.Base(file), ".md") + seen[task] = true + section, ok := taskRoutes[task] + if !ok { + t.Errorf("task %s has no guide route; add it to taskRoutes and a section to the generated guide", task) + continue + } + if !strings.Contains(string(guide), "## "+section) { + t.Errorf("task %s routes to %q, which the generated guide does not have", task, section) + } + } + for task := range taskRoutes { + if !seen[task] { + t.Errorf("taskRoutes names %s, but tools/aieval/tasks has no such task", task) + } + } +} diff --git a/ui/focus_bind.go b/ui/focus_bind.go index 43cbc45db..2e2b63940 100644 --- a/ui/focus_bind.go +++ b/ui/focus_bind.go @@ -17,7 +17,10 @@ import "github.com/vivaui/viva/gfx" // belongs to one window at a time, so give each window its own. The element // needs an identity: a control, or a container after Hit. // -// a := ui.FocusBind(ui.TextField(c, &m.query, "Search", ""), &m.focus, FocusSearch) +// a := ui.FocusBind(ui.TextField(c, &m.query, "Search", ""), &m.focus, focusSearch) +// +// where focusSearch is a value of the application's own (such as +// const focusSearch = "search"); *field holds a value of that type. // // Not inside a Memo, whose copies are not declared. Use FocusedValue to read the // focus that is committed, rather than the request. diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 02d251720..4a56fece6 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -120,6 +120,11 @@ const siteFiles = () => ({ '', ...await Promise.all(showcase.map(entry => entryOf(entry.pathname))), '', + '## Agent skill', + '', + `- [building-with-viva skill](${loc('skills/building-with-viva/SKILL.md')}): the briefing an agent loads before changing a Viva application.`, + `- [Recipe cheat sheet](${loc('skills/building-with-viva/recipes.md')}): which finished example to start from.`, + '', '## Optional', '', `- [Documentation in Chinese](${loc('zh/docs/')}): the same guides, translated.`, diff --git a/website/content/guides/en/build-and-package.md b/website/content/guides/en/build-and-package.md index 8cfad3715..28a255887 100644 --- a/website/content/guides/en/build-and-package.md +++ b/website/content/guides/en/build-and-package.md @@ -41,7 +41,7 @@ The recipes `viva add` writes come with the command, so the command and the Viva ```sh go tool viva add --out ./components button -go get -tool github.com/vivaui/viva/cmd/viva@v0.1.3 # pin an existing project +go get -tool github.com/vivaui/viva/cmd/viva@v0.6.5 # pin an existing project ``` `viva doctor` and `viva add` warn when the command in your `PATH` and the project disagree. diff --git a/website/content/guides/en/coding-agents.md b/website/content/guides/en/coding-agents.md index b2f3987f0..9e14fd4bd 100644 --- a/website/content/guides/en/coding-agents.md +++ b/website/content/guides/en/coding-agents.md @@ -6,7 +6,7 @@ group: start skill: building-with-viva --- -Viva draws its own interface, repaints only on request and has no layout cache, so an agent that writes it like a web or retained-mode toolkit produces code that review rejects. The `building-with-viva` skill is a short briefing that an agent loads before it touches a Viva application. It is one Markdown file with no code to run. +Viva draws its own interface, repaints only on request and has no layout cache, so an agent that writes it like a web or retained-mode toolkit produces code that review rejects. The `building-with-viva` skill is a short briefing that an agent loads before it touches a Viva application. It is two Markdown files with no code to run: the briefing and a recipe cheat sheet. ## What the skill covers @@ -26,6 +26,8 @@ Download the file into your project's skills directory. Claude Code reads `.clau mkdir -p .claude/skills/building-with-viva curl -fsSL https://vivaui.dev/skills/building-with-viva/SKILL.md \ -o .claude/skills/building-with-viva/SKILL.md +curl -fsSL https://vivaui.dev/skills/building-with-viva/recipes.md \ + -o .claude/skills/building-with-viva/recipes.md ``` In a checkout of Viva itself, copy or symlink `docs/skills/building-with-viva` instead. The repository's `AGENTS.md` takes precedence over the skill there. diff --git a/website/content/guides/en/declarative-layout.md b/website/content/guides/en/declarative-layout.md index 80f5332ee..875914383 100644 --- a/website/content/guides/en/declarative-layout.md +++ b/website/content/guides/en/declarative-layout.md @@ -59,7 +59,7 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page) `ui.Choice` and `ui.Tabs` are one tab stop each: Left and Right (Up and Down for vertical tabs) move to the next enabled option, wrapping, and choose it; Home and End go to the first and last. -A click flips `m.sync` in the paint that delivers it, the first time the control is asked (`Clicked`, `Changed`) or else when the page ends, so reading `m.sync` before that sees the value from before the click and a `Disabled` written after the control still holds. `Choice`, `Tabs` and `Select` take a value of any comparable type and write it as they are declared: disable them with an `if`, not a `Disabled` after them. `TextField` needs no `Config.TextInput`: the page's `Config` gives the platform the editor of each field it declared, and passes any other focused field to the provider the configuration already had. `Popover` and `Modal` open while a `*bool` is true and set it to false when dismissed (see [Dialogs, menus and popups](/en/docs/overlays/)). `Box.NativeView` gives a page of the system's web engine the room of an element. +A click flips `m.sync` in the paint that delivers it, the first time the control is asked (`Clicked`, `Changed`) or else when the page ends, so reading `m.sync` before that sees the value from before the click and a `Disabled` written after the control still holds. `Choice`, `Tabs` and `Select` take a value of any comparable type and write it as they are declared: disable them with an `if`, not a `Disabled` after them. `Tabs` and `Select` also honor a chained `Disabled` for input, `Choice` does not; the `if` is the reliable form. `TextField` needs no `Config.TextInput`: the page's `Config` gives the platform the editor of each field it declared, and passes any other focused field to the provider the configuration already had. `Popover` and `Modal` open while a `*bool` is true and set it to false when dismissed (see [Dialogs, menus and popups](/en/docs/overlays/)). `Box.NativeView` gives a page of the system's web engine the room of an element. An element is named by where it is: its kind and its number among the elements of that kind in its container. Three things refine that: @@ -67,7 +67,51 @@ An element is named by where it is: its kind and its number among the elements o - Inside `c.Key(item.ID)` or `c.KeyInt(id)`, elements are numbered within that row, so a row's buttons follow it when rows come, go or move. Keys are reused two paints after their row is gone. A loop whose rows hold a `Button` keys its rows; `viva vet` reports one that does not. - While the user holds a button (presses it, or it has the focus), a paint in which another button took its place does not deliver the press, and the focus is given up. -`ui.TextArea(c, &m.notes, label, placeholder)` is a field of several rows. A control of your own (a terminal, an editor, a canvas the user draws on) is `ui.Control(c, label, &m.handlers)`: an empty, focusable element you paint with `Draw`, whose `Handlers` receive its keys, presses, wheel and, for `RoleTextField` or `RoleTerminal`, the platform's typing and input methods through `Text`; no identity is declared and the window dispatches nothing. A control with several interactive parts (the stars of a rating, the nodes of a graph) declares them as it draws, with `Handlers.Parts().At(i)` as their identities: a key, a press or the wheel on a part reaches the same `Handlers` with the part as the event's `Target`, and a printable key typed while the control has the focus reaches `Key` with its `Text`. `.FocusGroup(ui.FocusHorizontal)` on a row or column makes the controls inside one Tab stop with the arrow keys between them, as a toolbar's are; `.FocusOrder` gives a custom grid the row and column order it needs. The controls without their look are `ui.ButtonBase`, `CheckboxBase`, `SwitchBase`, `ToggleBase`, `RadioBase`, `TabBase`, `SliderBase`, `SelectBase` and `TextFieldBase`: bound and keyed like their dressed forms, for a design of your own. `ui.TextField(...).AutoFocus()` takes the focus as the field appears (once: the user's choice stays), and `.Submitted()` is true in the paint that delivers Enter in it; `.Secure()` makes it a password field. `.Tooltip("Delete")` gives a control the tip shown while the pointer rests on it, which is also its description. `ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. `ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)` slides a panel in from an edge, as shadcn's Sheet: with an empty title the body has the whole panel, and `NonModal` leaves the keyboard on the page behind it; `Swipe` adds a handle at its inner edge, and a drag on it moves the panel toward its edge, closing it when dragged past half its size or thrown, sliding it back otherwise. `ui.Tree(c, &m.tree, n, label, content)` is a List of the visible rows of the application's tree, with `TreeState.Node` describing each (its depth, whether it is a branch and open); the arrows move, open and close, and the tree reports `Toggled()` and `Chosen()` for the application to act on. Typing the start of a row's name moves to it. With `TreeState.CanDrop` set, rows can be dragged onto one another (before, into or after a row, as `CanDrop` allows), and `Dropped()` reports the drop; move the rows in `c.After`, since the paint reporting it is still declaring them. `state.RowID(i)` is the identity of visible row i (`DisclosureID(i)` its chevron's, and `ListState` has `RowID` too), for giving a row the focus or finding its hit. Any other box can drag and drop with a `ui.DragState` kept in the model: `ui.Row(c).Hit(ui.ID(c), "Group").DragSource(&m.drag)` makes a box a source, and `.DropTarget(&m.drag, m.accepts, m.drops)` makes one a target. The page follows the press, the short distance that makes it a drag, and the target under the pointer; `m.drag.Dragging()`, `Source()`, `Target()` and `At()` paint the gesture, `accept(source, target)` decides, `drop(source, target)` runs on release, and Escape lets go. A press that does not move is still a click. Inside a `ui.Control`'s `Draw`, a card of a custom grid is declared as a part with `d.Canvas.Hit(part, r)` and becomes a source and target of the same state with `d.DragSource(&m.drag, part, r)` and `d.DropTarget(&m.drag, part, r, accept, drop)`, so one control carries many draggable parts with stable identities; a target part needs no Hit. Keep the callbacks in the model and declare the boxes every paint, not in a `Memo`. Toasts are a `ui.Toaster` kept in the model: `m.toaster.Show("Saved", "", ui.ToastSuccess)` puts one up, and `ui.Toasts(c, &m.toaster)`, declared once and last, paints them and takes each down after five seconds, asking for one frame when the next is due and none while nothing is up. `ShowAction(title, description, kind, "Undo")` gives one a button, whose press `m.toaster.Acted()` reports after `Toasts` and which takes the toast down; a `ui.ToastLoading` toast spins and stays until `m.toaster.Done(id, "Uploaded", "", ui.ToastSuccess)` replaces it; `Toaster.Position` puts the stack in another corner or centered (`ui.ToastTopCenter`). A keyboard shortcut is declared where it acts, as a click is read: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }` is the page's (Primary is Command on macOS, Control elsewhere), and `list.Shortcut(0, "delete")` on a container or control acts only while the focus is in it, the innermost of nested ones winning. A chord without Primary, Ctrl or Alt is left to a field or terminal being typed in, and while a Popover, Modal, Menu, or Select or Combobox list is open the page's own shortcuts wait. `ui.List(c, &state, n, row)` declares only the rows on screen of a list of `n`, each as tall as its content, and scrolls it; `row` gets a `ui.ListRow` whose `Element` is the row's container to style and whose `C` declares what is in it, and `ListState.Key` names rows by an item's ID. A click chooses a row and the arrows, Home, End and Page Up and Down move between them, with the choice in `state.Selected()` and `state.Changed()` reporting that the user made one; Enter or a double click is `state.Submitted()`; `ListState.Label` makes typing the start of a row's text move to it. Set `ListState.Selection` to a `ui.Selection` to let the user choose several (Primary-click adds or removes a row, Shift extends, Primary+A chooses all). `ScrollTo`, `ScrollIntoView`, `ScrollToEnd`, `Visible` and `AtEnd` move and read the scroll position, and `box.ClickModifiers()` and `box.DoubleClicked()` say how a click on any element came. A row's `Element` is a Row, so an icon, a name and a size lie side by side. `ListState.Header` marks rows that head a section: the heading of the section at the top stays there while its rows scroll under it, until the next one pushes it away (give it a background; headings are not chosen, focused or typed to, and the keys pass over them). `ListState.Reorder` lets the user drag rows to another place, the chosen ones when the row dragged is one of them, and calls it with the rows and the row they go before; the list shows where they would go and scrolls near its edges, and Escape lets go. `ListState.RowWidth` makes the rows at least that wide: where they are wider than the list it scrolls sideways too (the horizontal wheel, or the wheel with Shift), and where they are not they grow to its width, as the columns of a table do; a header above the list follows the rows with `box.ScrollWith(&state)` on its content: give it the rows' width, and put it in a container of the header's height that clips. `ui.State[T](c, "open")` is an element's own small state (whether its menu is open), found by its name in its container and kept while the container is declared. `ui.Memo(c, *row, fn)` copies the part `fn` declares from the last paint while that value compares equal, declaring it again when it is hovered, focused, animated or resized; see Cost below. + + +### Text fields and custom controls + +`ui.TextArea(c, &m.notes, label, placeholder)` is a field of several rows. A control of your own (a terminal, an editor, a canvas the user draws on) is `ui.Control(c, label, &m.handlers)`: an empty, focusable element you paint with `Draw`, whose `Handlers` receive its keys, presses, wheel and, for `gfx.RoleTextField` or `gfx.RoleTerminal`, the platform's typing and input methods through `Text`; no identity is declared and the window dispatches nothing. A control with several interactive parts (the stars of a rating, the nodes of a graph) declares them as it draws, with `Handlers.Parts().At(i)` as their identities: a key, a press or the wheel on a part reaches the same `Handlers` with the part as the event's `Target`, and a printable key typed while the control has the focus reaches `Key` with its `Text`. + +### Focus groups and control bases + +`.FocusGroup(ui.FocusHorizontal)` on a row or column makes the controls inside one Tab stop with the arrow keys between them, as a toolbar's are; `.FocusOrder` gives a custom grid the row and column order it needs. The controls without their look are `ui.ButtonBase`, `CheckboxBase`, `SwitchBase`, `ToggleBase`, `RadioBase`, `TabBase`, `SliderBase`, `SelectBase` and `TextFieldBase`: bound and keyed like their dressed forms, for a design of your own. + +### Field focus and tooltips + +`ui.TextField(...).AutoFocus()` takes the focus as the field appears (once: the user's choice stays), and `.Submitted()` is true in the paint that delivers Enter in it; `.Secure()` makes it a password field. `.Tooltip("Delete")` gives a control the tip shown while the pointer rests on it, which is also its description. + +### Menus, search fields and context menus + +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` is shadcn's dropdown menu of actions: `menu.Item("Rename").Clicked()` reads one as a button is read, the arrows move between items, typing a letter goes to the item it begins, and choosing one closes the menu. `menu.Sub("Move to", func(to *ui.MenuItems) { ... })` is an item with a submenu beside it, which opens as the pointer rests on the item, on a click, or on Right, Enter or Space with its first item focused; Left goes back, Escape closes every menu, and choosing in it closes them all. `menu.Item("Model").Description("What answers")` adds a second line under an item, `menu.WidthRange(140, 320)` bounds the menu's width, `menu.Above()` opens it over the anchor, for a trigger along the bottom of a panel, and `menu.Beside()` to its right, for a row of a list or popup whose menu should leave the rows under it in sight. `ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` takes Select's arguments and a label, and filters the choices as the user types into it, with the platform's input methods. `.Clearable()` gives it a button that clears the choice, `.Empty("No zone matches")` is what its list says when nothing matches, and `.Creatable("")` offers what was typed as a new choice ("Create dev"), which `.Created()` reports for the application to add. A Button takes an icon before its label with `.Icon(plus)`, or alone with `.IconOnly()`. `ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` opens the same items at the pointer on a secondary press of `row`, or under it on Shift+F10; items take an `.Icon`, the keycaps of a shortcut with `.Keys(ui.Primary, "c")` (shown only: the shortcut is a `Shortcut` where its action is), and `.Checked` or `.Chosen` to be a checkbox or a radio item. A search field is a TextField with `.Icon(search)` before its text and `.Action(cross, "Clear")`, a small button at its end that `.ActionClicked()` reads. + +### Drawers + +`ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)` slides a panel in from an edge, as shadcn's Sheet: with an empty title the body has the whole panel, and `NonModal` leaves the keyboard on the page behind it; `Swipe` adds a handle at its inner edge, and a drag on it moves the panel toward its edge, closing it when dragged past half its size or thrown, sliding it back otherwise. + +### Trees + +`ui.Tree(c, &m.tree, n, label, content)` is a List of the visible rows of the application's tree, with `TreeState.Node` describing each (its depth, whether it is a branch and open); the arrows move, open and close, and the tree reports `Toggled()` and `Chosen()` for the application to act on. Typing the start of a row's name moves to it. With `TreeState.CanDrop` set, rows can be dragged onto one another (before, into or after a row, as `CanDrop` allows), and `Dropped()` reports the drop; move the rows in `c.After`, since the paint reporting it is still declaring them. `state.RowID(i)` is the identity of visible row i (`DisclosureID(i)` its chevron's, and `ListState` has `RowID` too), for giving a row the focus or finding its hit. + +### Drag and drop + +Any other box can drag and drop with a `ui.DragState` kept in the model: `ui.Row(c).Hit(ui.ID(c), "Group").DragSource(&m.drag)` makes a box a source, and `.DropTarget(&m.drag, m.accepts, m.drops)` makes one a target. The page follows the press, the short distance that makes it a drag, and the target under the pointer; `m.drag.Dragging()`, `Source()`, `Target()` and `At()` paint the gesture, `accept(source, target)` decides, `drop(source, target)` runs on release, and Escape lets go. A press that does not move is still a click. Inside a `ui.Control`'s `Draw`, a card of a custom grid is declared as a part with `d.Canvas.Hit(part, r)` and becomes a source and target of the same state with `d.DragSource(&m.drag, part, r)` and `d.DropTarget(&m.drag, part, r, accept, drop)`, so one control carries many draggable parts with stable identities; a target part needs no Hit. Keep the callbacks in the model and declare the boxes every paint, not in a `Memo`. + +### Toasts + +Toasts are a `ui.Toaster` kept in the model: `m.toaster.Show("Saved", "", ui.ToastSuccess)` puts one up, and `ui.Toasts(c, &m.toaster)`, declared once and last, paints them and takes each down after five seconds, asking for one frame when the next is due and none while nothing is up. `ShowAction(title, description, kind, "Undo")` gives one a button, whose press `m.toaster.Acted()` reports after `Toasts` and which takes the toast down; a `ui.ToastLoading` toast spins and stays until `m.toaster.Done(id, "Uploaded", "", ui.ToastSuccess)` replaces it; `Toaster.Position` puts the stack in another corner or centered (`ui.ToastTopCenter`). + +### Shortcuts + +A keyboard shortcut is declared where it acts, as a click is read: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }` is the page's (Primary is Command on macOS, Control elsewhere), and `list.Shortcut(0, "delete")` on a container or control acts only while the focus is in it, the innermost of nested ones winning. A chord without Primary, Ctrl or Alt is left to a field or terminal being typed in, and while a Popover, Modal, Menu, or Select or Combobox list is open the page's own shortcuts wait. + +### Lists + +`ui.List(c, &state, n, row)` declares only the rows on screen of a list of `n`, each as tall as its content, and scrolls it; `row` gets a `ui.ListRow` whose `Element` is the row's container to style and whose `C` declares what is in it, and `ListState.Key` names rows by an item's ID. A click chooses a row and the arrows, Home, End and Page Up and Down move between them, with the choice in `state.Selected()` and `state.Changed()` reporting that the user made one; Enter or a double click is `state.Submitted()`; `ListState.Label` makes typing the start of a row's text move to it. Set `ListState.Selection` to a `ui.Selection` to let the user choose several (Primary-click adds or removes a row, Shift extends, Primary+A chooses all). `ScrollTo`, `ScrollIntoView`, `ScrollToEnd`, `Visible` and `AtEnd` move and read the scroll position, and `box.ClickModifiers()` and `box.DoubleClicked()` say how a click on any element came. A row's `Element` is a Row, so an icon, a name and a size lie side by side. `ListState.Header` marks rows that head a section: the heading of the section at the top stays there while its rows scroll under it, until the next one pushes it away (give it a background; headings are not chosen, focused or typed to, and the keys pass over them). `ListState.Reorder` lets the user drag rows to another place, the chosen ones when the row dragged is one of them, and calls it with the rows and the row they go before; the list shows where they would go and scrolls near its edges, and Escape lets go. `ListState.RowWidth` makes the rows at least that wide: where they are wider than the list it scrolls sideways too (the horizontal wheel, or the wheel with Shift), and where they are not they grow to its width, as the columns of a table do; a header above the list follows the rows with `box.ScrollWith(&state)` on its content: give it the rows' width, and put it in a container of the header's height that clips. + +### Element state and memoization + +`ui.State[T](c, "open")` is an element's own small state (whether its menu is open), found by its name in its container and kept while the container is declared. `ui.Memo(c, *row, fn)` copies the part `fn` declares from the last paint while that value compares equal, declaring it again when it is hovered, focused, animated or resized; see Cost below. A settings struct can have its form written for it. Tag the fields and run `viva form` (from `//go:generate go tool viva form`): it writes `viva_form.go` with `func (v *Settings) Form(c ui.C) ui.Box`, plain page code with no reflection: @@ -255,19 +299,86 @@ ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: sidebar}).Childre }) ``` -## Mixing with hand-placed painting +## Tables -`ui.Slot(c)` reserves a rectangle for something you paint yourself, and `Box.Rect()` says where it ended up; paint it with a `Draw` callback or a `ui.Control` when it needs input. Use the page's canvas (`c.Canvas()`) and its rectangles when you need to paint below the page's declarations. +`ui.Table` is a virtualized table: it reads only the visible rows from a `ui.TableSource` (or a `ui.TableRows`, a `[][]string`), keeps a fixed header while its body scrolls, and reports what the user did. The data and its order stay in the application: the table paints the sort arrow, and the application sorts the source after `HeaderClicked`. -## Cost + +```go +// A table of servers: a fixed header, sortable columns, one selected row and a +// body that scrolls under the header when the window is short. +package main -Declaring, measuring, arranging and painting a page of about sixty elements takes about 8 microseconds and allocates nothing once the page has seen its largest page. Keep one `ui.Page` per window, in your state; the zero value of that page's config is ready. The function you give `Children` is called at once and never stored, so it costs nothing either. +import ( + "log" + "sort" -A single-line `Text` is not wrapped: a line that does not fit is clipped, and it shrinks before a fixed-size sibling does. Use `Paragraph` for text that should wrap. + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/ui" +) -## Starting a project +type model struct { + table ui.TableState + rows ui.TableRows +} + +func newModel() *model { + return &model{rows: ui.TableRows{ + {"web-01", "Running", "eu-west"}, + {"web-02", "Running", "us-east"}, + {"db-primary", "Degraded", "eu-west"}, + {"cache", "Stopped", "us-east"}, + }} +} -`viva init my-app` writes a runnable project: a window laid out with `ui`, a test that drives it without a window, `viva.toml`, and `AGENTS.md`, a one-page guide to layout, identities, clicks and tests that a coding assistant reads before it changes the UI. `viva dev .` then runs it with hot reload. +// page declares the table. A header click sorts the rows and a row click +// selects it; the table keeps the selection and the scroll position itself. +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + ui.Text(c, "Servers").FontSize(20).Bold() + table := ui.Table(c, &m.table, ui.TableSpec{ + Headers: []string{"Name", "State", "Region"}, + Sortable: []bool{true, true, true}, + Source: &m.rows, + Striped: true, + Columns: []components.TableColumn{{Width: 200}, {Width: 120}, {}}, + }) + if row, ok := table.RowClicked(); ok { + m.table.Select(row) + } + if column, ok := table.HeaderClicked(); ok { + m.table.SortBy(column) + m.sortRows() + } + if row := m.table.Selected(); row >= 0 { + ui.Text(c, "Selected: "+m.rows[row][0]).Muted() + } + }) +} + +// sortRows orders the rows by the column the table reports as sorted. The table +// paints the arrow; the application owns the data and its order. +func (m *model) sortRows() { + column, descending, ok := m.table.Sort() + if !ok { + return + } + sort.SliceStable(m.rows, func(i, j int) bool { + less := m.rows[i][column] < m.rows[j][column] + if descending { + return !less + } + return less + }) +} + +func main() { + if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, newModel().page); err != nil { + log.Fatal(err) + } +} +``` ```go diff --git a/website/content/guides/zh/build-and-package.md b/website/content/guides/zh/build-and-package.md index eb3b3253e..d1b2c43f5 100644 --- a/website/content/guides/zh/build-and-package.md +++ b/website/content/guides/zh/build-and-package.md @@ -41,7 +41,7 @@ viva help package # 某个命令的参数 ```sh go tool viva add --out ./components button -go get -tool github.com/vivaui/viva/cmd/viva@v0.1.3 # 给已有项目锁定 +go get -tool github.com/vivaui/viva/cmd/viva@v0.6.5 # 给已有项目锁定 ``` `PATH` 里的命令和项目版本不一致时,`viva doctor` 和 `viva add` 会提醒。 diff --git a/website/content/guides/zh/coding-agents.md b/website/content/guides/zh/coding-agents.md index 74906631a..f31f9d31a 100644 --- a/website/content/guides/zh/coding-agents.md +++ b/website/content/guides/zh/coding-agents.md @@ -6,7 +6,7 @@ group: start skill: building-with-viva --- -Viva 自己绘制界面,只在被请求时重绘,也没有布局缓存,所以按网页或保留式工具包的写法来写,产出的代码会被评审拒绝。`building-with-viva` skill 是一份简短的说明,Claude Code、Codex 这类 AI 编程助手在改动 Viva 应用之前加载它。它只是一个 Markdown 文件,没有需要运行的代码。 +Viva 自己绘制界面,只在被请求时重绘,也没有布局缓存,所以按网页或保留式工具包的写法来写,产出的代码会被评审拒绝。`building-with-viva` skill 是一份简短的说明,Claude Code、Codex 这类 AI 编程助手在改动 Viva 应用之前加载它。它是两个 Markdown 文件,没有需要运行的代码:一份说明和一份配方速查。 ## skill 涵盖什么 @@ -26,6 +26,8 @@ Viva 自己绘制界面,只在被请求时重绘,也没有布局缓存,所 mkdir -p .claude/skills/building-with-viva curl -fsSL https://vivaui.dev/skills/building-with-viva/SKILL.md \ -o .claude/skills/building-with-viva/SKILL.md +curl -fsSL https://vivaui.dev/skills/building-with-viva/recipes.md \ + -o .claude/skills/building-with-viva/recipes.md ``` 在 Viva 自己的仓库副本中,请改为复制或软链 `docs/skills/building-with-viva`。在那里,仓库的 `AGENTS.md` 优先于这个 skill。 diff --git a/website/content/guides/zh/declarative-layout.md b/website/content/guides/zh/declarative-layout.md index cfa4ce715..78cea404c 100644 --- a/website/content/guides/zh/declarative-layout.md +++ b/website/content/guides/zh/declarative-layout.md @@ -59,7 +59,7 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page) `ui.Choice` 和 `ui.Tabs` 各占一个 Tab 停靠点:左右方向键(垂直的标签页用上下键)移动到下一个可用选项并选中它,到头会回绕;Home 和 End 去第一个和最后一个。 -点击会在递送它的那一遍绘制里翻转 `m.sync`:在控件第一次被询问(`Clicked`、`Changed`)时写入,没有被询问就在页面结束时写入;在那之前读 `m.sync` 看到的还是点击前的值,所以写在控件之后的 `Disabled` 依然有效。`Choice`、`Tabs` 和 `Select` 接受任意可比较类型的值,并在声明时就写入:要禁用它们,用 `if` 包起来,而不是在后面写 `Disabled`。`TextField` 不需要 `Config.TextInput`:页面的 `Config` 把它声明过的每个输入框的编辑器交给平台,其他获得焦点的输入框交给配置里原有的提供者。`Popover` 和 `Modal` 在一个 `*bool` 为真时打开,被关闭时把它设为 false(见[对话框、菜单和弹出层](/zh/docs/overlays/))。`Box.NativeView` 把一个元素的区域交给系统网页引擎的页面。 +点击会在递送它的那一遍绘制里翻转 `m.sync`:在控件第一次被询问(`Clicked`、`Changed`)时写入,没有被询问就在页面结束时写入;在那之前读 `m.sync` 看到的还是点击前的值,所以写在控件之后的 `Disabled` 依然有效。`Choice`、`Tabs` 和 `Select` 接受任意可比较类型的值,并在声明时就写入:要禁用它们,用 `if` 包起来,而不是在后面写 `Disabled`。`Tabs` 和 `Select` 也会让链式 `Disabled` 对输入生效,`Choice` 不会;可靠的形式始终是 `if`。`TextField` 不需要 `Config.TextInput`:页面的 `Config` 把它声明过的每个输入框的编辑器交给平台,其他获得焦点的输入框交给配置里原有的提供者。`Popover` 和 `Modal` 在一个 `*bool` 为真时打开,被关闭时把它设为 false(见[对话框、菜单和弹出层](/zh/docs/overlays/))。`Box.NativeView` 把一个元素的区域交给系统网页引擎的页面。 元素按位置命名:它的种类,以及它在所在容器里同类元素中的序号。另有三条细化: @@ -67,7 +67,52 @@ ui.Run(app.Config{Title: "Settings", Width: 480, Height: 320}, m.page) - 在 `c.Key(item.ID)` 或 `c.KeyInt(id)` 里,元素只在这一行内部编号,所以行出现、消失或移动时,行里的按钮跟着这一行走。行消失两遍绘制之后,它的 Key 才会被复用。行里有 `Button` 的循环要给行加 Key;没加时 `viva vet` 会报告。 - 用户按住一个按钮(按下它,或它有焦点)时,如果某一遍绘制里另一个按钮占了它的位置,这次按下不会递送,焦点也会被放弃。 -`ui.TextArea(c, &m.notes, label, placeholder)` 是多行输入框。自己写的控件(终端、编辑器、可以画画的画布)用 `ui.Control(c, label, &m.handlers)`:它是一个可获得焦点的空元素,用 `Draw` 绘制,`Handlers` 接收它的按键、指针和滚轮;角色为 `RoleTextField` 或 `RoleTerminal` 时,还通过 `Text` 接收平台的打字和输入法。不用声明任何标识,窗口也不用分派任何事件。有多个可交互部分的控件(评分的几颗星、图的节点)在绘制时声明它们,用 `Handlers.Parts().At(i)` 作标识:落在某个部分上的按键、点击和滚轮,会连同该部分作为事件的 `Target` 交给同一个 `Handlers`;控件有焦点时打出的可打印字符,以 `Text` 交给 `Key`。在行或列上写 `.FocusGroup(ui.FocusHorizontal)`,里面的控件就成为一个 Tab 停靠点,方向键在它们之间移动,像工具栏一样;`.FocusOrder` 可以给自定义网格按行列移动。没有外观的控件有 `ui.ButtonBase`、`CheckboxBase`、`SwitchBase`、`ToggleBase`、`RadioBase`、`TabBase`、`SliderBase`、`SelectBase` 和 `TextFieldBase`:绑定和命名方式与带外观的版本相同,用来做你自己的设计。`ui.TextField(...).AutoFocus()` 在输入框出现时把焦点给它(只给一次,用户移开后不抢回),`.Submitted()` 在递送回车的那一遍绘制里为真;`.Secure()` 让它成为密码字段。`.Tooltip("Delete")` 给控件一个指针停留时显示的提示,它同时也是控件的描述。`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。`ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)` 从窗口一边滑入一个面板,即 shadcn 的 Sheet:标题为空时整个面板都给 body,`NonModal` 让键盘留在背后的页面;`Swipe` 在面板内侧边缘加一个把手,拖动它面板随之移向边缘,拖过一半或快速甩出时关闭,否则滑回原位。`ui.Tree(c, &m.tree, n, label, content)` 是应用自己的树里可见行组成的 List,由 `TreeState.Node` 描述每一行(深度、是否为分支、是否展开);方向键移动、展开和折叠,树报告 `Toggled()` 和 `Chosen()` 由应用处理。输入行名的开头会跳到那一行。设置 `TreeState.CanDrop` 后,行可以拖到另一行的前面、里面或后面(由 `CanDrop` 决定接受哪些),`Dropped()` 报告放下的那一次;移动行要放在 `c.After` 里做,因为报告它的那次绘制还在声明这些行。`state.RowID(i)` 是第 i 个可见行的身份(`DisclosureID(i)` 是它箭头的身份,`ListState` 也有 `RowID`),用来给某一行焦点或找到它的 hit。其他元素可以用模型里的 `ui.DragState` 拖放:`ui.Row(c).Hit(ui.ID(c), "Group").DragSource(&m.drag)` 把元素声明为源,`.DropTarget(&m.drag, m.accepts, m.drops)` 把它声明为目标。页面负责按下、把按下变成拖拽的短距离,以及指针下的目标;`m.drag.Dragging()`、`Source()`、`Target()` 和 `At()` 用来绘制拖拽,`accept(source, target)` 决定接不接受,`drop(source, target)` 在松开时执行,Escape 放弃。没有移动的按下仍然是点击。在 `ui.Control` 的 `Draw` 里,自定义网格的卡片用 `d.Canvas.Hit(part, r)` 声明为 part,再用 `d.DragSource(&m.drag, part, r)` 和 `d.DropTarget(&m.drag, part, r, accept, drop)` 声明为同一个状态的源和目标,一个控件就能承载多个身份稳定、可拖拽的 part;目标 part 不需要 Hit。回调保存在模型里,元素每遍绘制都重新声明,不要放在 `Memo` 里。Toast 是模型里的一个 `ui.Toaster`:`m.toaster.Show("Saved", "", ui.ToastSuccess)` 显示一条,`ui.Toasts(c, &m.toaster)` 在页面里声明一次、放在最后,负责绘制并在五秒后收起;它只在下一条到期时请求一帧,没有 toast 时不做任何调度。`ShowAction(title, description, kind, "Undo")` 给 toast 加一个按钮,按下后 toast 收起,在 `Toasts` 之后用 `m.toaster.Acted()` 读取;`ui.ToastLoading` 的 toast 显示转圈且不会自动收起,直到 `m.toaster.Done(id, "Uploaded", "", ui.ToastSuccess)` 替换它;`Toaster.Position` 把整组 toast 放到别的角落或居中(`ui.ToastTopCenter`)。键盘快捷键在它起作用的地方声明,和读取点击一样:`if ui.Shortcut(c, ui.Primary, "s") { m.save() }` 是整个页面的快捷键(Primary 在 macOS 上是 Command,其他平台是 Control);在容器或控件上用 `list.Shortcut(0, "delete")`,只在焦点位于它之内时生效,嵌套时最内层的生效。不带 Primary、Ctrl 或 Alt 的按键留给正在输入的输入框或终端;Popover、Modal、Menu 或 Select、Combobox 列表打开时,页面级快捷键不生效。`ui.List(c, &state, n, row)` 只声明 `n` 行列表里显示在屏幕上的行,每行高度由内容决定,并负责滚动;`row` 得到一个 `ui.ListRow`,其中 `Element` 是这一行的容器(用来设置样式),`C` 用来声明行里的内容,`ListState.Key` 按条目 ID 为行命名。点击会选中一行,方向键、Home、End、Page Up 和 Page Down 在行之间移动,选中的行在 `state.Selected()` 里,`state.Changed()` 报告用户做了选择;回车或双击是 `state.Submitted()`;设置 `ListState.Label` 后,输入行文字的开头会跳到那一行。把 `ListState.Selection` 设为一个 `ui.Selection` 就能让用户选多行(Primary 加点击增减一行,Shift 扩展,Primary+A 全选)。`ScrollTo`、`ScrollIntoView`、`ScrollToEnd`、`Visible` 和 `AtEnd` 移动并读取滚动位置,`box.ClickModifiers()` 和 `box.DoubleClicked()` 说明任何元素上的点击是怎么发生的。行的 `Element` 是一个 Row,所以图标、名称和大小并排放。`ListState.Header` 标出作为分组标题的行:处在顶部的那一组的标题会留在顶部,它的行从下面滚过,直到下一个标题把它顶走(给它设个背景;标题不会被选中、聚焦,也不参与输入跳转,按键会跳过它)。`ListState.Reorder` 让用户把行拖到别的位置,拖动的行被选中时拖走所有选中的行,并用这些行和它们要放到哪一行之前来调用它;列表会显示它们要去的位置,靠近边缘时自动滚动,按 Escape 放弃拖动。`ListState.RowWidth` 让行至少这么宽:行比列表宽时列表也能横向滚动(水平滚轮,或按住 Shift 用滚轮),不比列表宽时行会撑满列表,像表格的列那样;列表上方的表头用 `box.ScrollWith(&state)` 加在它的内容上,随行一起移动:给它和行一样的宽度,放在定高、会裁剪的容器里。`ui.State[T](c, "open")` 是元素自己的小状态(比如菜单是否打开),在它的容器里按名字查找,容器被声明期间一直保留。`ui.Memo(c, *row, fn)` 在那个值比较相等时从上一遍绘制复制 `fn` 声明的部分,在它被悬停、获得焦点、处于动画中或改变大小时重新声明;见下面的开销。 +`ui.TextArea(c, &m.notes, label, placeholder)` 是多行输入框。 + + +### 输入框与自定义控件 + +自己写的控件(终端、编辑器、可以画画的画布)用 `ui.Control(c, label, &m.handlers)`:它是一个可获得焦点的空元素,用 `Draw` 绘制,`Handlers` 接收它的按键、指针和滚轮;角色为 `gfx.RoleTextField` 或 `gfx.RoleTerminal` 时,还通过 `Text` 接收平台的打字和输入法。不用声明任何标识,窗口也不用分派任何事件。有多个可交互部分的控件(评分的几颗星、图的节点)在绘制时声明它们,用 `Handlers.Parts().At(i)` 作标识:落在某个部分上的按键、点击和滚轮,会连同该部分作为事件的 `Target` 交给同一个 `Handlers`;控件有焦点时打出的可打印字符,以 `Text` 交给 `Key`。 + +### 焦点组与无外观控件 + +在行或列上写 `.FocusGroup(ui.FocusHorizontal)`,里面的控件就成为一个 Tab 停靠点,方向键在它们之间移动,像工具栏一样;`.FocusOrder` 可以给自定义网格按行列移动。没有外观的控件有 `ui.ButtonBase`、`CheckboxBase`、`SwitchBase`、`ToggleBase`、`RadioBase`、`TabBase`、`SliderBase`、`SelectBase` 和 `TextFieldBase`:绑定和命名方式与带外观的版本相同,用来做你自己的设计。 + +### 输入框焦点与提示 + +`ui.TextField(...).AutoFocus()` 在输入框出现时把焦点给它(只给一次,用户移开后不抢回),`.Submitted()` 在递送回车的那一遍绘制里为真;`.Secure()` 让它成为密码字段。`.Tooltip("Delete")` 给控件一个指针停留时显示的提示,它同时也是控件的描述。 + +### 菜单、搜索框与右键菜单 + +`ui.Menu(c, anchor, &m.menu, func(menu *ui.MenuItems) { ... })` 是 shadcn 的下拉菜单:像读按钮一样用 `menu.Item("Rename").Clicked()` 读取一项,方向键在各项之间移动,输入字母会跳到以它开头的项,选中一项后菜单关闭。`menu.Sub("Move to", func(to *ui.MenuItems) { ... })` 是一个旁边带子菜单的项:指针在它上面停留、点击它,或按 Right、Enter、Space 时打开(键盘打开时焦点落在子菜单第一项);Left 返回,Escape 关闭所有菜单,在子菜单里选中一项也会全部关闭。 `menu.Item("Model").Description("What answers")` 给项加一行说明;`menu.WidthRange(140, 320)` 限制菜单宽度,`menu.Above()` 让菜单在锚点上方展开(锚点在面板底部时),`menu.Beside()` 让菜单在锚点右侧展开(列表或弹出层里的行,菜单不遮住下面的行)。`ui.Combobox(c, &m.zone, zones, Zone.String, "Time zone")` 接受 Select 的参数再加一个标签,用户输入时(支持平台输入法)筛选选项。`.Clearable()` 加一个清除选择的按钮,`.Empty("No zone matches")` 是没有匹配项时列表显示的文字,`.Creatable("")` 把输入的内容作为新选项提供("Create dev"),由 `.Created()` 报告,应用自己把它加进选项。Button 用 `.Icon(plus)` 在标签前加图标,加 `.IconOnly()` 则只显示图标。`ui.ContextMenu(c, row, func(menu *ui.MenuItems) { ... })` 在 `row` 上按下副键时于指针处打开同样的菜单项,按 Shift+F10 时在它下方打开;菜单项可以加 `.Icon`、用 `.Keys(ui.Primary, "c")` 显示快捷键键帽(只显示,快捷键本身是动作所在处的一个 `Shortcut`),用 `.Checked` 或 `.Chosen` 成为复选或单选项。搜索框是带 `.Icon(search)`(文字前的图标)和 `.Action(cross, "Clear")`(末尾的小按钮,用 `.ActionClicked()` 读取)的 TextField。 + +### 抽屉 + +`ui.Drawer(c, &m.open, "Host", ui.DrawerSpec{Side: ui.DrawerLeft, Size: 320}, body, footer)` 从窗口一边滑入一个面板,即 shadcn 的 Sheet:标题为空时整个面板都给 body,`NonModal` 让键盘留在背后的页面;`Swipe` 在面板内侧边缘加一个把手,拖动它面板随之移向边缘,拖过一半或快速甩出时关闭,否则滑回原位。 + +### 树 + +`ui.Tree(c, &m.tree, n, label, content)` 是应用自己的树里可见行组成的 List,由 `TreeState.Node` 描述每一行(深度、是否为分支、是否展开);方向键移动、展开和折叠,树报告 `Toggled()` 和 `Chosen()` 由应用处理。输入行名的开头会跳到那一行。设置 `TreeState.CanDrop` 后,行可以拖到另一行的前面、里面或后面(由 `CanDrop` 决定接受哪些),`Dropped()` 报告放下的那一次;移动行要放在 `c.After` 里做,因为报告它的那次绘制还在声明这些行。`state.RowID(i)` 是第 i 个可见行的身份(`DisclosureID(i)` 是它箭头的身份,`ListState` 也有 `RowID`),用来给某一行焦点或找到它的 hit。 + +### 拖放 + +其他元素可以用模型里的 `ui.DragState` 拖放:`ui.Row(c).Hit(ui.ID(c), "Group").DragSource(&m.drag)` 把元素声明为源,`.DropTarget(&m.drag, m.accepts, m.drops)` 把它声明为目标。页面负责按下、把按下变成拖拽的短距离,以及指针下的目标;`m.drag.Dragging()`、`Source()`、`Target()` 和 `At()` 用来绘制拖拽,`accept(source, target)` 决定接不接受,`drop(source, target)` 在松开时执行,Escape 放弃。没有移动的按下仍然是点击。在 `ui.Control` 的 `Draw` 里,自定义网格的卡片用 `d.Canvas.Hit(part, r)` 声明为 part,再用 `d.DragSource(&m.drag, part, r)` 和 `d.DropTarget(&m.drag, part, r, accept, drop)` 声明为同一个状态的源和目标,一个控件就能承载多个身份稳定、可拖拽的 part;目标 part 不需要 Hit。回调保存在模型里,元素每遍绘制都重新声明,不要放在 `Memo` 里。 + +### Toast + +Toast 是模型里的一个 `ui.Toaster`:`m.toaster.Show("Saved", "", ui.ToastSuccess)` 显示一条,`ui.Toasts(c, &m.toaster)` 在页面里声明一次、放在最后,负责绘制并在五秒后收起;它只在下一条到期时请求一帧,没有 toast 时不做任何调度。`ShowAction(title, description, kind, "Undo")` 给 toast 加一个按钮,按下后 toast 收起,在 `Toasts` 之后用 `m.toaster.Acted()` 读取;`ui.ToastLoading` 的 toast 显示转圈且不会自动收起,直到 `m.toaster.Done(id, "Uploaded", "", ui.ToastSuccess)` 替换它;`Toaster.Position` 把整组 toast 放到别的角落或居中(`ui.ToastTopCenter`)。 + +### 快捷键 + +键盘快捷键在它起作用的地方声明,和读取点击一样:`if ui.Shortcut(c, ui.Primary, "s") { m.save() }` 是整个页面的快捷键(Primary 在 macOS 上是 Command,其他平台是 Control);在容器或控件上用 `list.Shortcut(0, "delete")`,只在焦点位于它之内时生效,嵌套时最内层的生效。不带 Primary、Ctrl 或 Alt 的按键留给正在输入的输入框或终端;Popover、Modal、Menu 或 Select、Combobox 列表打开时,页面级快捷键不生效。 + +### 列表 + +`ui.List(c, &state, n, row)` 只声明 `n` 行列表里显示在屏幕上的行,每行高度由内容决定,并负责滚动;`row` 得到一个 `ui.ListRow`,其中 `Element` 是这一行的容器(用来设置样式),`C` 用来声明行里的内容,`ListState.Key` 按条目 ID 为行命名。点击会选中一行,方向键、Home、End、Page Up 和 Page Down 在行之间移动,选中的行在 `state.Selected()` 里,`state.Changed()` 报告用户做了选择;回车或双击是 `state.Submitted()`;设置 `ListState.Label` 后,输入行文字的开头会跳到那一行。把 `ListState.Selection` 设为一个 `ui.Selection` 就能让用户选多行(Primary 加点击增减一行,Shift 扩展,Primary+A 全选)。`ScrollTo`、`ScrollIntoView`、`ScrollToEnd`、`Visible` 和 `AtEnd` 移动并读取滚动位置,`box.ClickModifiers()` 和 `box.DoubleClicked()` 说明任何元素上的点击是怎么发生的。行的 `Element` 是一个 Row,所以图标、名称和大小并排放。`ListState.Header` 标出作为分组标题的行:处在顶部的那一组的标题会留在顶部,它的行从下面滚过,直到下一个标题把它顶走(给它设个背景;标题不会被选中、聚焦,也不参与输入跳转,按键会跳过它)。`ListState.Reorder` 让用户把行拖到别的位置,拖动的行被选中时拖走所有选中的行,并用这些行和它们要放到哪一行之前来调用它;列表会显示它们要去的位置,靠近边缘时自动滚动,按 Escape 放弃拖动。`ListState.RowWidth` 让行至少这么宽:行比列表宽时列表也能横向滚动(水平滚轮,或按住 Shift 用滚轮),不比列表宽时行会撑满列表,像表格的列那样;列表上方的表头用 `box.ScrollWith(&state)` 加在它的内容上,随行一起移动:给它和行一样的宽度,放在定高、会裁剪的容器里。 + +### 元素状态与缓存 + +`ui.State[T](c, "open")` 是元素自己的小状态(比如菜单是否打开),在它的容器里按名字查找,容器被声明期间一直保留。`ui.Memo(c, *row, fn)` 在那个值比较相等时从上一遍绘制复制 `fn` 声明的部分,在它被悬停、获得焦点、处于动画中或改变大小时重新声明;见下面的开销。 设置类结构体的表单可以自动生成。给字段加 tag,然后运行 `viva form`(写成 `//go:generate go tool viva form`):它生成 `viva_form.go`,里面是 `func (v *Settings) Form(c ui.C) ui.Box`,就是普通的页面代码,不用反射: @@ -255,19 +300,86 @@ ui.Overlay(c, ui.OverlaySpec{Band: ui.LayerPaneChrome, Bounds: sidebar}).Childre }) ``` -## 和手工绘制混用 +## 表格 -`ui.Slot(c)` 为你自己绘制的内容预留一块矩形,`Box.Rect()` 告诉你它最后落在哪里;用 `Draw` 回调画它,需要输入时用 `ui.Control`。需要页面声明之下的绘制时,用页面的画布(`c.Canvas()`)和它给出的矩形。 +`ui.Table` 是虚拟化表格:它只从 `ui.TableSource`(或 `ui.TableRows`,也就是 `[][]string`)读取可见的行,表体滚动时表头固定,并报告用户做了什么。数据和顺序都属于应用:表格只画排序箭头,应用在 `HeaderClicked` 之后自己排序数据源。 -## 开销 + +```go +// A table of servers: a fixed header, sortable columns, one selected row and a +// body that scrolls under the header when the window is short. +package main -声明、测量、排布并绘制一个约六十个元素的页面大约需要 8 微秒,页面见过最大页面之后不再分配内存。为每个窗口在你的状态里保存一个 `ui.Page`;它的配置零值即可使用。传给 `Children` 的函数立即调用且不会被保存,所以也没有开销。 +import ( + "log" + "sort" -单行 `Text` 不换行:放不下的行会被裁剪,并且先于固定尺寸的兄弟元素收缩。需要换行的文字用 `Paragraph`。 + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/ui" +) -## 创建项目 +type model struct { + table ui.TableState + rows ui.TableRows +} + +func newModel() *model { + return &model{rows: ui.TableRows{ + {"web-01", "Running", "eu-west"}, + {"web-02", "Running", "us-east"}, + {"db-primary", "Degraded", "eu-west"}, + {"cache", "Stopped", "us-east"}, + }} +} -`viva init my-app` 会写出一个能直接运行的项目:用 `ui` 布局的窗口、无需窗口即可驱动它的测试、`viva.toml`,以及 `AGENTS.md`,一页纸的布局、标识、点击和测试指南,供编码助手在修改界面前阅读。之后 `viva dev .` 以热重载方式运行。 +// page declares the table. A header click sorts the rows and a row click +// selects it; the table keeps the selection and the scroll position itself. +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + ui.Text(c, "Servers").FontSize(20).Bold() + table := ui.Table(c, &m.table, ui.TableSpec{ + Headers: []string{"Name", "State", "Region"}, + Sortable: []bool{true, true, true}, + Source: &m.rows, + Striped: true, + Columns: []components.TableColumn{{Width: 200}, {Width: 120}, {}}, + }) + if row, ok := table.RowClicked(); ok { + m.table.Select(row) + } + if column, ok := table.HeaderClicked(); ok { + m.table.SortBy(column) + m.sortRows() + } + if row := m.table.Selected(); row >= 0 { + ui.Text(c, "Selected: "+m.rows[row][0]).Muted() + } + }) +} + +// sortRows orders the rows by the column the table reports as sorted. The table +// paints the arrow; the application owns the data and its order. +func (m *model) sortRows() { + column, descending, ok := m.table.Sort() + if !ok { + return + } + sort.SliceStable(m.rows, func(i, j int) bool { + less := m.rows[i][column] < m.rows[j][column] + if descending { + return !less + } + return less + }) +} + +func main() { + if err := ui.Run(app.Config{Title: "Servers", Width: 720, Height: 480}, newModel().page); err != nil { + log.Fatal(err) + } +} +``` ```go diff --git a/website/site.test.mjs b/website/site.test.mjs index 46ca32196..9469fe17a 100644 --- a/website/site.test.mjs +++ b/website/site.test.mjs @@ -266,6 +266,13 @@ const structuredData = html => { return JSON.parse(block)['@graph']; }; +test('the raw skill files are served so the install command can fetch them', () => { + for (const file of ['SKILL.md', 'recipes.md']) { + const body = readFileSync(new URL(`skills/building-with-viva/${file}`, output), 'utf8'); + assert.ok(body.length > 100, `${file} is empty`); + } +}); + test('structured data names the product on the home page and each guide', () => { for (const locale of ['zh', 'en']) { const home = structuredData(readPage(`${locale}/`)); @@ -352,6 +359,8 @@ test('the crawler files describe the site that was built', () => { for (const slug of guideSlugs) assert.ok(llms.includes(`https://vivaui.dev/en/docs/${slug}/`), `llms.txt lacks ${slug}`); assert.ok(llms.includes('https://vivaui.dev/en/components/') && llms.includes('https://vivaui.dev/en/api/'), 'llms.txt lacks the reference indexes'); assert.ok(llms.includes('https://vivaui.dev/en/showcase/'), 'llms.txt lacks the showcase'); + assert.ok(llms.includes('https://vivaui.dev/skills/building-with-viva/SKILL.md'), 'llms.txt lacks the agent skill'); + assert.ok(llms.includes('https://vivaui.dev/skills/building-with-viva/recipes.md'), 'llms.txt lacks the recipe cheat sheet'); assert.ok(!llms.includes('/en/ui/button/'), 'llms.txt lists every component page instead of the catalog'); const headers = readFileSync(new URL('_headers', output), 'utf8'); diff --git a/website/src/lib/site.test.ts b/website/src/lib/site.test.ts index 8a181e0c6..2be1c60d1 100644 --- a/website/src/lib/site.test.ts +++ b/website/src/lib/site.test.ts @@ -4,7 +4,7 @@ import test from 'node:test'; import { site } from './site.ts'; import { home } from './home.ts'; import { showcase } from './showcase.ts'; -import { skillNames, skillPath } from './skills.ts'; +import { skillFiles, skillNames, skillPath } from './skills.ts'; const guides = new URL('../../content/guides/', import.meta.url); const slugs = (locale: string) => readdirSync(new URL(`${locale}/`, guides)).filter(name => name.endsWith('.md')).map(name => name.slice(0, -3)).sort(); @@ -134,16 +134,20 @@ test('guides link only within their own language', () => { } }); -test('every skill is named like its directory and the coding-agent guide installs it from the path the site serves', () => { +test('every skill is named like its directory and the coding-agent guide installs every file it ships', () => { const names = skillNames(); assert.ok(names.length >= 1); for (const name of names) { const text = readFileSync(new URL(`../../../docs/skills/${name}/SKILL.md`, import.meta.url), 'utf8'); assert.match(text, new RegExp(`^---\\nname: ${name}\\n`), `${name}: front matter name`); + const files = skillFiles(name); + assert.ok(files.includes('SKILL.md'), `${name}: no SKILL.md`); for (const locale of ['zh', 'en']) { const guide = read(locale, 'coding-agents'); - assert.ok(guide.includes(`https://vivaui.dev${skillPath(name)}`), `${locale}: install URL for ${name}`); - assert.ok(guide.includes(`.claude/skills/${name}/SKILL.md`), `${locale}: install target for ${name}`); + for (const file of files) { + assert.ok(guide.includes(`https://vivaui.dev${skillPath(name, file)}`), `${locale}: install URL for ${name}/${file}`); + assert.ok(guide.includes(`.claude/skills/${name}/${file}`), `${locale}: install target for ${name}/${file}`); + } } } }); diff --git a/website/src/lib/skills.ts b/website/src/lib/skills.ts index ccf908236..8b0832e82 100644 --- a/website/src/lib/skills.ts +++ b/website/src/lib/skills.ts @@ -6,14 +6,29 @@ import { resolve } from 'node:path'; // could drift from it. const root = () => resolve(process.cwd(), '../docs/skills'); -export const skillPath = (name: string): string => `/skills/${name}/SKILL.md`; +// skillPath is where a skill file is served; file defaults to the briefing. +export const skillPath = (name: string, file = 'SKILL.md'): string => `/skills/${name}/${file}`; export function skillNames(): string[] { return readdirSync(root(), { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name).sort(); } +// skillFiles are the Markdown files a skill ships: SKILL.md and the pages it +// links to, such as recipes.md. The install step downloads all of them. +export function skillFiles(name: string): string[] { + return readdirSync(resolve(root(), name), { withFileTypes: true }) + .filter(entry => entry.isFile() && entry.name.endsWith('.md')) + .map(entry => entry.name) + .sort(); +} + +export function readSkillFile(name: string, file: string): string { + if (!skillFiles(name).includes(file)) throw new Error(`skill ${name} has no ${file}`); + return readFileSync(resolve(root(), name, file), 'utf8'); +} + export function readSkill(name: string): string { - return readFileSync(resolve(root(), name, 'SKILL.md'), 'utf8'); + return readSkillFile(name, 'SKILL.md'); } // A skill file opens with its own title, and the guide that shows it already has diff --git a/website/src/pages/skills/[name]/SKILL.md.ts b/website/src/pages/skills/[name]/SKILL.md.ts deleted file mode 100644 index 810d1f914..000000000 --- a/website/src/pages/skills/[name]/SKILL.md.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { APIRoute } from 'astro'; -import { readSkill, skillNames } from '../../../lib/skills'; - -export function getStaticPaths() { - return skillNames().map(name => ({ params: { name } })); -} - -// The raw file, so `curl` can drop it into a project's skills directory. -export const GET: APIRoute = ({ params }) => - new Response(readSkill(params.name!), { headers: { 'content-type': 'text/markdown; charset=utf-8' } }); diff --git a/website/src/pages/skills/[name]/[file].md.ts b/website/src/pages/skills/[name]/[file].md.ts new file mode 100644 index 000000000..bc01750c6 --- /dev/null +++ b/website/src/pages/skills/[name]/[file].md.ts @@ -0,0 +1,11 @@ +import type { APIRoute } from 'astro'; +import { readSkillFile, skillFiles, skillNames } from '../../../lib/skills'; + +export function getStaticPaths() { + return skillNames().flatMap(name => skillFiles(name).map(file => ({ params: { name, file: file.slice(0, -3) } }))); +} + +// The raw file, so `curl` can drop it into a project's skills directory. The +// route keeps /skills//SKILL.md and adds the pages beside it. +export const GET: APIRoute = ({ params }) => + new Response(readSkillFile(params.name!, `${params.file}.md`), { headers: { 'content-type': 'text/markdown; charset=utf-8' } }); From bd68f9ee30fddc27c7335a6191d2442717ee5151 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 09:21:46 +0800 Subject: [PATCH 05/12] fix(winpkg): replace loaded native files during install EnsureClosed only moved the program image aside. Native files the program loads at runtime, such as conpty.dll, stayed locked and File failed on them: a GUI install showed "cannot open file for writing" and a silent install skipped the file without updating it. Apply the same delete-then-rename-aside treatment before each extra file, clean the moved copies on the next install, and mark locked extra files for reboot removal when uninstalling. --- tools/winpkg/nsis.go | 38 ++++++++++++++++++++++++++++++++++++- tools/winpkg/winpkg_test.go | 37 ++++++++++++++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 3 deletions(-) diff --git a/tools/winpkg/nsis.go b/tools/winpkg/nsis.go index 8ea370e03..9357e0fbd 100644 --- a/tools/winpkg/nsis.go +++ b/tools/winpkg/nsis.go @@ -291,6 +291,35 @@ func (script Script) Generate() ([]byte, error) { line(`!insertmacro EnsureClosed "un."`) line("") + // A native file the program loads at runtime is held open like the program + // image itself. Windows allows renaming it aside but not deleting or + // overwriting it, so every extra file gets the same treatment before File + // writes over it. The caller pushes the installed path. + line(`Function EnsureFileWritable`) + line(` Exch $0`) + line(` Push $1`) + line(` retry_file:`) + line(` ClearErrors`) + line(` Delete "$0"`) + line(` ${IfNot} ${Errors}`) + line(` Pop $1`) + line(` Pop $0`) + line(` Return`) + line(` ${EndIf}`) + line(` ; A loaded image can be renamed but not deleted, so move it aside.`) + line(` System::Call 'kernel32::GetTickCount()i .r1'`) + line(` ClearErrors`) + line(` Rename "$0" "$0.$1.old"`) + line(` ${IfNot} ${Errors}`) + line(` Pop $1`) + line(` Pop $0`) + line(` Return`) + line(` ${EndIf}`) + line(` MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "$(CLOSE_APP)" /SD IDCANCEL IDRETRY retry_file`) + line(` Abort`) + line(`FunctionEnd`) + line("") + // The finish page runs after installation. The checkbox is MUI's "show // readme" option, so a silent install (/S) skips it and creates no shortcut. // The marker records that this installer created the shortcut once; the @@ -359,6 +388,9 @@ func (script Script) Generate() ([]byte, error) { line(` ; What an earlier update moved aside goes once nothing holds it.`) line(` ClearErrors`) line(` Delete "$INSTDIR\${APP_EXE}.*.old"`) + for _, file := range files { + line(` Delete "$INSTDIR\%s.*.old"`, strings.ReplaceAll(file.Destination, "/", `\`)) + } line(` SetOutPath "$INSTDIR"`) line(` ; The program's modification time would otherwise be stored in the installer`) line(` ; and make every build of the same program differ.`) @@ -382,7 +414,10 @@ func (script Script) Generate() ([]byte, error) { if parent := path.Dir(file.Destination); parent != "." { directory += `\` + strings.ReplaceAll(parent, "/", `\`) } + destination := `$INSTDIR\` + strings.ReplaceAll(file.Destination, "/", `\`) line(` SetOutPath "%s"`, directory) + line(` Push "%s"`, destination) + line(` Call EnsureFileWritable`) line(` File "/oname=%s" "%s"`, path.Base(file.Destination), source) } if len(files) > 0 { @@ -459,7 +494,8 @@ func (script Script) Generate() ([]byte, error) { line(` Delete "$INSTDIR\${APP_ICON}"`) } for _, file := range files { - line(` Delete "$INSTDIR\%s"`, strings.ReplaceAll(file.Destination, "/", `\`)) + line(` Delete "$INSTDIR\%s.*.old"`, strings.ReplaceAll(file.Destination, "/", `\`)) + line(` Delete /REBOOTOK "$INSTDIR\%s"`, strings.ReplaceAll(file.Destination, "/", `\`)) } for _, directory := range extraDirs(files) { line(` RMDir "$INSTDIR\%s"`, strings.ReplaceAll(directory, "/", `\`)) diff --git a/tools/winpkg/winpkg_test.go b/tools/winpkg/winpkg_test.go index 584024689..ff8745ed4 100644 --- a/tools/winpkg/winpkg_test.go +++ b/tools/winpkg/winpkg_test.go @@ -462,6 +462,33 @@ func TestEnsureClosedMovesARunningProgramAsideBeforeAskingTheUser(t *testing.T) } } +// A loaded native file (conpty.dll, OpenConsole.exe) can be renamed but not +// deleted, so the installer must move it aside before writing over it, exactly +// as it does for its own image. Asking first would end a silent install. +func TestEnsureFileWritableMovesALoadedFileAside(t *testing.T) { + got := generate(t, sample()) + start := strings.Index(got, "Function EnsureFileWritable") + if start < 0 { + t.Fatalf("the script lacks EnsureFileWritable:\n%s", got) + } + body := got[start:] + if end := strings.Index(body, "FunctionEnd"); end >= 0 { + body = body[:end] + } + remove := strings.Index(body, `Delete "$0"`) + rename := strings.Index(body, `Rename "$0" "$0.$1.old"`) + message := strings.Index(body, "MessageBox") + if remove < 0 || rename < 0 || message < 0 { + t.Fatalf("EnsureFileWritable lacks delete, rename or question:\n%s", body) + } + if !(remove < rename && rename < message) { + t.Errorf("EnsureFileWritable asks the user before moving the file aside:\n%s", body) + } + if !strings.Contains(body, "/SD IDCANCEL") { + t.Errorf("a silent install is not told to cancel:\n%s", body) + } +} + func TestFindReportsHowToInstall(t *testing.T) { t.Setenv("PATH", t.TempDir()) _, err := find("", nil) @@ -657,12 +684,18 @@ func TestGenerateInstallsAndRemovesExtraFiles(t *testing.T) { got := generate(t, script) for _, want := range []string{ ` SetOutPath "$INSTDIR\conpty\x64"`, + ` Push "$INSTDIR\conpty\x64\conpty.dll"`, + ` Call EnsureFileWritable`, ` File "/oname=conpty.dll" "/tmp/p/conpty/x64/conpty.dll"`, ` SetOutPath "$INSTDIR\conpty\x64\x64"`, + ` Push "$INSTDIR\conpty\x64\x64\OpenConsole.exe"`, + ` Call EnsureFileWritable`, ` File "/oname=OpenConsole.exe" "/tmp/p/conpty/x64/x64/OpenConsole.exe"`, ` SetOutPath "$INSTDIR"`, - ` Delete "$INSTDIR\conpty\x64\conpty.dll"`, - ` Delete "$INSTDIR\conpty\x64\x64\OpenConsole.exe"`, + ` Delete "$INSTDIR\conpty\x64\conpty.dll.*.old"`, + ` Delete /REBOOTOK "$INSTDIR\conpty\x64\conpty.dll"`, + ` Delete "$INSTDIR\conpty\x64\x64\OpenConsole.exe.*.old"`, + ` Delete /REBOOTOK "$INSTDIR\conpty\x64\x64\OpenConsole.exe"`, } { if !strings.Contains(got, want) { t.Errorf("the script lacks %q", want) From 49bc0aea86f5a6ab82ae2b5f925088f3ae1969cd Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:57:44 +0800 Subject: [PATCH 06/12] fix(linux): restore read-only editor input before the first key --- app/run_canvas.go | 6 + internal/platform/contract.go | 3 + internal/platform/linux/input_linux_test.go | 137 ++++++++++++++++++++ internal/platform/linux/window_linux.go | 19 +++ 4 files changed, 165 insertions(+) diff --git a/app/run_canvas.go b/app/run_canvas.go index 69dd5f9c1..c89c8e0da 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -203,6 +203,12 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, OnClosed: normalized.OnClosed, DynamicTextInput: normalized.TextInput != nil, } + if normalized.TextInput != nil { + config.ReadOnlyTextFocused = func() bool { + context, _, _ := painter.focusedTextField() + return !context.ID.IsZero() && context.ReadOnly + } + } config.WindowBorderColor = borderColorHandler(normalized.WindowBorderColor) return config, frames } diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 2beef8ef8..9a29c1870 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -141,6 +141,9 @@ type Config struct { OnClosed func() TextInput *TextInput DynamicTextInput bool + // ReadOnlyTextFocused reports the last painted focused hit. Linux uses it + // to recheck a disabled native input before routing a new key. + ReadOnlyTextFocused func() bool // Actions, when set, is filled by the adapter with what the window controls // that Viva draws need: see WindowActions. It is set for a WindowCustomTitlebar // window on a platform whose system draws no controls for it. diff --git a/internal/platform/linux/input_linux_test.go b/internal/platform/linux/input_linux_test.go index 979671de4..00fbdbde2 100644 --- a/internal/platform/linux/input_linux_test.go +++ b/internal/platform/linux/input_linux_test.go @@ -13,6 +13,7 @@ import ( "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" + "github.com/vivaui/viva/text" ) func TestNormalizedKeysym(t *testing.T) { @@ -727,6 +728,142 @@ func TestX11FocusInForgetsHeldKeys(t *testing.T) { } } +func TestX11FocusInRefreshesInputBeforeNextQueuedKey(t *testing.T) { + var calls []string + input := &platform.TextInput{State: platform.TextState{Value: "writable"}} + state := &linuxWindowState{ + win: &window{}, + application: &linuxApplication{}, + text: &linuxTextInput{}, + config: platform.Config{ + DynamicTextInput: true, + ReadOnlyTextFocused: func() bool { return true }, + OnActivate: func() { calls = append(calls, "activate") }, + OnRedraw: func() (platform.Frame, error) { + calls = append(calls, "redraw") + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: input}}, nil + }, + }, + router: eventRouter{present: func(frame platform.Frame) error { + if !frame.TextInput.Changed || frame.TextInput.Input != input { + t.Fatalf("activation did not publish the new text input: %+v", frame.TextInput) + } + calls = append(calls, "present") + return nil + }}, + } + previous := activeWindow.Load() + defer activeWindow.Store(previous) + for _, event := range []xcbFocusEvent{ + {ResponseType: xcbFocusIn, Detail: 5}, // NotifyPointer + {ResponseType: xcbFocusIn, Mode: xcbNotifyGrab}, + } { + if closed, err := state.handleEvent(unsafe.Pointer(&event)); closed || err != nil { + t.Fatalf("non-keyboard focus: closed=%v err=%v", closed, err) + } + } + if len(calls) != 0 { + t.Fatalf("spurious focus refreshed input: %v", calls) + } + event := xcbFocusEvent{ResponseType: xcbFocusIn, Detail: xcbNotifyAncestor} + if closed, err := state.handleEvent(unsafe.Pointer(&event)); closed || err != nil { + t.Fatalf("keyboard focus: closed=%v err=%v", closed, err) + } + if want := []string{"activate", "redraw", "present"}; !reflect.DeepEqual(calls, want) { + t.Fatalf("input was not refreshed before returning to the queued key: %v, want %v", calls, want) + } + state.config.ReadOnlyTextFocused = func() bool { return false } + if closed, err := state.handleEvent(unsafe.Pointer(&event)); closed || err != nil { + t.Fatalf("non-read-only activation: closed=%v err=%v", closed, err) + } + if want := []string{"activate", "redraw", "present", "activate"}; !reflect.DeepEqual(calls, want) { + t.Fatalf("non-read-only activation repainted before the queued key: %v, want %v", calls, want) + } +} + +func TestX11RevalidatesDisabledEditorBeforeFirstNativeKey(t *testing.T) { + editor := text.NewEditor("cat") + editor.MoveTo(0, false) + textInput := &linuxTextInput{engine: fixedAdvanceEngine{}} + defer textInput.close() + redraws := 0 + config := platform.Config{ + DynamicTextInput: true, + ReadOnlyTextFocused: func() bool { return !textInput.enabled }, + OnRedraw: func() (platform.Frame, error) { + redraws++ + field := callbackTextField(editor) + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &field}}, nil + }, + } + textInput.config = &config + state := &linuxWindowState{ + win: &window{keymap: xcbKeymap{first: 9, last: 9, perKeycode: 2, keysyms: []uint32{'x', 'X'}}}, + config: config, text: textInput, + router: eventRouter{config: config, text: textInput, present: func(frame platform.Frame) error { + _, _, err := textInput.prepare(frame) + return err + }}, + } + previous := activeWindow.Load() + defer activeWindow.Store(previous) + key := xcbInputEvent{ResponseType: xcbKeyPress, Detail: 9} + if closed, err := state.handleEvent(unsafe.Pointer(&key)); closed || err != nil { + t.Fatalf("first key: closed=%v err=%v", closed, err) + } + if editor.String() != "xcat" || redraws == 0 { + t.Fatalf("first native key lost after read-only input: text=%q redraws=%d", editor.String(), redraws) + } + before := redraws + if closed, err := state.handleEvent(unsafe.Pointer(&key)); closed || err != nil { + t.Fatalf("next key: closed=%v err=%v", closed, err) + } + if editor.String() != "xxcat" || redraws != before+1 { + t.Fatalf("enabled input was revalidated unnecessarily: text=%q redraws=%d->%d", editor.String(), before, redraws) + } +} + +// BenchmarkX11KeyOnDisabledText compares a nonmodifier key on a focused field +// whose native input is disabled, with and without the read-only refresh that +// repaints before each key. The difference is the steady-state cost of a +// focused read-only field; the application's paint itself is not included. +func BenchmarkX11KeyOnDisabledText(b *testing.B) { + b.Run("not read-only", func(b *testing.B) { benchmarkDisabledTextKey(b, false) }) + b.Run("read-only", func(b *testing.B) { benchmarkDisabledTextKey(b, true) }) +} + +func benchmarkDisabledTextKey(b *testing.B, readOnly bool) { + textInput := &linuxTextInput{engine: fixedAdvanceEngine{}} + defer textInput.close() + config := platform.Config{ + DynamicTextInput: true, + ReadOnlyTextFocused: func() bool { return readOnly }, + OnRedraw: func() (platform.Frame, error) { + // A read-only field is painted without a native input. + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true}}, nil + }, + } + textInput.config = &config + state := &linuxWindowState{ + win: &window{keymap: xcbKeymap{first: 9, last: 9, perKeycode: 2, keysyms: []uint32{'x', 'X'}}}, + config: config, text: textInput, + router: eventRouter{config: config, text: textInput, present: func(frame platform.Frame) error { + _, _, err := textInput.prepare(frame) + return err + }}, + } + previous := activeWindow.Load() + defer activeWindow.Store(previous) + key := xcbInputEvent{ResponseType: xcbKeyPress, Detail: 9} + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + if _, err := state.handleEvent(unsafe.Pointer(&key)); err != nil { + b.Fatal(err) + } + } +} + func TestModifierTrackerRetainsKeysStillDown(t *testing.T) { tracker := newModifierTracker() tracker.press(10, 0, input.KeyUnknown) diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 2fa0279a3..2addd094c 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -841,6 +841,17 @@ func (state *linuxWindowState) reportFrame() (int32, int32, bool) { return x, y, true } +// A read-only hit can become writable outside the app. Publish its current +// input owner before a queued key is routed through the old disabled owner. +func (state *linuxWindowState) refreshReadOnlyTextInput() error { + config := state.config + if !config.DynamicTextInput || state.text == nil || state.text.enabled || + config.ReadOnlyTextFocused == nil || !config.ReadOnlyTextFocused() || config.OnRedraw == nil { + return nil + } + return state.router.presentFrame(config.OnRedraw()) +} + func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { win, config, textInput, renderer, router := state.win, state.config, state.text, state.renderer, state.router activeWindow.Store(win) @@ -1031,6 +1042,11 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { inputEvent := (*xcbInputEvent)(event) repeat := state.pendingKeyReleaseDetail == inputEvent.Detail && state.pendingKeyReleaseTime == inputEvent.Time state.pendingKeyReleaseDetail, state.pendingKeyReleaseTime = 0, 0 + if !win.keymap.key(inputEvent.Detail).IsModifier() { + if err := state.refreshReadOnlyTextInput(); err != nil { + return false, err + } + } return false, router.key(&win.keymap, inputEvent, repeat) case xcbKeyRelease: inputEvent := (*xcbInputEvent)(event) @@ -1067,6 +1083,9 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { // The same details, outside a grab, are the window becoming active. if realFocus && keyboardFocus && config.OnActivate != nil { config.OnActivate() + if err := state.refreshReadOnlyTextInput(); err != nil { + return false, err + } } if keyboardFocus { // A key pressed or released while another window or a grab held the From 84a9897996da19693389c1d37f1b435d9514d03a Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Mon, 16 Nov 2026 20:58:03 -0800 Subject: [PATCH 07/12] fix(update): stage a Windows patch payload before quitting --- docs/updating.md | 4 +- update/install.go | 3 +- update/install_windows.go | 46 ++++++++++-- update/install_windows_test.go | 127 ++++++++++++++++++++++++++++++++- 4 files changed, 168 insertions(+), 12 deletions(-) diff --git a/docs/updating.md b/docs/updating.md index 201f88740..df3681b56 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -215,7 +215,9 @@ payload kind do not match, copies the installed payload into a staging directory, and applies the patch there. `Install` then runs the same checks as a full update (the bundle identifier, version and `codesign` on macOS) and replaces the application. A failure in either step changes nothing: the application keeps -running the old version and can download the whole archive. +running the old version and can download the whole archive. `Install` copies the +payload before it calls `quit`, so the directory `ApplyPatch` returned is still +the application's to delete once `quit` has been called. ## Updating in the application diff --git a/update/install.go b/update/install.go index 49f66a196..8fd6081a6 100644 --- a/update/install.go +++ b/update/install.go @@ -43,7 +43,8 @@ type InstallOptions struct { // name does not matter, so the one ApplyPatch returns can be passed as it // is: the copy takes the running bundle's name. Install replaces the running // application with it exactly as it would with an unpacked archive, running - // the same checks. + // the same checks. Install copies the payload before it calls quit, so the + // caller still owns it and may delete it once quit has been called. Payload string // Asset is the archive it came from. Its Format tells Install how to unpack // it, and the format must suit the running platform. diff --git a/update/install_windows.go b/update/install_windows.go index 9f9028b95..9baf81fa9 100644 --- a/update/install_windows.go +++ b/update/install_windows.go @@ -185,14 +185,41 @@ func installPayload(options InstallOptions, quit func()) error { if err := checkWritable(installDir); err != nil { return err } + // The helper reads the payload only after this process has exited, and the + // caller may delete its payload as soon as quit is called, as it may on the + // other platforms. The helper reads a copy of its own instead and deletes + // it when it is done, whether the update worked or not. + options.report("staging") + staged, err := stagePayloadDir(payload) + if err != nil { + return fmt.Errorf("update: staging the payload: %w", err) + } options.report("replacing") - if err := startPayloadHelper(os.Getpid(), payload, installDir, executable, options.Args); err != nil { + if err := startPayload(os.Getpid(), staged, installDir, executable, options.Args); err != nil { + _ = os.RemoveAll(staged) return fmt.Errorf("update: start the update helper: %w", err) } quit() return nil } +// stagePayloadDir copies payload into a new temporary directory, which the update +// helper owns from then on, and returns that directory. +func stagePayloadDir(payload string) (string, error) { + staged, err := os.MkdirTemp("", "viva-update-payload-") + if err != nil { + return "", err + } + if err := copyTree(payload, staged); err != nil { + _ = os.RemoveAll(staged) + return "", err + } + return staged, nil +} + +// startPayload starts the update helper; a test replaces it. +var startPayload = startPayloadHelper + // startPayloadHelper launches a detached PowerShell script that waits for this // process to exit, copies the staged files over the installation and starts // the new program. It moves every file it replaces to a same-volume backup until @@ -217,8 +244,6 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, fmt.Fprintf(&script, "$payload = %s\n", powerShellQuote(payload)) fmt.Fprintf(&script, "$dir = %s\n", powerShellQuote(installDir)) fmt.Fprintf(&script, "$exe = %s\n", powerShellQuote(executable)) - // Enumeration expands DOS aliases, so both substring roots need full names. - script.WriteString("$payload = (Get-Item -LiteralPath $payload).FullName\n") script.WriteString("$backup = Join-Path $dir ('.viva-update-' + [guid]::NewGuid().ToString('N'))\n") script.WriteString("$created = New-Object System.Collections.ArrayList\n") script.WriteString("$temps = New-Object System.Collections.ArrayList\n") @@ -235,6 +260,9 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, script.WriteString(" foreach ($rel in $created) { Remove-Item -LiteralPath (Join-Path $dir $rel) -Force -ErrorAction SilentlyContinue }\n") script.WriteString(" foreach ($tmp in $temps) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }\n") script.WriteString("}\n") + // The payload is the helper's own copy (stagePayloadDir): it is deleted on every + // way out, so a failed update leaves nothing behind either. + script.WriteString("function Discard { Remove-Item -LiteralPath $payload -Recurse -Force -ErrorAction SilentlyContinue }\n") // The relaunch keeps the arguments the program was started with, so a test // binary starts its own case again rather than a whole suite. script.WriteString("function Launch {\n") @@ -248,8 +276,12 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, script.WriteString(" if (-not (Get-Process -Id $parent -ErrorAction SilentlyContinue)) { $alive = $false; break }\n") script.WriteString(" Start-Sleep -Seconds 1\n") script.WriteString("}\n") - script.WriteString("if ($alive) { exit 1 }\n") + script.WriteString("if ($alive) { Discard; exit 1 }\n") script.WriteString("try {\n") + // Enumeration expands DOS aliases, so both substring roots need full names. + // Resolving it is inside the try: a payload that cannot be read must still + // start the old version again rather than leave no application running. + script.WriteString(" $payload = (Get-Item -LiteralPath $payload).FullName\n") // A backup a previous update could not remove (its old executable was still // held) would otherwise stay in the install directory for good: the name is // a fresh GUID each time. @@ -279,10 +311,10 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, } script.WriteString("\n") script.WriteString(" Start-Sleep -Seconds 2\n") - script.WriteString(" if ($p.HasExited -and $p.ExitCode -ne 0) { Restore; Launch; exit 1 }\n") - script.WriteString("} catch { Restore; Launch; exit 1 }\n") + script.WriteString(" if ($p.HasExited -and $p.ExitCode -ne 0) { Restore; Launch; Discard; exit 1 }\n") + script.WriteString("} catch { Restore; Launch; Discard; exit 1 }\n") script.WriteString("Remove-Item -Recurse -Force $backup -ErrorAction SilentlyContinue\n") - script.WriteString("Remove-Item -Recurse -Force $payload -ErrorAction SilentlyContinue\n") + script.WriteString("Discard\n") script.WriteString("exit 0\n") return script.String() } diff --git a/update/install_windows_test.go b/update/install_windows_test.go index a1b3c2b28..d82dca3b5 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -232,9 +232,10 @@ func TestPayloadHelperScriptKeepsABackupAndRestores(t *testing.T) { "$p.HasExited -and $p.ExitCode -ne 0", "function Launch {", "Start-Process -FilePath $exe -ArgumentList", - "if ($p.HasExited -and $p.ExitCode -ne 0) { Restore; Launch; exit 1 }", - "} catch { Restore; Launch; exit 1 }", - "Remove-Item -Recurse -Force $payload", + "if ($p.HasExited -and $p.ExitCode -ne 0) { Restore; Launch; Discard; exit 1 }", + "} catch { Restore; Launch; Discard; exit 1 }", + "if ($alive) { Discard; exit 1 }", + "function Discard { Remove-Item -LiteralPath $payload -Recurse -Force", "exit 0", } { if !strings.Contains(script, want) { @@ -267,6 +268,123 @@ func TestInstallPayloadRefusesAFile(t *testing.T) { } } +// An application deletes the payload ApplyPatch made once Install has called +// quit, as it may on every platform; the helper reads the payload only after the +// application has exited, so it must read a copy of its own. +func TestInstallPayloadHandsTheHelperACopyTheCallerMayDelete(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + payload := t.TempDir() + want := copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, filepath.Base(executable))) + if err := os.MkdirAll(filepath.Join(payload, "lib"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(payload, "lib", "new.dll"), []byte("new"), 0o644); err != nil { + t.Fatal(err) + } + var started string + previous := startPayload + startPayload = func(_ int, staged, _, _ string, _ []string) error { + started = staged + return nil + } + t.Cleanup(func() { startPayload = previous }) + + quit := func() { + if err := os.RemoveAll(payload); err != nil { + t.Errorf("delete the payload after quit: %v", err) + } + } + if err := installPayload(InstallOptions{Payload: payload}, quit); err != nil { + t.Fatal(err) + } + if started == "" { + t.Fatal("installPayload did not start the helper") + } + t.Cleanup(func() { _ = os.RemoveAll(started) }) + if strings.EqualFold(filepath.Clean(started), filepath.Clean(payload)) { + t.Fatal("the helper was handed the caller's payload, which is gone before the helper reads it") + } + got, err := os.ReadFile(filepath.Join(started, filepath.Base(executable))) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("the helper's copy lacks the program: %v", err) + } + if data, err := os.ReadFile(filepath.Join(started, "lib", "new.dll")); err != nil || string(data) != "new" { + t.Fatalf("the helper's copy lacks lib\\new.dll: %q, %v", data, err) + } +} + +func TestInstallPayloadDeletesItsCopyWhenTheHelperDoesNotStart(t *testing.T) { + executable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + payload := t.TempDir() + copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, filepath.Base(executable))) + var started string + previous := startPayload + startPayload = func(_ int, staged, _, _ string, _ []string) error { + started = staged + return errors.New("no helper") + } + t.Cleanup(func() { startPayload = previous }) + + called := false + if err := installPayload(InstallOptions{Payload: payload}, func() { called = true }); err == nil { + t.Fatal("installPayload reported success without a helper") + } + if called { + t.Fatal("installPayload called quit although the helper did not start") + } + if _, err := os.Stat(started); !os.IsNotExist(err) { + _ = os.RemoveAll(started) + t.Errorf("the copy for a helper that never started was left behind: %v", err) + } + if _, err := os.Stat(filepath.Join(payload, filepath.Base(executable))); err != nil { + t.Errorf("the caller's payload was touched: %v", err) + } +} + +// A helper that cannot read its payload must start the old version again: the +// application has already quit, and nothing else would bring it back. +func TestPayloadHelperRelaunchesTheOldVersionWithoutAPayload(t *testing.T) { + install := t.TempDir() + testExecutable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + original := copyWindowsFile(t, testExecutable, filepath.Join(install, "app.exe")) + marker := filepath.Join(t.TempDir(), "started") + t.Setenv("VIVA_UPDATE_START_MARKER", marker) + missing := filepath.Join(t.TempDir(), "gone") + script := payloadHelperScript(999999, missing, install, filepath.Join(install, "app.exe"), []string{"-test.run=^TestPayloadHelperProcess$"}) + runPayloadHelper(t, script, 1) + waitForMarker(t, marker) + got, err := os.ReadFile(filepath.Join(install, "app.exe")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, original) { + t.Error("app.exe changed although there was nothing to install") + } +} + +// waitForMarker waits, for a bounded time, until the program the helper started +// wrote marker: Launch starts it without waiting for it. +func waitForMarker(t *testing.T, marker string) { + t.Helper() + for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) { + if data, err := os.ReadFile(marker); err == nil && string(data) == "started" { + return + } + if time.Now().After(deadline) { + t.Fatal("the old version was not started again") + } + } +} + func systemExecutable(t *testing.T, name string) string { t.Helper() path := filepath.Join(os.Getenv("SystemRoot"), "System32", name) @@ -468,6 +586,9 @@ func TestPayloadHelperRollsBackAFailedStart(t *testing.T) { if _, err := os.Stat(filepath.Join(install, "new.dll")); !os.IsNotExist(err) { t.Errorf("new.dll survived the rollback: %v", err) } + if _, err := os.Stat(payload); !os.IsNotExist(err) { + t.Errorf("the helper's payload survived a failed update: %v", err) + } } func TestPayloadHelperProcess(t *testing.T) { From cefdb9dea1848f46f3e7428d383e02680b96e8d0 Mon Sep 17 00:00:00 2001 From: Dean Cen Date: Tue, 17 Nov 2026 12:58:08 +0800 Subject: [PATCH 08/12] fix(linux): search XDG config dirs for Vulkan ICD manifests --- internal/platform/linux/api_linux_test.go | 115 ++++++++++++++++++++++ internal/platform/linux/vulkan_linux.go | 85 ++++++++++++++++ 2 files changed, 200 insertions(+) diff --git a/internal/platform/linux/api_linux_test.go b/internal/platform/linux/api_linux_test.go index e2650a531..54b0693d3 100644 --- a/internal/platform/linux/api_linux_test.go +++ b/internal/platform/linux/api_linux_test.go @@ -7,6 +7,7 @@ import ( "fmt" "math" "os" + "path/filepath" "slices" "strings" "testing" @@ -467,6 +468,120 @@ func TestMissingVulkanIsNamedAndSaysWhatToInstall(t *testing.T) { } } +func TestVulkanDriverManifestDetection(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "notes.txt"), []byte("not a driver"), 0o600); err != nil { + t.Fatal(err) + } + if vulkanDriverManifestsExist([]string{dir}) { + t.Fatal("a directory without an ICD manifest counts as a Vulkan driver") + } + manifest := filepath.Join(dir, "driver.json") + if err := os.WriteFile(manifest, []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + if !vulkanDriverManifestsExist([]string{dir}) || !vulkanDriverManifestsExist([]string{manifest}) { + t.Fatal("an ICD manifest was not detected") + } +} + +func TestVulkanWithoutDriverManifestDoesNotLoadDriver(t *testing.T) { + t.Setenv("VK_DRIVER_FILES", filepath.Join(t.TempDir(), "missing.json")) + t.Setenv("VK_ICD_FILENAMES", "") + t.Setenv("VK_ADD_DRIVER_FILES", "") + if vulkanDriverConfigured() { + t.Fatal("a missing ICD manifest counts as a Vulkan driver") + } + _, err := loadVulkan() + if !errors.Is(err, platform.ErrNoGraphics) { + t.Fatalf("loadVulkan error = %v, want platform.ErrNoGraphics", err) + } +} + +func TestVulkanEmptyICDOverrideDoesNotUseDefaultManifests(t *testing.T) { + root := t.TempDir() + t.Setenv("HOME", root) + t.Setenv("XDG_DATA_HOME", root) + writeVulkanManifest(t, filepath.Join(root, "vulkan", "icd.d")) + t.Setenv("VK_DRIVER_FILES", "") + t.Setenv("VK_ICD_FILENAMES", "") + unsetTestEnv(t, "VK_ADD_DRIVER_FILES") + if vulkanDriverConfigured() { + t.Fatal("an empty ICD override falls back to the default driver manifests") + } +} + +// The default search reads each XDG base the loader reads. Only positive cases are +// checked: the system's /etc/vulkan/icd.d is always searched, so an empty result +// cannot be asserted on a machine that has a driver installed. +func TestVulkanDefaultManifestSearchFindsEachXDGDirectory(t *testing.T) { + cases := []struct { + name string + // env sets the search variables under root, and returns the base whose + // vulkan/icd.d holds the manifest. + env func(t *testing.T, root string) string + }{ + {"config home", func(t *testing.T, root string) string { + t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config")) + return filepath.Join(root, "config") + }}, + {"home default config", func(t *testing.T, root string) string { + t.Setenv("HOME", root) + return filepath.Join(root, ".config") + }}, + {"config dirs", func(t *testing.T, root string) string { + t.Setenv("XDG_CONFIG_DIRS", filepath.Join(root, "missing")+":"+filepath.Join(root, "xdg")) + return filepath.Join(root, "xdg") + }}, + {"data home", func(t *testing.T, root string) string { + t.Setenv("XDG_DATA_HOME", filepath.Join(root, "data")) + return filepath.Join(root, "data") + }}, + {"data dirs", func(t *testing.T, root string) string { + t.Setenv("XDG_DATA_DIRS", filepath.Join(root, "share")) + return filepath.Join(root, "share") + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + t.Setenv("HOME", filepath.Join(root, "home")) + t.Setenv("XDG_CONFIG_DIRS", "") + t.Setenv("XDG_DATA_DIRS", "") + unsetTestEnv(t, "XDG_CONFIG_HOME") + unsetTestEnv(t, "XDG_DATA_HOME") + unsetTestEnv(t, "VK_DRIVER_FILES") + unsetTestEnv(t, "VK_ICD_FILENAMES") + unsetTestEnv(t, "VK_ADD_DRIVER_FILES") + base := tc.env(t, root) + writeVulkanManifest(t, filepath.Join(base, "vulkan", "icd.d")) + if !vulkanDriverConfigured() { + t.Fatalf("a manifest under the %s was not found", tc.name) + } + }) + } +} + +// unsetTestEnv removes name for the rest of the test. t.Setenv restores the original +// value at cleanup, which the bare os.Unsetenv alone would not. +func unsetTestEnv(t *testing.T, name string) { + t.Helper() + t.Setenv(name, "") + if err := os.Unsetenv(name); err != nil { + t.Fatal(err) + } +} + +func writeVulkanManifest(t *testing.T, dir string) { + t.Helper() + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "driver.json"), []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } +} + // A loader whose installed drivers fail to initialize fails enumeration with // VK_ERROR_INITIALIZATION_FAILED (a driver-less loader gives // VK_ERROR_INCOMPATIBLE_DRIVER). That is still a machine that cannot draw, not a diff --git a/internal/platform/linux/vulkan_linux.go b/internal/platform/linux/vulkan_linux.go index aed120aae..8a7eac67d 100644 --- a/internal/platform/linux/vulkan_linux.go +++ b/internal/platform/linux/vulkan_linux.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" "math" + "os" + "path/filepath" "unsafe" "github.com/ebitengine/purego" @@ -473,7 +475,90 @@ type vulkanScratch struct { contentX, contentY int32 } +// Loader 1.1.97 segfaults in vkCreateInstance when no ICD manifest exists. +func vulkanDriverConfigured() bool { + var paths []string + if files, ok := os.LookupEnv("VK_DRIVER_FILES"); ok { + paths = filepath.SplitList(files) + } else if files, ok := os.LookupEnv("VK_ICD_FILENAMES"); ok { + paths = filepath.SplitList(files) + } else { + paths = vulkanDefaultManifestDirs() + } + if files := os.Getenv("VK_ADD_DRIVER_FILES"); files != "" { + paths = append(paths, filepath.SplitList(files)...) + } + return vulkanDriverManifestsExist(paths) +} + +// vulkanDefaultManifestDirs lists the directories the loader searches for ICD manifests +// when no override is set, in its order: the user's config and data homes, then the +// system lists under each XDG base. +func vulkanDefaultManifestDirs() []string { + home := os.Getenv("HOME") + configHome := os.Getenv("XDG_CONFIG_HOME") + if configHome == "" && home != "" { + configHome = filepath.Join(home, ".config") + } + dataHome := os.Getenv("XDG_DATA_HOME") + if dataHome == "" && home != "" { + dataHome = filepath.Join(home, ".local", "share") + } + var paths []string + if configHome != "" { + paths = append(paths, filepath.Join(configHome, "vulkan", "icd.d")) + } + paths = appendVulkanDirs(paths, os.Getenv("XDG_CONFIG_DIRS"), "/etc/xdg") + if dataHome != "" { + paths = append(paths, filepath.Join(dataHome, "vulkan", "icd.d")) + } + paths = appendVulkanDirs(paths, os.Getenv("XDG_DATA_DIRS"), "/usr/local/share:/usr/share") + return append(paths, "/etc/vulkan/icd.d") +} + +// appendVulkanDirs adds the vulkan/icd.d directory under each entry of an XDG search list, +// or under the fallback list when the variable is unset. +func appendVulkanDirs(paths []string, list, fallback string) []string { + if list == "" { + list = fallback + } + for _, dir := range filepath.SplitList(list) { + if dir != "" { + paths = append(paths, filepath.Join(dir, "vulkan", "icd.d")) + } + } + return paths +} + +func vulkanDriverManifestsExist(paths []string) bool { + for _, path := range paths { + if path == "" { + continue + } + info, err := os.Stat(path) + if err != nil { + continue + } + if !info.IsDir() { + return true + } + entries, err := os.ReadDir(path) + if err != nil { + continue + } + for _, entry := range entries { + if !entry.IsDir() && filepath.Ext(entry.Name()) == ".json" { + return true + } + } + } + return false +} + func loadVulkan() (*vulkanAPI, error) { + if !vulkanDriverConfigured() { + return nil, noVulkan("Vulkan has no driver (no ICD manifest)", nil) + } library, err := purego.Dlopen("libvulkan.so.1", purego.RTLD_NOW|purego.RTLD_LOCAL) if err != nil { return nil, noVulkan("libvulkan.so.1 is not installed", err) From 68f1a05b9ca16fbf81ed6451a2615f1c545c3ada Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Mon, 16 Nov 2026 21:00:46 -0800 Subject: [PATCH 09/12] feat(app): add window title support across native and headless backends --- app/title.go | 24 ++++++++ app/title_test.go | 41 ++++++++++++++ headless/application.go | 12 ++++ internal/platform/darwin/native.h | 1 + internal/platform/darwin/native.m | 37 ++++++++++++ internal/platform/darwin/platform.go | 13 +++++ .../platform/darwin/testdata/traffic_lights.m | 7 +++ internal/platform/linux/gtk_window_linux.go | 11 ++++ internal/platform/windows/title_windows.go | 56 +++++++++++++++++++ internal/platform/windows/window_windows.go | 5 ++ 10 files changed, 207 insertions(+) create mode 100644 app/title.go create mode 100644 app/title_test.go create mode 100644 internal/platform/windows/title_windows.go diff --git a/app/title.go b/app/title.go new file mode 100644 index 000000000..3ad9c3a3e --- /dev/null +++ b/app/title.go @@ -0,0 +1,24 @@ +package app + +import "fmt" + +type titleControl interface { + SetTitle(string) error +} + +// SetTitle changes the window's title: the text of its system title bar, the +// task switcher and the taskbar or Dock window list. A window with +// WindowCustomTitlebar keeps no visible system title bar, but the title is still +// what the system lists and what assistive technology reads. Calls are safe from +// any goroutine; the change is applied on the window's thread. Unsupported hosts +// return an error wrapping ErrUnsupported. +func (window *Window) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("app: window is closed") + } + control, ok := window.control.(titleControl) + if !ok { + return fmt.Errorf("%w: window titles", ErrUnsupported) + } + return control.SetTitle(title) +} diff --git a/app/title_test.go b/app/title_test.go new file mode 100644 index 000000000..a2828d29d --- /dev/null +++ b/app/title_test.go @@ -0,0 +1,41 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "testing" +) + +type titleTestControl struct { + fakeWindow + titles []string +} + +func (control *titleTestControl) SetTitle(title string) error { + control.titles = append(control.titles, title) + return nil +} + +func TestSetTitleDelegatesToTheHost(t *testing.T) { + control := &titleTestControl{} + window := &Window{control: control} + if err := window.SetTitle("project – main.go"); err != nil { + t.Fatal(err) + } + if len(control.titles) != 1 || control.titles[0] != "project – main.go" { + t.Fatalf("titles = %q", control.titles) + } + window.closed.Store(true) + if err := window.SetTitle("closed"); err == nil || len(control.titles) != 1 { + t.Fatal("closed window accepted a title") + } + var missing *Window + if err := missing.SetTitle("nil"); err == nil { + t.Fatal("nil window accepted a title") + } + unsupported := &Window{control: &fakeWindow{}} + if err := unsupported.SetTitle("x"); !errors.Is(err, ErrUnsupported) { + t.Fatalf("unsupported host: %v", err) + } +} diff --git a/headless/application.go b/headless/application.go index 6f0f90d34..dd7dac503 100644 --- a/headless/application.go +++ b/headless/application.go @@ -179,6 +179,18 @@ func (window *headlessWindow) SetFullscreen(fullscreen bool) error { return nil } +// SetTitle records the title the windows command lists. +func (window *headlessWindow) SetTitle(title string) error { + window.application.mu.Lock() + defer window.application.mu.Unlock() + entry := window.application.windows[window.id] + if entry == nil { + return fmt.Errorf("headless: window is closed") + } + entry.title = title + return nil +} + func (window *headlessWindow) Fullscreen() bool { window.application.mu.Lock() entry := window.application.windows[window.id] diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index e42b13054..bdc325aac 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -399,6 +399,7 @@ void viva_application_move_window(void *window, double x, double y); /* Posts a content resize to the AppKit event loop. */ void viva_application_set_window_size(void *window, double width, double height); int viva_application_set_fullscreen(void *window, int fullscreen); +int viva_application_set_title(void *window, const char *title); int viva_application_fullscreen(void *window); int viva_application_set_always_on_top(void *window, int enabled); int viva_application_run(void); diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 443d89117..94f395c5e 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -6369,6 +6369,7 @@ - (void)confirmClose; - (void)hideWindow; - (void)showWindow; - (void)setFullscreen:(BOOL)fullscreen; +- (void)setWindowTitle:(NSString *)title; - (void)setAlwaysOnTop:(BOOL)enabled; - (BOOL)isFullscreen; - (void)reopenWindow; @@ -6926,6 +6927,20 @@ - (BOOL)isFullscreen { return (_window.styleMask & NSWindowStyleMaskFullScreen) != 0; } +- (void)setWindowTitle:(NSString *)title { + [_title release]; + _title = [title copy]; + if (_window != nil) { + _window.title = _title; + /* A new title lays the titlebar out again, and AppKit sets the zoom + * button back at the system's height without reporting the move as a + * frame change, so keepTrafficLightsCentered never hears of it. */ + if (_windowMode == VIVA_WINDOW_CUSTOM_TITLEBAR) { + viva_place_traffic_lights(_window, _titlebarHeight, _trafficLightScale); + } + } +} + - (void)setFullscreen:(BOOL)fullscreen { _fullscreenTarget = fullscreen; if (!_fullscreenTransition && [self isFullscreen] != fullscreen) { @@ -7699,6 +7714,28 @@ int viva_application_set_fullscreen(void *window, int fullscreen) { return found; } +int viva_application_set_title(void *window, const char *title) { + __block int found = 0; + NSString *value = [[NSString alloc] initWithUTF8String:title != NULL ? title : ""]; + if (value == nil) { + value = [@"" retain]; + } + void (^work)(void) = ^{ + VivaAppDelegate *delegate = viva_find_window(window); + if (delegate != nil) { + found = 1; + [delegate setWindowTitle:value]; + } + }; + if ([NSThread isMainThread]) { + work(); + } else { + dispatch_sync(dispatch_get_main_queue(), work); + } + [value release]; + return found; +} + int viva_application_fullscreen(void *window) { __block int fullscreen = 0; void (^work)(void) = ^{ diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index fdf658132..557c39d2c 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -110,6 +110,19 @@ func (window *nativeWindow) SetFullscreen(fullscreen bool) error { return nil } +// SetTitle changes the NSWindow's title on the main thread. +func (window *nativeWindow) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("darwin: window is closed") + } + value := C.CString(title) + defer C.free(unsafe.Pointer(value)) + if C.viva_application_set_title(window.token, value) == 0 { + return fmt.Errorf("darwin: window is unavailable") + } + return nil +} + func (window *nativeWindow) Fullscreen() bool { return window != nil && !window.closed.Load() && C.viva_application_fullscreen(window.token) != 0 } diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index b79ca0e04..6b95fb841 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -163,6 +163,13 @@ int main(void) { window.titlebarAppearsTransparent = NO; window.titlebarAppearsTransparent = YES; assertCenter(window, 18, "after the titlebar was restyled"); + // A new title lays the titlebar out too, and AppKit moves the zoom + // button back without reporting it as a frame change. + [delegate setWindowTitle:@"project"]; + assertCenter(window, 18, "after the title changed"); + assertAligned(window, "after the title changed"); + [delegate setWindowTitle:@"project - file"]; + assertAligned(window, "after the title changed again"); assert(fabs(NSWidth(scaledClose.frame) / NSWidth(scaledClose.bounds) - compactScale) < 0.01); [delegate setAlwaysOnTop:YES]; assert(window.level == NSFloatingWindowLevel); diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index a8104776b..ca8504ed1 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -284,6 +284,17 @@ func (w *gtkWindow) SetFullscreen(fullscreen bool) error { func (w *gtkWindow) Fullscreen() bool { return w.fullscreen.Load() } +// SetTitle changes the toplevel's title on the GTK thread. +func (w *gtkWindow) SetTitle(title string) error { + w.app.enqueue(func() { + if !w.closed { + value := cString(title) + w.g.windowSetTitle(w.toplevel, &value[0]) + } + }) + return nil +} + func (w *gtkWindow) SetAlwaysOnTop(enabled bool) error { if w == nil || w.app == nil { return fmt.Errorf("linux: window is closed") diff --git a/internal/platform/windows/title_windows.go b/internal/platform/windows/title_windows.go new file mode 100644 index 000000000..a8661ba3c --- /dev/null +++ b/internal/platform/windows/title_windows.go @@ -0,0 +1,56 @@ +package windows + +import ( + "fmt" + "sync" + "syscall" + "unsafe" +) + +// wmSetTitle asks the window thread to apply the title SetTitle stored. +// SetWindowTextW from another thread would send WM_SETTEXT and wait for the +// window thread, so the change is posted instead. Its number is the next free +// one after wmSetSize (0x8052): the window procedure switches on every private +// message, and two of them with one number do not compile. +const wmSetTitle = 0x8053 + +var setWindowText = user.NewProc("SetWindowTextW") + +// titleRequest holds the latest title asked for until the window thread applies it. +type titleRequest struct { + mu sync.Mutex + title string + pending bool +} + +func (window *nativeWindow) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + request := &window.state.pendingTitle + request.mu.Lock() + request.title, request.pending = title, true + request.mu.Unlock() + if ok, _, err := postMessage.Call(window.state.window, wmSetTitle, 0, 0); ok == 0 { + return fmt.Errorf("windows: request title: %w", err) + } + return nil +} + +// applyTitle sets the stored title on the window and in the accessibility tree. +func (state *windowState) applyTitle() { + request := &state.pendingTitle + request.mu.Lock() + title, pending := request.title, request.pending + request.pending = false + request.mu.Unlock() + if !pending || state.window == 0 { + return + } + value, err := syscall.UTF16PtrFromString(title) + if err != nil { + return + } + state.config.Title = title + setWindowText.Call(state.window, uintptr(unsafe.Pointer(value))) +} diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index a61f56770..03dcc92d6 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -75,6 +75,8 @@ const ( ) type windowState struct { + // pendingTitle is the title SetTitle asked for, applied on the window thread. + pendingTitle titleRequest fullscreen atomic.Bool fullscreenChanging bool fullscreenStyle uint32 @@ -476,6 +478,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmFullscreen: state.setFullscreen(first != 0) return 0 + case wmSetTitle: + state.applyTitle() + return 0 case wmSysCommand: if state.fullscreen.Load() { switch first & 0xfff0 { From 76aba78e85c2068066e2b7b7d7858a139898400f Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 12:56:52 +0800 Subject: [PATCH 10/12] feat(app): set X11 window titles and reject unusable ones The default Linux build runs on X11, where SetTitle returned ErrUnsupported; only the opt-in GTK shell applied titles. The X11 window now applies them on its event loop, as SetSize does: SetTitle stores the latest title and posts a command, and the loop writes WM_NAME and _NET_WM_NAME. An empty title clears both. Titles are checked in app.Window.SetTitle before any backend sees them. A title with a NUL byte or invalid UTF-8 returns an error and changes nothing. Windows used to accept such a title and drop it silently, and Darwin truncated or emptied it, so the backends now agree. This follows #304, which landed as 68f1a05 and added SetTitle without the X11 path or the title checks. Tests cover the X11 command path with a fake xcb API, the headless windows listing with rejected titles and a closed window, and a Windows read-back through GetWindowTextW. The docs table gets a window title row. --- app/title.go | 15 ++- app/title_test.go | 5 + docs/system-integrations.md | 1 + headless/title_test.go | 44 +++++++++ internal/platform/linux/status_item_linux.go | 2 + .../platform/linux/window_identity_linux.go | 37 +++++--- internal/platform/linux/window_linux.go | 9 +- internal/platform/linux/window_title_linux.go | 26 +++++ .../platform/linux/window_title_linux_test.go | 95 +++++++++++++++++++ .../platform/windows/title_windows_test.go | 77 +++++++++++++++ 10 files changed, 295 insertions(+), 16 deletions(-) create mode 100644 headless/title_test.go create mode 100644 internal/platform/linux/window_title_linux.go create mode 100644 internal/platform/linux/window_title_linux_test.go create mode 100644 internal/platform/windows/title_windows_test.go diff --git a/app/title.go b/app/title.go index 3ad9c3a3e..6f627ba57 100644 --- a/app/title.go +++ b/app/title.go @@ -1,6 +1,10 @@ package app -import "fmt" +import ( + "fmt" + "strings" + "unicode/utf8" +) type titleControl interface { SetTitle(string) error @@ -10,12 +14,17 @@ type titleControl interface { // task switcher and the taskbar or Dock window list. A window with // WindowCustomTitlebar keeps no visible system title bar, but the title is still // what the system lists and what assistive technology reads. Calls are safe from -// any goroutine; the change is applied on the window's thread. Unsupported hosts -// return an error wrapping ErrUnsupported. +// any goroutine; the change is applied on the window's thread. A title must be +// valid UTF-8 without NUL bytes, since not every platform can hold the rest, so +// other titles return an error and change nothing. Unsupported hosts return an +// error wrapping ErrUnsupported. func (window *Window) SetTitle(title string) error { if window == nil || window.closed.Load() { return fmt.Errorf("app: window is closed") } + if !utf8.ValidString(title) || strings.IndexByte(title, 0) >= 0 { + return fmt.Errorf("app: window title must be valid UTF-8 without NUL bytes") + } control, ok := window.control.(titleControl) if !ok { return fmt.Errorf("%w: window titles", ErrUnsupported) diff --git a/app/title_test.go b/app/title_test.go index a2828d29d..350e24b31 100644 --- a/app/title_test.go +++ b/app/title_test.go @@ -26,6 +26,11 @@ func TestSetTitleDelegatesToTheHost(t *testing.T) { if len(control.titles) != 1 || control.titles[0] != "project – main.go" { t.Fatalf("titles = %q", control.titles) } + for _, bad := range []string{"main\x00.go", "main\xff.go"} { + if err := window.SetTitle(bad); err == nil || len(control.titles) != 1 { + t.Fatalf("title %q was accepted: titles = %q", bad, control.titles) + } + } window.closed.Store(true) if err := window.SetTitle("closed"); err == nil || len(control.titles) != 1 { t.Fatal("closed window accepted a title") diff --git a/docs/system-integrations.md b/docs/system-integrations.md index 664bd3a23..c6ef8dabd 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -36,6 +36,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Application menu bar (`Application.SetMenuBar`) | the NSMenu bar's application and Window menus stay; the application's own menus sit between them, with their key equivalents, enablement, check marks, submenus and loop-thread actions | `ErrUnsupported`: a window's own menu bar is `components.Menubar` | `ErrUnsupported`: `components.Menubar` | `ErrUnsupported`: `components.Menubar` | | System proxy (`app/proxy.SystemProxy`) | CFNetwork's settings for the URL: the static HTTP, HTTPS or SOCKS proxy with its bypass list. A PAC script is reported as `ErrSystemProxyUnavailable`, not silently bypassed | WinHTTP's automatic proxy: auto-detection (WPAD), the PAC script, or the static per-user settings | the environment only (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`); a proxy kept in GSettings is not read | `ErrSystemProxyUnavailable` | | Fullscreen (`RequestFullscreen`, `OnFullscreen`) | `NSWindow.toggleFullScreen:` | `SetWindowPos` / window style | window-manager fullscreen | `requestFullscreen` / `exitFullscreen`, reported by `fullscreenchange` | +| Window title (`SetTitle`) | `NSWindow.title`, the text the window list and Mission Control show | `SetWindowTextW`, applied on the window thread | `WM_NAME` and `_NET_WM_NAME` on X11; `gtk_window_set_title` on the GTK shell | `ErrUnsupported`: the page keeps its own title | | Page visibility (`OnMinimize`) | window minimized/restored | window minimized/restored | window minimized/restored | `visibilitychange`; a hidden tab counts as minimized | | Window activation (`OnActivate`) | `NSWindowDidBecomeKeyNotification` | `WM_ACTIVATE`, when not `WA_INACTIVE` | an X11 `FocusIn` whose detail is `Ancestor` or `Nonlinear` outside a grab, or GTK's `focus-in-event` | the window `focus` event | diff --git a/headless/title_test.go b/headless/title_test.go new file mode 100644 index 000000000..af530d9dc --- /dev/null +++ b/headless/title_test.go @@ -0,0 +1,44 @@ +//go:build darwin || windows || linux + +package headless + +import ( + "strings" + "testing" + + "github.com/vivaui/viva/app" +) + +func TestWindowTitleIsListedAndUnusableTitlesChangeNothing(t *testing.T) { + host := newApplicationSession(Options{ReferenceText: true}) + var window *app.Window + app.UseApplicationRunner(func(start func(app.Host) error) error { return start(host) }) + defer app.UseApplicationRunner(nil) + err := app.RunApplication(func(application *app.Application) error { + var err error + window, err = application.OpenWindow(app.Config{Title: "before", Width: 500, Height: 300}, nil) + return err + }) + if err != nil { + t.Fatal(err) + } + defer host.closeAll() + if err := window.SetTitle("after"); err != nil { + t.Fatal(err) + } + if text := run(t, host, "windows\n"); !strings.Contains(text, `title="after"`) { + t.Fatalf("windows output does not list the new title:\n%s", text) + } + for _, bad := range []string{"bad\x00title", "bad\xfftitle"} { + if err := window.SetTitle(bad); err == nil { + t.Fatalf("title %q was accepted", bad) + } + } + if text := run(t, host, "windows\n"); !strings.Contains(text, `title="after"`) { + t.Fatalf("a rejected title changed the window:\n%s", text) + } + host.closeAll() + if err := window.SetTitle("late"); err == nil { + t.Fatal("closed window accepted a title") + } +} diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index c9c89e143..391ad459a 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -145,6 +145,8 @@ func (win *window) markPanel(config platform.Config, x, y int16) error { func (state *linuxWindowState) command(command uint32, data []byte) error { win := state.win switch command { + case commandSetTitle: + win.applyPendingTitle() case commandSetSize: if len(data) < 12 || win.frame.maximized || win.minimized || win.fullscreen.Load() { return nil diff --git a/internal/platform/linux/window_identity_linux.go b/internal/platform/linux/window_identity_linux.go index 2101ce3e5..9f48bcf7d 100644 --- a/internal/platform/linux/window_identity_linux.go +++ b/internal/platform/linux/window_identity_linux.go @@ -9,20 +9,12 @@ import ( const xcbAtomWMClientMachine = 36 // setIdentity names the window and its process to the window manager: the title -// in both forms (_NET_WM_NAME is UTF-8, WM_NAME can only carry Latin-1 and is -// what older managers read), and the process id with the host it runs on, which -// is how a manager offers to end a window that stopped answering its ping. +// (see setTitle), and the process id with the host it runs on, which is how a +// manager offers to end a window that stopped answering its ping. func (win *window) setIdentity(title string) { api, connection := win.api, win.connection if title != "" { - legacy := latin1(title) - api.changeProperty(connection, xcbPropertyReplace, win.id, xcbAtomWMName, xcbAtomString, 8, uint32(len(legacy)), unsafe.Pointer(&legacy[0])) - utf8String, err := api.atom(connection, "UTF8_STRING") - name, nameErr := api.atom(connection, "_NET_WM_NAME") - if err == nil && nameErr == nil { - encoded := []byte(title) - api.changeProperty(connection, xcbPropertyReplace, win.id, name, utf8String, 8, uint32(len(encoded)), unsafe.Pointer(&encoded[0])) - } + win.setTitle(title) } if host, err := os.Hostname(); err == nil && host != "" { machine := []byte(host) @@ -33,3 +25,26 @@ func (win *window) setIdentity(title string) { } } } + +// setTitle writes the title in both forms: _NET_WM_NAME is UTF-8, WM_NAME can only +// carry Latin-1 and is what older managers read. An empty title clears both. +func (win *window) setTitle(title string) { + api, connection := win.api, win.connection + legacy := latin1(title) + api.changeProperty(connection, xcbPropertyReplace, win.id, xcbAtomWMName, xcbAtomString, 8, uint32(len(legacy)), propertyData(legacy)) + utf8String, err := api.atom(connection, "UTF8_STRING") + name, nameErr := api.atom(connection, "_NET_WM_NAME") + if err == nil && nameErr == nil { + encoded := []byte(title) + api.changeProperty(connection, xcbPropertyReplace, win.id, name, utf8String, 8, uint32(len(encoded)), propertyData(encoded)) + } +} + +// propertyData is the data pointer for a property of len(value) bytes. An empty value has +// no first byte to point at, and X11 reads nothing from the pointer when the length is zero. +func propertyData(value []byte) unsafe.Pointer { + if len(value) == 0 { + return nil + } + return unsafe.Pointer(&value[0]) +} diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 2addd094c..161f65436 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -34,8 +34,12 @@ type window struct { caretAtom uint32 closeAtom uint32 commandAtom uint32 - moveResizeAtom uint32 - cursor uint32 + // titleMu guards pendingTitle, the title SetTitle asked for that the event loop + // has not written to the window yet. + titleMu sync.Mutex + pendingTitle string + moveResizeAtom uint32 + cursor uint32 // themed is the cursor theme's loader, tried once. themed *themedCursors cursorsTried bool @@ -202,6 +206,7 @@ const ( commandEnterFullscreen commandExitFullscreen commandSetSize + commandSetTitle commandPost ) diff --git a/internal/platform/linux/window_title_linux.go b/internal/platform/linux/window_title_linux.go new file mode 100644 index 000000000..abfdf22f9 --- /dev/null +++ b/internal/platform/linux/window_title_linux.go @@ -0,0 +1,26 @@ +package linux + +import "fmt" + +// SetTitle posts the title to the X11 event loop, which writes it to the window. The +// title is kept until the loop applies it, so a later call replaces an earlier one that +// has not been applied yet. +func (window *nativeWindow) SetTitle(title string) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("linux: window is closed") + } + win := window.state.win + win.titleMu.Lock() + win.pendingTitle = title + win.titleMu.Unlock() + win.postClientMessage(win.commandAtom, commandSetTitle) + return nil +} + +// applyPendingTitle runs on the event loop: it writes the latest title SetTitle stored. +func (win *window) applyPendingTitle() { + win.titleMu.Lock() + title := win.pendingTitle + win.titleMu.Unlock() + win.setTitle(title) +} diff --git a/internal/platform/linux/window_title_linux_test.go b/internal/platform/linux/window_title_linux_test.go new file mode 100644 index 000000000..2398bb378 --- /dev/null +++ b/internal/platform/linux/window_title_linux_test.go @@ -0,0 +1,95 @@ +package linux + +import ( + "bytes" + "testing" + "unsafe" +) + +// titleProperty is one changeProperty call a title makes: the property and its bytes. +type titleProperty struct { + property uint32 + data []byte +} + +func newTitleTestWindow(t *testing.T, written *[]titleProperty) *window { + t.Helper() + atoms := map[string]uint32{"UTF8_STRING": 40, "_NET_WM_NAME": 41} + return &window{ + id: 7, + connection: 1, + commandAtom: 50, + api: &xcbAPI{ + internAtom: func(_ uintptr, _ uint8, length uint16, name *byte) xcbAtomCookie { + return xcbAtomCookie{Sequence: atoms[string(unsafe.Slice(name, int(length)))]} + }, + internAtomReply: func(_ uintptr, cookie xcbAtomCookie, _ *unsafe.Pointer) *xcbAtomReply { + return &xcbAtomReply{Atom: cookie.Sequence} + }, + changeProperty: func(_ uintptr, _ uint8, _ uint32, property uint32, _ uint32, _ uint8, length uint32, data unsafe.Pointer) xcbVoidCookie { + var value []byte + if length > 0 { + value = bytes.Clone(unsafe.Slice((*byte)(data), int(length))) + } + *written = append(*written, titleProperty{property: property, data: value}) + return xcbVoidCookie{} + }, + sendEvent: func(uintptr, uint8, uint32, uint32, *byte) xcbVoidCookie { return xcbVoidCookie{} }, + flush: func(uintptr) int32 { return 1 }, + }, + } +} + +// The title is posted to the loop, which writes WM_NAME (Latin-1, what older managers read) +// and _NET_WM_NAME (UTF-8). The loop, not the caller, touches the window. +func TestSetTitleWritesBothNamesOnTheEventLoop(t *testing.T) { + var written []titleProperty + win := newTitleTestWindow(t, &written) + window := &nativeWindow{state: &linuxWindowState{win: win}} + if err := window.SetTitle("Motty – 设置"); err != nil { + t.Fatal(err) + } + if len(written) != 0 { + t.Fatal("SetTitle wrote the window from the caller's goroutine") + } + if err := window.state.command(commandSetTitle, nil); err != nil { + t.Fatal(err) + } + if len(written) != 2 { + t.Fatalf("title wrote %d properties, want WM_NAME and _NET_WM_NAME", len(written)) + } + if want := latin1("Motty – 设置"); !bytes.Equal(written[0].data, want) || written[0].property != xcbAtomWMName { + t.Fatalf("WM_NAME = %q, want %q", written[0].data, want) + } + if want := []byte("Motty – 设置"); !bytes.Equal(written[1].data, want) || written[1].property != 41 { + t.Fatalf("_NET_WM_NAME = %q, want %q", written[1].data, want) + } +} + +// A later title replaces one the loop has not applied yet, and an empty title clears both names. +func TestSetTitleAppliesTheLatestTitleAndEmptyClears(t *testing.T) { + var written []titleProperty + win := newTitleTestWindow(t, &written) + window := &nativeWindow{state: &linuxWindowState{win: win}} + for _, title := range []string{"first", "second"} { + if err := window.SetTitle(title); err != nil { + t.Fatal(err) + } + } + if err := window.state.command(commandSetTitle, nil); err != nil { + t.Fatal(err) + } + if !bytes.Equal(written[0].data, []byte("second")) { + t.Fatalf("applied %q, want the latest title", written[0].data) + } + written = written[:0] + if err := window.SetTitle(""); err != nil { + t.Fatal(err) + } + if err := window.state.command(commandSetTitle, nil); err != nil { + t.Fatal(err) + } + if len(written) != 2 || len(written[0].data) != 0 || len(written[1].data) != 0 { + t.Fatalf("empty title wrote %v, want both names cleared", written) + } +} diff --git a/internal/platform/windows/title_windows_test.go b/internal/platform/windows/title_windows_test.go new file mode 100644 index 000000000..61bc07505 --- /dev/null +++ b/internal/platform/windows/title_windows_test.go @@ -0,0 +1,77 @@ +//go:build windows + +package windows + +import ( + "runtime" + "syscall" + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" +) + +// windowsMessage is the MSG structure the message loop reads. +type windowsMessage struct { + Hwnd uintptr + Message uint32 + WParam uintptr + LParam uintptr + Time uint32 + X, Y int32 +} + +// pumpWindowMessages dispatches what is queued for this thread, so the title the window +// thread was asked for is applied before the test reads it. +func pumpWindowMessages() { + peek := user.NewProc("PeekMessageW") + const removeMessage = 1 + var message windowsMessage + for { + if ok, _, _ := peek.Call(uintptr(unsafe.Pointer(&message)), 0, 0, 0, removeMessage); ok == 0 { + return + } + translateMessage.Call(uintptr(unsafe.Pointer(&message))) + dispatchMessage.Call(uintptr(unsafe.Pointer(&message))) + } +} + +func TestSetTitleReachesTheWindowText(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva title test", Width: 640, Height: 400, + OnResize: func(platform.Size) (platform.Frame, error) { + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + }, + }) + if err != nil { + return err + } + defer opened.Close() + window := opened.(*nativeWindow) + getText := user.NewProc("GetWindowTextW") + titleOf := func() string { + buffer := make([]uint16, 256) + length, _, _ := getText.Call(window.state.window, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer))) + return syscall.UTF16ToString(buffer[:length]) + } + if got := titleOf(); got != "Viva title test" { + t.Fatalf("opening title = %q", got) + } + const want = "Viva – 标题" + if err := window.SetTitle(want); err != nil { + t.Fatal(err) + } + pumpWindowMessages() + if got := titleOf(); got != want { + t.Fatalf("title after SetTitle = %q, want %q", got, want) + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} From cd1f2985f410abdfe6126526ffa6f2e2a35adb76 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 12:59:31 +0800 Subject: [PATCH 11/12] feat(app): carry out menu action results on the active window An application menu runs its entry outside the window's event handlers, so the focus, clipboard and repaint a command returns were dropped: choosing Find from the menu bar opened the bar while the keyboard stayed in the terminal. MenuBarItem.OnSelect now returns the gfx.EventResult a key handler returns, and the runtime applies it to the window that last became active and wakes the window for the frame that shows it. The application keeps producing results; applying focus and scheduling the repaint stay in the runtime, so Motty's menu actions only return what their commands did. The companion motty commit uses this for Find, the command palette, the assistant, the host panel, the local terminal and tab switching. --- README.md | 7 +++- app/application.go | 63 +++++++++++++++++++++++++++-- app/application_native.go | 31 +++++++++++++- app/application_test.go | 19 +++++++++ app/initial_bitmap_headless_test.go | 2 +- app/menu_bar.go | 63 +++++++++++++++++++++++++++-- app/menu_bar_result_test.go | 52 ++++++++++++++++++++++++ app/run_canvas.go | 12 +++--- docs/system-integrations.md | 2 +- 9 files changed, 233 insertions(+), 18 deletions(-) create mode 100644 app/menu_bar_result_test.go diff --git a/README.md b/README.md index 79ab7dbe3..23b258f85 100644 --- a/README.md +++ b/README.md @@ -119,8 +119,11 @@ WebView and no bundled rendering runtime. releasing it ends the request. - `Application.SetMenuBar` puts the application's own File, Edit and View menus between the system's application menu and Window menu on macOS, with key - equivalents, enablement, check marks, submenus and loop-thread callbacks; the - other desktop targets build their menus in the window with `components.Menubar`. + equivalents, enablement, check marks and submenus. An entry's action returns + the same `gfx.EventResult` a key handler does, and the runtime carries its + focus, clipboard and repaint out on the active window, so a command chosen + from the menu behaves as its shortcut does; the other desktop targets build + their menus in the window with `components.Menubar`. - `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. diff --git a/app/application.go b/app/application.go index 0bdac102f..22f613c1b 100644 --- a/app/application.go +++ b/app/application.go @@ -87,6 +87,11 @@ type Window struct { fullscreen atomic.Bool topmostMu sync.Mutex topmost atomic.Bool + // applyResult carries out a command's event result on this window. The + // native host sets it; a host without windows leaves it nil, and the result + // of a menu action has nowhere to go. + applyResult func(gfx.EventResult) bool + requestRedraw func() } // Close requests that the native window close. Closing the final window ends @@ -196,9 +201,13 @@ func (window *Window) Closed() bool { // RunApplication call. OpenWindow must be called from the startup callback or // a window callback, both of which run on the native event-loop thread. type Application struct { - host Host - mu sync.Mutex - windows map[*Window]struct{} + host Host + mu sync.Mutex + windows map[*Window]struct{} + // active is the window that last became the one the user works in, which is + // where the application menu bar's commands take effect, as a native menu's + // key equivalents do. + active *Window openedAny bool } @@ -223,8 +232,16 @@ func (application *Application) OpenWindow(config Config, canvas *gfx.Canvas) (* }) closed := func() { window.closed.Store(true) + application.forgetActive(window) forget() } + onActivate := config.OnActivate + config.OnActivate = func() { + application.setActive(window) + if onActivate != nil { + onActivate() + } + } // The runtime tracks the minimize state for every window, so Window.Minimized // answers even when the application did not ask for OnMinimize. There is no // minimize event during OpenWindow, so the zero value is the initial state. @@ -256,12 +273,52 @@ func (application *Application) OpenWindow(config Config, canvas *gfx.Canvas) (* return nil, err } window.control = control + if applier, ok := control.(interface { + applyResult(gfx.EventResult) bool + requestRedraw() + }); ok { + window.applyResult, window.requestRedraw = applier.applyResult, applier.requestRedraw + } application.mu.Lock() application.openedAny = true application.mu.Unlock() return window, nil } +// setActive records the window the user is working in. +func (application *Application) setActive(window *Window) { + application.mu.Lock() + application.active = window + application.mu.Unlock() +} + +// forgetActive clears the active window as it closes, so a menu action after it +// does not run against a window that no longer paints. +func (application *Application) forgetActive(window *Window) { + application.mu.Lock() + if application.active == window { + application.active = nil + } + application.mu.Unlock() +} + +// activeWindow is where the application menu's commands take effect: the +// window that last became active, or the only window while no activation has +// been reported. Nil when there is no such window. +func (application *Application) activeWindow() *Window { + application.mu.Lock() + defer application.mu.Unlock() + if application.active != nil && !application.active.closed.Load() { + return application.active + } + if len(application.windows) == 1 { + for window := range application.windows { + return window + } + } + return nil +} + // AddStatusItem puts an icon in the system's status area. It is called from the // startup callback or a window callback, like OpenWindow. func (application *Application) AddStatusItem(config StatusItemConfig) (*StatusItem, error) { diff --git a/app/application_native.go b/app/application_native.go index 7ba7ccb78..f47720637 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -46,7 +46,7 @@ func RunApplication(start func(*Application) error) error { type nativeHost struct{ native platform.Application } func (host nativeHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func()) (WindowControl, error) { - windowConfig, cleanup, err := prepareNativeWindow(config, canvas) + windowConfig, painter, cleanup, err := prepareNativeWindow(config, canvas) if err != nil { return nil, err } @@ -63,7 +63,34 @@ func (host nativeHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func cleanup() return nil, err } - return window, nil + // A command the runtime did not receive through an event handler, such as a + // menu action, hands its result here: the painter carries it out and the + // window's waker asks for the frame that shows it. + return resultWindow{WindowControl: window, painter: painter, waker: windowConfig.Waker}, nil +} + +// resultWindow is the control of a window whose painter can carry out an event +// result from outside an event handler. +type resultWindow struct { + WindowControl + painter *painter + waker *platform.Waker +} + +// What OpenWindow looks for in a host's window control. +var _ interface { + applyResult(gfx.EventResult) bool + requestRedraw() +} = resultWindow{} + +func (window resultWindow) applyResult(result gfx.EventResult) bool { + return window.painter.applyEventResult(result) +} + +func (window resultWindow) requestRedraw() { + if window.waker != nil { + window.waker.Wake() + } } // CanPreview says whether the adapter's windows can be a DragPreview. diff --git a/app/application_test.go b/app/application_test.go index 42edfa644..3275f8975 100644 --- a/app/application_test.go +++ b/app/application_test.go @@ -17,6 +17,9 @@ type fakeHost struct { items []*fakeStatusItem quits int reject string + // menuBar is the menu bar the application installed, already wrapped so its + // actions carry out what they did in the active window. + menuBar []Menu // badge is the label the application last put on the Dock tile. badge string // progress is the fraction the application last asked the icon to show. @@ -28,6 +31,10 @@ type fakeWindow struct { closed func() hides, shows int done bool + // applied is what an application menu action asked the window to carry + // out, in order; redraws counts the frames it asked for. + applied []gfx.EventResult + redraws int } func (window *fakeWindow) Close() { @@ -39,6 +46,13 @@ func (window *fakeWindow) Close() { func (window *fakeWindow) Hide() { window.hides++ } func (window *fakeWindow) Show() { window.shows++ } +func (window *fakeWindow) applyResult(result gfx.EventResult) bool { + window.applied = append(window.applied, result) + return !result.Focus.IsZero() +} + +func (window *fakeWindow) requestRedraw() { window.redraws++ } + // Frame is where the window's Config.Origin put it. func (window *fakeWindow) Frame() (gfx.Rect, bool) { origin := window.config.originPoint() @@ -75,6 +89,11 @@ func (host *fakeHost) SetDockBadge(text string) { host.badge = text } func (host *fakeHost) SetProgress(fraction float32) { host.progress = fraction } +func (host *fakeHost) SetMenuBar(menus []Menu) error { + host.menuBar = menus + return nil +} + func (host *fakeHost) Post(fn func()) { if fn != nil { fn() diff --git a/app/initial_bitmap_headless_test.go b/app/initial_bitmap_headless_test.go index c40ef75d2..15b1c3198 100644 --- a/app/initial_bitmap_headless_test.go +++ b/app/initial_bitmap_headless_test.go @@ -20,7 +20,7 @@ func TestPreparedWindowUploadsInitialBitmapToMetal(test *testing.T) { var canvas gfx.Canvas config.Paint(&canvas, gfx.Size{Width: 80, Height: 40}) caption = "ready" - native, cleanup, err := prepareNativeWindow(config, &canvas) + native, _, cleanup, err := prepareNativeWindow(config, &canvas) if err != nil { test.Fatal(err) } diff --git a/app/menu_bar.go b/app/menu_bar.go index e8ca146ac..01d1313c9 100644 --- a/app/menu_bar.go +++ b/app/menu_bar.go @@ -35,8 +35,13 @@ type MenuBarItem struct { Shortcut keymap.Chord // Submenu, when not empty, makes the entry open a menu of these. Submenu []MenuBarItem - // OnSelect runs on the event-loop thread when the user chooses the entry. - OnSelect func() + // OnSelect runs on the event-loop thread when the user chooses the entry and + // returns what the command did, as a key handler does. The runtime applies + // the focus, clipboard and activation it names to the window the user is + // working in and asks for the repaint it requests, so an entry that runs the + // same command as a shortcut moves the keyboard the same way. Return the + // zero result for an entry that changes nothing. + OnSelect func() gfx.EventResult } // SetMenuBar replaces the application's own menus. It is macOS-only today and @@ -54,7 +59,52 @@ func (application *Application) SetMenuBar(menus []Menu) error { if !ok { return fmt.Errorf("%w: the application menu bar", ErrUnsupported) } - return setter.SetMenuBar(menus) + return setter.SetMenuBar(application.menuBar(menus)) +} + +// menuBar copies menus, wrapping every action so the runtime carries out what +// it did on the window the user is working in. A native menu runs its entry +// outside the window's event handlers, so the result would otherwise be +// dropped, and a menu entry that runs the same command as a shortcut would not +// move the keyboard, write the clipboard or repaint. +func (application *Application) menuBar(menus []Menu) []Menu { + out := make([]Menu, len(menus)) + for index, menu := range menus { + out[index] = Menu{Title: menu.Title, Items: application.menuBarItems(menu.Items)} + } + return out +} + +func (application *Application) menuBarItems(items []MenuBarItem) []MenuBarItem { + out := make([]MenuBarItem, len(items)) + for index, item := range items { + item.Submenu = application.menuBarItems(item.Submenu) + if selectItem := item.OnSelect; selectItem != nil { + item.OnSelect = func() gfx.EventResult { + result := selectItem() + application.applyMenuResult(result) + return result + } + } + out[index] = item + } + return out +} + +// applyMenuResult carries out a menu action's result on the active window: +// the focus, clipboard and activation it names, and a repaint when it asks for +// one. A window created without Config.Invalidator has no waker, so the runtime +// cannot ask it for the frame that shows the result; such an application asks +// for its own repaint. +func (application *Application) applyMenuResult(result gfx.EventResult) { + window := application.activeWindow() + if window == nil || window.applyResult == nil { + return + } + changed := window.applyResult(result) + if (changed || result.Repaint) && window.requestRedraw != nil { + window.requestRedraw() + } } // platform menus carry a key as a character and a modifier mask, so the @@ -76,9 +126,14 @@ func platformMenuItems(items []MenuBarItem) []platform.MenuBarItem { key = strings.ToLower(string(item.Shortcut.Char)) modifiers = menuModifiers(item.Shortcut.Modifiers) } + var onSelect func() + if item.OnSelect != nil { + selectItem := item.OnSelect + onSelect = func() { selectItem() } + } out[index] = platform.MenuBarItem{ Title: item.Title, Separator: item.Separator, Disabled: item.Disabled, Checked: item.Checked, - Key: key, Modifiers: modifiers, OnSelect: item.OnSelect, Items: platformMenuItems(item.Submenu), + Key: key, Modifiers: modifiers, OnSelect: onSelect, Items: platformMenuItems(item.Submenu), } } return out diff --git a/app/menu_bar_result_test.go b/app/menu_bar_result_test.go new file mode 100644 index 000000000..b3e4ec4fb --- /dev/null +++ b/app/menu_bar_result_test.go @@ -0,0 +1,52 @@ +//go:build darwin || windows || linux + +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" +) + +// A native menu runs its entry outside the window's event handlers. What the +// action did must still reach the window the user is working in, or a Find +// chosen from the menu bar opens its bar without the keyboard. +func TestMenuActionCarriesItsResultToTheActiveWindow(t *testing.T) { + host := &fakeHost{} + useHost(t, host) + want := gfx.EventResult{Handled: true, Repaint: true, Focus: gfx.Item(7), FocusVisible: true} + if err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{Title: "menu"}, nil); err != nil { + return err + } + return application.SetMenuBar([]Menu{{ + Title: "Edit", + Items: []MenuBarItem{ + {Title: "Find", Shortcut: keymap.Chord{Char: 'f', Modifiers: gfx.ModifierMeta}, OnSelect: func() gfx.EventResult { return want }}, + {Title: "More", Submenu: []MenuBarItem{{Title: "Inside", OnSelect: func() gfx.EventResult { return gfx.EventResult{Handled: true} }}}}, + }, + }}) + }); err != nil { + t.Fatal(err) + } + window := host.windows[0] + window.config.OnActivate() // the user brings this window to the front + if got := host.menuBar[0].Items[0].OnSelect(); got != want { + t.Fatalf("menu action returned %+v, want %+v", got, want) + } + if len(window.applied) != 1 || window.applied[0] != want { + t.Fatalf("window carried out %+v, want %+v", window.applied, want) + } + if window.redraws != 1 { + t.Fatalf("menu action asked for %d repaints, want 1", window.redraws) + } + // A submenu entry is wrapped the same way, and a result that neither moves + // the focus nor asks for a repaint does not wake the window. + if got := host.menuBar[0].Items[1].Submenu[0].OnSelect(); got != (gfx.EventResult{Handled: true}) { + t.Fatalf("submenu action returned %+v", got) + } + if len(window.applied) != 2 || window.redraws != 1 { + t.Fatalf("submenu action applied=%d redraws=%d, want 2 applied and 1 repaint", len(window.applied), window.redraws) + } +} diff --git a/app/run_canvas.go b/app/run_canvas.go index c89c8e0da..784dbe0e2 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -216,13 +216,15 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, // prepareNativeWindow builds the native window for one application window. It // runs on the window loop's main thread, which the platform preferences it // reads require; a test owns the wiring through nativeWindowConfig instead. -func prepareNativeWindow(config Config, canvas *gfx.Canvas) (platform.Config, func(), error) { +// The painter is what carries out an event result the window did not receive +// from an event handler, such as an application menu action. +func prepareNativeWindow(config Config, canvas *gfx.Canvas) (platform.Config, *painter, func(), error) { normalized, err := config.normalize() if err != nil { - return platform.Config{}, nil, err + return platform.Config{}, nil, nil, err } if normalized.TextInput != nil && !nativeTextInputSupported { - return platform.Config{}, nil, fmt.Errorf("%w: native text input", ErrUnsupported) + return platform.Config{}, nil, nil, fmt.Errorf("%w: native text input", ErrUnsupported) } if canvas == nil { canvas = &gfx.Canvas{} @@ -241,7 +243,7 @@ func prepareNativeWindow(config Config, canvas *gfx.Canvas) (platform.Config, fu painter, err := newPainter(canvas, &normalized) if err != nil { cleanup() - return platform.Config{}, nil, err + return platform.Config{}, nil, nil, err } painter.setClipboardText = func(value string) { _ = nativeSetClipboardText(value) } painter.setCursor = nativeSetCursor @@ -249,5 +251,5 @@ func prepareNativeWindow(config Config, canvas *gfx.Canvas) (platform.Config, fu native, timer := nativeWindowConfig(&normalized, painter) frames = timer stopWatchingDesktop := watchDesktopSettings(canvas, native.Waker) - return native, func() { stopWatchingDesktop(); cleanup() }, nil + return native, painter, func() { stopWatchingDesktop(); cleanup() }, nil } diff --git a/docs/system-integrations.md b/docs/system-integrations.md index c6ef8dabd..f6da7f495 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -33,7 +33,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Native look (`SetNativeAppearance`) | `NSApplication.appearance`: window buttons, menus, file dialogs and native text editing follow it | nothing to do: Viva draws the window buttons | nothing to do: Viva draws the window buttons | nothing to do | | Reduced motion (`ReduceMotion`, returns `bool`) | `NSWorkspace.accessibilityDisplayShouldReduceMotion` | `SPI_GETCLIENTAREAANIMATION` | the settings portal's `reduced-motion` or `enable-animations`, else XSETTINGS `Gtk/EnableAnimations`, else KDE's `AnimationDurationFactor` of 0; a change is applied to a running canvas | `prefers-reduced-motion`, read at mount and watched with `matchMedia` | | Keep awake (`PreventSleep`) | an `IOPMAssertion` of type `PreventUserIdleSystemSleep`, named by the reason; `pmset -g assertions` lists it | a power request of type `SystemRequired`, created with the reason; `powercfg /requests` lists it | logind's `Manager.Inhibit("idle")` on the system bus, held by the returned descriptor; `systemd-inhibit --list` shows it. `ErrSleepPreventionUnavailable` without logind | `ErrSleepPreventionUnavailable`: a page cannot keep the machine awake | -| Application menu bar (`Application.SetMenuBar`) | the NSMenu bar's application and Window menus stay; the application's own menus sit between them, with their key equivalents, enablement, check marks, submenus and loop-thread actions | `ErrUnsupported`: a window's own menu bar is `components.Menubar` | `ErrUnsupported`: `components.Menubar` | `ErrUnsupported`: `components.Menubar` | +| Application menu bar (`Application.SetMenuBar`) | the NSMenu bar's application and Window menus stay; the application's own menus sit between them, with their key equivalents, enablement, check marks, submenus and actions whose event results the runtime carries out on the active window | `ErrUnsupported`: a window's own menu bar is `components.Menubar` | `ErrUnsupported`: `components.Menubar` | `ErrUnsupported`: `components.Menubar` | | System proxy (`app/proxy.SystemProxy`) | CFNetwork's settings for the URL: the static HTTP, HTTPS or SOCKS proxy with its bypass list. A PAC script is reported as `ErrSystemProxyUnavailable`, not silently bypassed | WinHTTP's automatic proxy: auto-detection (WPAD), the PAC script, or the static per-user settings | the environment only (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`); a proxy kept in GSettings is not read | `ErrSystemProxyUnavailable` | | Fullscreen (`RequestFullscreen`, `OnFullscreen`) | `NSWindow.toggleFullScreen:` | `SetWindowPos` / window style | window-manager fullscreen | `requestFullscreen` / `exitFullscreen`, reported by `fullscreenchange` | | Window title (`SetTitle`) | `NSWindow.title`, the text the window list and Mission Control show | `SetWindowTextW`, applied on the window thread | `WM_NAME` and `_NET_WM_NAME` on X11; `gtk_window_set_title` on the GTK shell | `ErrUnsupported`: the page keeps its own title | From 82a3318dd91d986fdd385535a2716030b6f120b4 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 13:31:49 +0800 Subject: [PATCH 12/12] fix(app): run menu shortcuts through the focused handler A menu's key equivalent reached its entry directly, so a command that depends on the focused control ran the wrong branch: Edit > Copy in Motty's assistant panel copied the terminal selection and ignored a selection in an assistant answer, because the shortcut handler never saw Cmd+C. Offer a menu entry's chord to the window first, as AppKit offers a key to the focused content before the menu: a character chord to the shortcut handler, a named key to the key handler, both with the focused control as the target. OnSelect runs only when that handler declines, so pressing a shortcut and choosing its entry run one command. The routing stays in the application; the runtime only supplies the focused target and carries out what the handler returned. --- app/application.go | 9 ++- app/application_native.go | 9 +++ app/application_test.go | 24 +++++++ app/menu_bar.go | 26 +++++++- app/menu_bar_result_test.go | 130 ++++++++++++++++++++++++++++++++++++ app/painter.go | 22 ++++++ docs/system-integrations.md | 2 +- 7 files changed, 219 insertions(+), 3 deletions(-) diff --git a/app/application.go b/app/application.go index 22f613c1b..86a3c92f0 100644 --- a/app/application.go +++ b/app/application.go @@ -7,6 +7,7 @@ import ( "sync/atomic" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" ) // ErrNoWindows is returned when an application startup callback returns @@ -92,6 +93,11 @@ type Window struct { // of a menu action has nowhere to go. applyResult func(gfx.EventResult) bool requestRedraw func() + // runShortcut offers a menu entry's chord to the application's shortcut + // handler with the control that holds the keyboard, as pressing the chord + // does. The native host sets it; nil means no handler and the entry's + // OnSelect runs instead. + runShortcut func(keymap.Chord) (gfx.EventResult, bool) } // Close requests that the native window close. Closing the final window ends @@ -276,8 +282,9 @@ func (application *Application) OpenWindow(config Config, canvas *gfx.Canvas) (* if applier, ok := control.(interface { applyResult(gfx.EventResult) bool requestRedraw() + runShortcut(keymap.Chord) (gfx.EventResult, bool) }); ok { - window.applyResult, window.requestRedraw = applier.applyResult, applier.requestRedraw + window.applyResult, window.requestRedraw, window.runShortcut = applier.applyResult, applier.requestRedraw, applier.runShortcut } application.mu.Lock() application.openedAny = true diff --git a/app/application_native.go b/app/application_native.go index f47720637..92d5fd25a 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -8,6 +8,7 @@ import ( "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/keymap" ) // RunApplication starts the native application loop. start runs once on the @@ -81,6 +82,7 @@ type resultWindow struct { var _ interface { applyResult(gfx.EventResult) bool requestRedraw() + runShortcut(keymap.Chord) (gfx.EventResult, bool) } = resultWindow{} func (window resultWindow) applyResult(result gfx.EventResult) bool { @@ -93,6 +95,13 @@ func (window resultWindow) requestRedraw() { } } +// runShortcut offers a menu entry's chord to the shortcut handler with the +// control that holds the keyboard, as the platform offers a key it did not +// claim itself. +func (window resultWindow) runShortcut(chord keymap.Chord) (gfx.EventResult, bool) { + return window.painter.menuShortcut(chord) +} + // CanPreview says whether the adapter's windows can be a DragPreview. func (host nativeHost) CanPreview() bool { _, ok := host.native.(interface{ SupportsDragPreview() }) diff --git a/app/application_test.go b/app/application_test.go index 3275f8975..9127b2284 100644 --- a/app/application_test.go +++ b/app/application_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" ) // fakeHost is an event loop with no windows: it records what the application @@ -31,6 +32,9 @@ type fakeWindow struct { closed func() hides, shows int done bool + // focused is the control that holds the keyboard, which a menu shortcut + // aims at before the entry's own action. + focused gfx.ID // applied is what an application menu action asked the window to carry // out, in order; redraws counts the frames it asked for. applied []gfx.EventResult @@ -53,6 +57,26 @@ func (window *fakeWindow) applyResult(result gfx.EventResult) bool { func (window *fakeWindow) requestRedraw() { window.redraws++ } +// runShortcut plays the platform offering a menu entry's chord to the +// application, as pressing the same key would deliver it. +func (window *fakeWindow) runShortcut(chord keymap.Chord) (gfx.EventResult, bool) { + if !chord.Valid() { + return gfx.EventResult{}, false + } + handler := window.config.OnKey + event := gfx.KeyEvent{Key: chord.Key, Modifiers: chord.Modifiers, Target: window.focused} + if chord.Char != 0 { + handler = window.config.OnShortcut + event.Key = gfx.KeyUnknown + event.Text = string(chord.Char) + } + if handler == nil { + return gfx.EventResult{}, false + } + response := handler(event) + return response, response.Handled +} + // Frame is where the window's Config.Origin put it. func (window *fakeWindow) Frame() (gfx.Rect, bool) { origin := window.config.originPoint() diff --git a/app/menu_bar.go b/app/menu_bar.go index 01d1313c9..c57e53374 100644 --- a/app/menu_bar.go +++ b/app/menu_bar.go @@ -31,7 +31,11 @@ type MenuBarItem struct { Checked bool // Shortcut is the key the system offers for the entry. Only a character key // is represented in a menu; a chord with a named key shows no shortcut, and - // the application still receives that key through its own handler. + // the application still receives that key through its own key handler. + // Before OnSelect runs, the chord is offered as pressing it would deliver + // it: a character chord to the shortcut handler, a named key to the key + // handler, with the focused control as the target. A handler that takes it + // owns the command. Shortcut keymap.Chord // Submenu, when not empty, makes the entry open a menu of these. Submenu []MenuBarItem @@ -80,7 +84,16 @@ func (application *Application) menuBarItems(items []MenuBarItem) []MenuBarItem for index, item := range items { item.Submenu = application.menuBarItems(item.Submenu) if selectItem := item.OnSelect; selectItem != nil { + shortcut := item.Shortcut item.OnSelect = func() gfx.EventResult { + // A menu's key equivalent is a fallback in AppKit: the focused + // content sees the chord first, and the menu entry runs only when + // nothing there takes it. A choice from the open menu goes through + // the same handler, so a click and its shortcut run one command. + if result, handled := application.runMenuShortcut(shortcut); handled { + application.applyMenuResult(result) + return result + } result := selectItem() application.applyMenuResult(result) return result @@ -91,6 +104,17 @@ func (application *Application) menuBarItems(items []MenuBarItem) []MenuBarItem return out } +// runMenuShortcut offers a menu entry's chord to the shortcut handler of the +// window the user is working in, with the control that holds the keyboard as +// the target, and reports whether the handler took it. +func (application *Application) runMenuShortcut(chord keymap.Chord) (gfx.EventResult, bool) { + window := application.activeWindow() + if window == nil || window.runShortcut == nil { + return gfx.EventResult{}, false + } + return window.runShortcut(chord) +} + // applyMenuResult carries out a menu action's result on the active window: // the focus, clipboard and activation it names, and a repaint when it asks for // one. A window created without Config.Invalidator has no waker, so the runtime diff --git a/app/menu_bar_result_test.go b/app/menu_bar_result_test.go index b3e4ec4fb..fb872b361 100644 --- a/app/menu_bar_result_test.go +++ b/app/menu_bar_result_test.go @@ -50,3 +50,133 @@ func TestMenuActionCarriesItsResultToTheActiveWindow(t *testing.T) { t.Fatalf("submenu action applied=%d redraws=%d, want 2 applied and 1 repaint", len(window.applied), window.redraws) } } + +// AppKit offers a menu's key equivalent to the focused content before the +// menu, and so does the runtime: the application's shortcut handler sees the +// chord with the focused control as its target, and the entry's own action +// runs only when that handler declines it. Choosing the entry runs the same +// command as pressing its shortcut, which is what a menu advertises. +func TestMenuShortcutReachesTheFocusedControlBeforeTheEntry(t *testing.T) { + host := &fakeHost{} + useHost(t, host) + selected := gfx.EventResult{Handled: true, ClipboardText: "selected text", Repaint: true} + var pressed gfx.KeyEvent + selectedEntry := false + if err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{ + Title: "menu", + OnShortcut: func(event gfx.KeyEvent) gfx.EventResult { + pressed = event + return selected + }, + }, nil); err != nil { + return err + } + return application.SetMenuBar([]Menu{{ + Title: "Edit", + Items: []MenuBarItem{{ + Title: "Copy", + Shortcut: keymap.Chord{Char: 'c', Modifiers: gfx.ModifierMeta}, + OnSelect: func() gfx.EventResult { + selectedEntry = true + return gfx.EventResult{} + }, + }}, + }}) + }); err != nil { + t.Fatal(err) + } + window := host.windows[0] + window.focused = gfx.Item(7) + if result := host.menuBar[0].Items[0].OnSelect(); result != selected { + t.Fatalf("menu shortcut returned %+v, want the handler's %+v", result, selected) + } + if selectedEntry { + t.Fatal("the entry's own action ran although the shortcut handler took the chord") + } + if pressed.Target != gfx.Item(7) || pressed.Text != "c" || pressed.Modifiers != gfx.ModifierMeta { + t.Fatalf("handler saw %+v, want Cmd+C aimed at the focused control", pressed) + } + if len(window.applied) != 1 || window.applied[0] != selected { + t.Fatalf("window carried out %+v, want %+v", window.applied, selected) + } + if window.redraws != 1 { + t.Fatalf("menu shortcut asked for %d repaints, want 1", window.redraws) + } +} + +func TestMenuEntryRunsWhenTheShortcutHandlerDeclines(t *testing.T) { + host := &fakeHost{} + useHost(t, host) + entry := gfx.EventResult{Handled: true, Repaint: true, Focus: gfx.Item(3)} + if err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{ + Title: "menu", + OnShortcut: func(gfx.KeyEvent) gfx.EventResult { return gfx.EventResult{} }, + }, nil); err != nil { + return err + } + return application.SetMenuBar([]Menu{{ + Title: "Edit", + Items: []MenuBarItem{{ + Title: "Find", + Shortcut: keymap.Chord{Char: 'f', Modifiers: gfx.ModifierMeta}, + OnSelect: func() gfx.EventResult { return entry }, + }}, + }}) + }); err != nil { + t.Fatal(err) + } + if got := host.menuBar[0].Items[0].OnSelect(); got != entry { + t.Fatalf("menu entry returned %+v, want %+v", got, entry) + } + window := host.windows[0] + if len(window.applied) != 1 || window.applied[0] != entry { + t.Fatalf("window carried out %+v, want %+v", window.applied, entry) + } +} + +// A named key has no menu key equivalent, so choosing its entry is how the +// menu runs it. The runtime offers it to the key handler as pressing the key +// would, and the entry's own action stays unused when the handler takes it. +func TestMenuEntryOffersANamedChordToTheKeyHandler(t *testing.T) { + host := &fakeHost{} + useHost(t, host) + copied := gfx.EventResult{Handled: true, ClipboardText: "selected text"} + var pressed gfx.KeyEvent + entryRan := false + if err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{ + Title: "menu", + OnKey: func(event gfx.KeyEvent) gfx.EventResult { + pressed = event + return copied + }, + }, nil); err != nil { + return err + } + return application.SetMenuBar([]Menu{{ + Title: "Edit", + Items: []MenuBarItem{{ + Title: "Copy", + Shortcut: keymap.Chord{Key: gfx.KeyF8}, + OnSelect: func() gfx.EventResult { + entryRan = true + return gfx.EventResult{} + }, + }}, + }}) + }); err != nil { + t.Fatal(err) + } + host.windows[0].focused = gfx.Item(4) + if got := host.menuBar[0].Items[0].OnSelect(); got != copied { + t.Fatalf("menu entry returned %+v, want the key handler's %+v", got, copied) + } + if entryRan { + t.Fatal("the entry's own action ran although the key handler took the chord") + } + if pressed.Key != gfx.KeyF8 || pressed.Target != gfx.Item(4) { + t.Fatalf("handler saw %+v, want F8 aimed at the focused control", pressed) + } +} diff --git a/app/painter.go b/app/painter.go index 687bca8be..ff02e9a72 100644 --- a/app/painter.go +++ b/app/painter.go @@ -18,6 +18,7 @@ import ( "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" "github.com/vivaui/viva/internal/semantic" + "github.com/vivaui/viva/keymap" "github.com/vivaui/viva/text" ) @@ -573,6 +574,27 @@ func normalizeShortcutText(value string) string { return value } +// menuShortcut offers a menu entry's chord to the window as the platform +// delivers the same key: a character chord to the shortcut handler, a named key +// to the key handler, both with the control that holds the keyboard as the +// target. The application decides whether the chord is its command; the caller +// carries out the result and asks for the repaint, unlike the platform's key +// path here. +func (painter *painter) menuShortcut(chord keymap.Chord) (gfx.EventResult, bool) { + event := gfx.KeyEvent{Key: chord.Key, Modifiers: chord.Modifiers, Target: painter.focus.Focused()} + handler := painter.onKey + if chord.Char != 0 { + event.Key = gfx.KeyUnknown + event.Text = normalizeShortcutText(string(chord.Char)) + handler = painter.onShortcut + } + if handler == nil || !chord.Valid() { + return gfx.EventResult{}, false + } + response := handler(event) + return response, response.Handled +} + // keysWanted reports whether the focused terminal asked for presses and // releases of every key (TextInput.KeyReleases). func (painter *painter) keysWanted() bool { diff --git a/docs/system-integrations.md b/docs/system-integrations.md index f6da7f495..b790a7f9c 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -33,7 +33,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Native look (`SetNativeAppearance`) | `NSApplication.appearance`: window buttons, menus, file dialogs and native text editing follow it | nothing to do: Viva draws the window buttons | nothing to do: Viva draws the window buttons | nothing to do | | Reduced motion (`ReduceMotion`, returns `bool`) | `NSWorkspace.accessibilityDisplayShouldReduceMotion` | `SPI_GETCLIENTAREAANIMATION` | the settings portal's `reduced-motion` or `enable-animations`, else XSETTINGS `Gtk/EnableAnimations`, else KDE's `AnimationDurationFactor` of 0; a change is applied to a running canvas | `prefers-reduced-motion`, read at mount and watched with `matchMedia` | | Keep awake (`PreventSleep`) | an `IOPMAssertion` of type `PreventUserIdleSystemSleep`, named by the reason; `pmset -g assertions` lists it | a power request of type `SystemRequired`, created with the reason; `powercfg /requests` lists it | logind's `Manager.Inhibit("idle")` on the system bus, held by the returned descriptor; `systemd-inhibit --list` shows it. `ErrSleepPreventionUnavailable` without logind | `ErrSleepPreventionUnavailable`: a page cannot keep the machine awake | -| Application menu bar (`Application.SetMenuBar`) | the NSMenu bar's application and Window menus stay; the application's own menus sit between them, with their key equivalents, enablement, check marks, submenus and actions whose event results the runtime carries out on the active window | `ErrUnsupported`: a window's own menu bar is `components.Menubar` | `ErrUnsupported`: `components.Menubar` | `ErrUnsupported`: `components.Menubar` | +| Application menu bar (`Application.SetMenuBar`) | the NSMenu bar's application and Window menus stay; the application's own menus sit between them, with their key equivalents, enablement, check marks, submenus and actions whose event results the runtime carries out on the active window. A character chord first reaches the application's shortcut handler with the focused control, and a named-key chord its key handler, as the system offers a key to the content before the menu; the entry's action runs only when that handler declines it | `ErrUnsupported`: a window's own menu bar is `components.Menubar` | `ErrUnsupported`: `components.Menubar` | `ErrUnsupported`: `components.Menubar` | | System proxy (`app/proxy.SystemProxy`) | CFNetwork's settings for the URL: the static HTTP, HTTPS or SOCKS proxy with its bypass list. A PAC script is reported as `ErrSystemProxyUnavailable`, not silently bypassed | WinHTTP's automatic proxy: auto-detection (WPAD), the PAC script, or the static per-user settings | the environment only (`HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `NO_PROXY`); a proxy kept in GSettings is not read | `ErrSystemProxyUnavailable` | | Fullscreen (`RequestFullscreen`, `OnFullscreen`) | `NSWindow.toggleFullScreen:` | `SetWindowPos` / window style | window-manager fullscreen | `requestFullscreen` / `exitFullscreen`, reported by `fullscreenchange` | | Window title (`SetTitle`) | `NSWindow.title`, the text the window list and Mission Control show | `SetWindowTextW`, applied on the window thread | `WM_NAME` and `_NET_WM_NAME` on X11; `gtk_window_set_title` on the GTK shell | `ErrUnsupported`: the page keeps its own title |