diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a2e0ae2..0242774e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -393,6 +393,10 @@ jobs: env: VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1' run: go test ./internal/platform/windows -run '^TestNativeGlobalShortcutRegistration$' -count=1 -v + - name: Native Windows clipboard transactions + env: + VIVA_WINDOWS_CLIPBOARD: '1' + run: go test ./internal/platform/windows -run '^TestColumnClipboardNative' -count=1 -v -timeout=2m - name: Native Direct2D text origins and hidden labels run: go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|HiddenNativeEditorDoesNotDrawColorEmoji|TextEngineRasterizesProportionalText)$' -count=1 -v - name: Promised file drag diff --git a/README.md b/README.md index d7ce5d63..ce30626c 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Wayland client and needs the system's GTK 3), and a Vulkan loader and driver for and DirectWrite. Viva loads the system libraries at runtime and bundles none of them. -The current release is `v0.6.8`; name it explicitly (`@v0.6.8`) to pin it. Guides, +The current release is `v0.6.9`; name it explicitly (`@v0.6.9`) 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 275e6a87..1ec501f7 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、Pango 和 Cairo 库的 X11(可选的 GTK 3 外壳用 `-tags vivagtk` 构建,是原生 Wayland 客户端,需要系统的 GTK 3),Vulkan 加载库和驱动用于 GPU 加速,缺失时窗口用 CPU 渲染;Windows 上需要 Win32、Direct3D 11 和 DirectWrite。Viva 在运行时加载系统库,自身不捆绑任何一个。 -当前版本是 `v0.6.8`;要固定版本就写明(`@v0.6.8`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 +当前版本是 `v0.6.9`;要固定版本就写明(`@v0.6.9`)。指南、API 参考和带实时预览的组件目录在 [`website/`](website/) 里,本地用 `npm run dev` 运行;也已经发布在 [vivaui.dev](https://vivaui.dev/zh/)。 下面的一切描述的都是这个仓库:它的测量、它自己的程序,以及如何开发框架本身,而不是如何用框架。 diff --git a/app/accessibility_test.go b/app/accessibility_test.go index 44be689e..423fab09 100644 --- a/app/accessibility_test.go +++ b/app/accessibility_test.go @@ -229,3 +229,36 @@ func TestRegionsNeverReportTheKeyboard(t *testing.T) { t.Errorf("region = %+v", painter.accessibility[0]) } } + +func TestSyncSemanticsUpdatesZeroIDContainerOnIncrementalPaint(t *testing.T) { + var canvas gfx.Canvas + width := float32(912) + role := gfx.RoleStatus + label := "Loading" + config := Config{ + Title: "a11y-container-incremental", + Width: 960, + Height: 200, + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.ContainerWithOptions(gfx.Rect{Width: width, Height: 24}, role, label, gfx.HitOptions{Level: 1}) + canvas.HitWithLabel(gfx.Item(1), gfx.Rect{Y: 40, Width: 80, Height: 24}, "Save") + }, + } + driver, err := NewDriver(config, &canvas) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + + // Frame 2: only the zero-ID container changes bounds, role and label; hit count and IDs stay identical. + width = 904 + role = gfx.RoleGroup + label = "Article A" + if err := driver.redraw(); err != nil { + t.Fatal(err) + } + nodes := driver.Accessibility() + if len(nodes) == 0 || nodes[0].Bounds.Width != 904 || nodes[0].Role != gfx.RoleGroup || nodes[0].Label != "Article A" { + t.Fatalf("stale zero-ID container accessibility node: %+v", nodes) + } +} diff --git a/app/fonts.go b/app/fonts.go index 9ef67472..f4ef1d2e 100644 --- a/app/fonts.go +++ b/app/fonts.go @@ -11,10 +11,11 @@ import ( // system, sorted and without duplicates. An application offers them to the user // and gives the chosen one to gfx.MonoFamily to draw terminal text in it. // -// What counts as monospace follows the platform. macOS and Windows measure -// each family and offer every one whose printable ASCII characters share one -// advance width, including coding families that do not set the fixed-pitch -// flag; the other platforms list what the system declares fixed-pitch. +// What counts as monospace follows the platform. macOS, Windows and Linux +// measure each family and offer every one whose printable ASCII characters +// share one advance width, including coding families that do not set the +// fixed-pitch flag; Linux without Pango, and the other platforms, list what the +// system declares fixed-pitch. // // The list is read from the system on every call and takes a moment, since a // family is measured rather than taken at its word, so it is for a settings diff --git a/app/painter.go b/app/painter.go index ca46d833..2fb0c0dd 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1764,7 +1764,10 @@ func (painter *painter) syncSemantics(incremental bool) (changed bool) { fast = false break } - if *current != *previous && !current.ID.IsZero() { + if *current != *previous { + // A zero ID is tracked like any other: it marks every zero-ID + // node (headings, groups, live regions) for a rebuild below, and + // matches nothing for an occluder or drag region, which has none. known := false for _, id := range dirty { if id == current.ID { diff --git a/base/state_types.go b/base/state_types.go index 0eb803ab..975b5122 100644 --- a/base/state_types.go +++ b/base/state_types.go @@ -19,6 +19,8 @@ type ColorPickerIDs struct { type ColorPickerLabels struct { Color, Saturation, Hue, Alpha, Hex, Clear, Cancel, Apply string + // InvalidColor is the message shown for an invalid Hex value. + InvalidColor string } // ColorPickerLayout is also the input geometry. Pointer and Key update a copy diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index 984d1dd8..a99ef143 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -58,12 +58,15 @@ type CodeEditorFoldRange struct { } // CodeEditorFoldMarker adds a disclosure button to a visible logical line. -// The caller owns its ID and handles clicks. Markers must be sorted by Line. +// The caller owns its ID and handles clicks. PlaceholderID, when nonzero, +// exposes the inline "..." badge on a folded header line as a button too. +// Markers must be sorted by Line. type CodeEditorFoldMarker struct { - Line int - ID gfx.ID - Collapsed bool - Label string + Line int + ID gfx.ID + PlaceholderID gfx.ID + Collapsed bool + Label string } // CodeEditorMaxHighlightedLine is the longest line, in bytes, that is handed to @@ -713,6 +716,47 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. } canvas.Unclip() } + if len(editor.folds) > 0 && len(snapshot.FoldMarkers) != 0 { + canvas.Clip(content) + markerIndex := 0 + if firstRow < len(editor.rows) { + firstLine := int(editor.rows[firstRow].line) + markerIndex = sort.Search(len(snapshot.FoldMarkers), func(i int) bool { return snapshot.FoldMarkers[i].Line >= firstLine }) + } + left := content.X - editor.scrollX + for index := firstRow; index < len(editor.rows); index++ { + y := content.Y + float32(index)*lineHeight - editor.scrollY + if y >= content.Y+content.Height { + break + } + row := editor.rows[index] + if editor.softWrapped(index) || !editor.isFoldHeader(int(row.line)) { + continue + } + for markerIndex < len(snapshot.FoldMarkers) && snapshot.FoldMarkers[markerIndex].Line < int(row.line) { + markerIndex++ + } + if markerIndex >= len(snapshot.FoldMarkers) || snapshot.FoldMarkers[markerIndex].Line != int(row.line) { + continue + } + marker := snapshot.FoldMarkers[markerIndex] + if marker.PlaceholderID.IsZero() { + continue + } + badge := foldBadgeRect(row, y, left, cellWidth, lineHeight, cellHeight) + if badge.X+badge.Width <= content.X || badge.X >= content.X+content.Width { + continue + } + label := marker.Label + if label == "" { + label = "Expand fold" + } + canvas.HitWithOptions(marker.PlaceholderID, badge, label, gfx.HitOptions{ + Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Disabled: snapshot.Disabled, + }) + } + canvas.Unclip() + } if !snapshot.ScrollbarID.IsZero() { area := BeginScrollArea(canvas, theme, gfx.Rect{X: bounds.X + bounds.Width - codeEditorBarSize - 1, Y: content.Y, Width: 10, Height: content.Height}, gfx.Size{Width: 10, Height: float32(len(editor.rows)) * lineHeight}).Offset(0, editor.scrollY).VerticalScrollbar(snapshot.ScrollbarID, snapshot.Label, "") @@ -1052,6 +1096,9 @@ func (paint *codePaint) row(index int, y float32) { (paint.value[rowEnd] == '\n' || paint.value[rowEnd] == '\r' && rowEnd+1 < len(paint.value) && paint.value[rowEnd+1] == '\n') { paint.lineEnding(row, y, left) } + if !editor.softWrapped(index) && editor.isFoldHeader(int(row.line)) { + paint.foldBadge(row, y, left) + } if paint.showWrapSymbol && editor.softWrapped(index) { paint.wrapSymbol(y) } @@ -1061,6 +1108,45 @@ func (paint *codePaint) row(index int, y float32) { } } +func (editor *CodeEditor) isFoldHeader(line int) bool { + if len(editor.folds) == 0 { + return false + } + index := sort.Search(len(editor.folds), func(i int) bool { return editor.folds[i].Header >= line }) + return index < len(editor.folds) && editor.folds[index].Header == line +} + +func foldBadgeRect(row codeRow, y, left, cellWidth, lineHeight, cellHeight float32) gfx.Rect { + width := max(float32(18), cellWidth*3.5) + height := max(float32(12), cellHeight-2) + return gfx.Rect{ + X: left + float32(row.cells)*cellWidth + cellWidth*0.5, + Y: y + (lineHeight-height)/2, + Width: width, + Height: height, + } +} + +func (paint *codePaint) foldBadge(row codeRow, y, left float32) { + badge := foldBadgeRect(row, y, left, paint.cellWidth, paint.lineHeight, paint.cellHeight) + bg := paint.muted + bg.Alpha *= 0.16 + fg := paint.muted + if paint.editor.disabled { + bg.Alpha *= 0.5 + fg.Alpha *= 0.5 + } + paint.canvas.Rounded(badge, 3, bg) + textBounds := gfx.Rect{ + X: badge.X + max(0, (badge.Width-paint.cellWidth*3)/2), + Y: y + (paint.lineHeight-paint.cellHeight)/2, + Width: paint.cellWidth * 3, + Height: paint.cellHeight, + } + runs := [1]gfx.TextRun{{Column: 0, Bytes: 3, Cells: 3, Color: fg}} + paint.canvas.LabelRuns("...", textBounds, gfx.TextStyle{Size: paint.size, Color: fg, Mono: true, MonoFace: paint.face}, paint.cellWidth, runs[:]) +} + func (paint *codePaint) wrapSymbol(y float32) { content := paint.editor.content paint.canvas.Label("↪", gfx.Rect{ diff --git a/components/code_editor.go b/components/code_editor.go index aff34054..242b1615 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -58,12 +58,15 @@ type CodeEditorFoldRange struct { } // CodeEditorFoldMarker adds a disclosure button to a visible logical line. -// The caller owns its ID and handles clicks. Markers must be sorted by Line. +// The caller owns its ID and handles clicks. PlaceholderID, when nonzero, +// exposes the inline "..." badge on a folded header line as a button too. +// Markers must be sorted by Line. type CodeEditorFoldMarker struct { - Line int - ID gfx.ID - Collapsed bool - Label string + Line int + ID gfx.ID + PlaceholderID gfx.ID + Collapsed bool + Label string } // CodeEditorMaxHighlightedLine is the longest line, in bytes, that is handed to @@ -713,6 +716,47 @@ func (editor *CodeEditor) Paint(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx. } canvas.Unclip() } + if len(editor.folds) > 0 && len(snapshot.FoldMarkers) != 0 { + canvas.Clip(content) + markerIndex := 0 + if firstRow < len(editor.rows) { + firstLine := int(editor.rows[firstRow].line) + markerIndex = sort.Search(len(snapshot.FoldMarkers), func(i int) bool { return snapshot.FoldMarkers[i].Line >= firstLine }) + } + left := content.X - editor.scrollX + for index := firstRow; index < len(editor.rows); index++ { + y := content.Y + float32(index)*lineHeight - editor.scrollY + if y >= content.Y+content.Height { + break + } + row := editor.rows[index] + if editor.softWrapped(index) || !editor.isFoldHeader(int(row.line)) { + continue + } + for markerIndex < len(snapshot.FoldMarkers) && snapshot.FoldMarkers[markerIndex].Line < int(row.line) { + markerIndex++ + } + if markerIndex >= len(snapshot.FoldMarkers) || snapshot.FoldMarkers[markerIndex].Line != int(row.line) { + continue + } + marker := snapshot.FoldMarkers[markerIndex] + if marker.PlaceholderID.IsZero() { + continue + } + badge := foldBadgeRect(row, y, left, cellWidth, lineHeight, cellHeight) + if badge.X+badge.Width <= content.X || badge.X >= content.X+content.Width { + continue + } + label := marker.Label + if label == "" { + label = "Expand fold" + } + canvas.HitWithOptions(marker.PlaceholderID, badge, label, gfx.HitOptions{ + Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Disabled: snapshot.Disabled, + }) + } + canvas.Unclip() + } if !snapshot.ScrollbarID.IsZero() { area := BeginScrollArea(canvas, theme, gfx.Rect{X: bounds.X + bounds.Width - codeEditorBarSize - 1, Y: content.Y, Width: 10, Height: content.Height}, gfx.Size{Width: 10, Height: float32(len(editor.rows)) * lineHeight}).Offset(0, editor.scrollY).VerticalScrollbar(snapshot.ScrollbarID, snapshot.Label, "") @@ -1052,6 +1096,9 @@ func (paint *codePaint) row(index int, y float32) { (paint.value[rowEnd] == '\n' || paint.value[rowEnd] == '\r' && rowEnd+1 < len(paint.value) && paint.value[rowEnd+1] == '\n') { paint.lineEnding(row, y, left) } + if !editor.softWrapped(index) && editor.isFoldHeader(int(row.line)) { + paint.foldBadge(row, y, left) + } if paint.showWrapSymbol && editor.softWrapped(index) { paint.wrapSymbol(y) } @@ -1061,6 +1108,45 @@ func (paint *codePaint) row(index int, y float32) { } } +func (editor *CodeEditor) isFoldHeader(line int) bool { + if len(editor.folds) == 0 { + return false + } + index := sort.Search(len(editor.folds), func(i int) bool { return editor.folds[i].Header >= line }) + return index < len(editor.folds) && editor.folds[index].Header == line +} + +func foldBadgeRect(row codeRow, y, left, cellWidth, lineHeight, cellHeight float32) gfx.Rect { + width := max(float32(18), cellWidth*3.5) + height := max(float32(12), cellHeight-2) + return gfx.Rect{ + X: left + float32(row.cells)*cellWidth + cellWidth*0.5, + Y: y + (lineHeight-height)/2, + Width: width, + Height: height, + } +} + +func (paint *codePaint) foldBadge(row codeRow, y, left float32) { + badge := foldBadgeRect(row, y, left, paint.cellWidth, paint.lineHeight, paint.cellHeight) + bg := paint.muted + bg.Alpha *= 0.16 + fg := paint.muted + if paint.editor.disabled { + bg.Alpha *= 0.5 + fg.Alpha *= 0.5 + } + paint.canvas.Rounded(badge, 3, bg) + textBounds := gfx.Rect{ + X: badge.X + max(0, (badge.Width-paint.cellWidth*3)/2), + Y: y + (paint.lineHeight-paint.cellHeight)/2, + Width: paint.cellWidth * 3, + Height: paint.cellHeight, + } + runs := [1]gfx.TextRun{{Column: 0, Bytes: 3, Cells: 3, Color: fg}} + paint.canvas.LabelRuns("...", textBounds, gfx.TextStyle{Size: paint.size, Color: fg, Mono: true, MonoFace: paint.face}, paint.cellWidth, runs[:]) +} + func (paint *codePaint) wrapSymbol(y float32) { content := paint.editor.content paint.canvas.Label("↪", gfx.Rect{ diff --git a/components/code_editor_fold_test.go b/components/code_editor_fold_test.go index c435afb5..ec92c627 100644 --- a/components/code_editor_fold_test.go +++ b/components/code_editor_fold_test.go @@ -143,3 +143,51 @@ func TestCodeEditorHiddenOffsetTakesTheFoldHeaderRow(t *testing.T) { t.Fatalf("visible offset y = %v, ok = %v, want %v", got, ok, want) } } + +func TestCodeEditorFoldedHeaderDrawsEllipsisBadgeAndExposesPlaceholderHit(t *testing.T) { + value := "abcdefghijabcdefghij\ninside\nafter" + fixture := newCodeFixture(value) + fixture.bounds.Width = fixture.widthFor(12) + codeEditorBarSize + fixture.snapshot.Wrap = true + fixture.snapshot.FoldGutter = true + fixture.snapshot.FoldedLines = []CodeEditorFoldRange{{Header: 0, LastLine: 1}} + fixture.snapshot.FoldMarkers = []CodeEditorFoldMarker{ + {Line: 0, ID: gfx.Item(30), PlaceholderID: gfx.Item(31), Collapsed: true, Label: "Expand block"}, + } + fixture.paint() + + ellipsisCount := 0 + for _, item := range fixture.canvas.Texts() { + if item.Value == "..." { + ellipsisCount++ + } + } + if ellipsisCount != 1 { + t.Fatalf("ellipsis label count = %d, want 1", ellipsisCount) + } + + hits := map[gfx.ID]gfx.Hit{} + for _, hit := range fixture.canvas.Hits() { + hits[hit.ID] = hit + } + badgeHit, ok := hits[gfx.Item(31)] + if !ok || badgeHit.Role != gfx.RoleButton || badgeHit.Label != "Expand block" { + t.Fatalf("placeholder hit = %+v, ok=%v", badgeHit, ok) + } + if badgeHit.Bounds.X <= fixture.editor.content.X || badgeHit.Bounds.Y < fixture.editor.content.Y+fixture.editor.lineHeight { + t.Fatalf("placeholder badge expected on second wrapped row of header, got %+v", badgeHit.Bounds) + } +} + +func TestCodeEditorFoldEllipsisSteadyPaintDoesNotAllocate(t *testing.T) { + fixture := newCodeFixture("head\ninside\nafter") + fixture.snapshot.FoldGutter = true + fixture.snapshot.FoldedLines = []CodeEditorFoldRange{{Header: 0, LastLine: 1}} + fixture.snapshot.FoldMarkers = []CodeEditorFoldMarker{ + {Line: 0, ID: gfx.Item(30), PlaceholderID: gfx.Item(31), Collapsed: true}, + } + fixture.paint() + if allocations := testing.AllocsPerRun(50, fixture.paint); allocations != 0 { + t.Fatalf("steady fold-ellipsis paint allocated %g times", allocations) + } +} diff --git a/docs/releases/0.6.9.md b/docs/releases/0.6.9.md new file mode 100644 index 00000000..ba9ea8e7 --- /dev/null +++ b/docs/releases/0.6.9.md @@ -0,0 +1,93 @@ +v0.6.9 是 v0.6.8 之后的版本:组件目录补上一批页面级组件(步骤条、描述列表、时间线、评分、数字输入、日期与时间选择、穿梭框、警告条、标签、面包屑、卡片、空状态、结果页、分页、气泡确认、可关闭标签条、上传、图片预览、@ 提示、新手引导、锚点目录与评论),页面控件补上环状与分段进度、按钮与开关的忙碌态、表格的列标题与排序筛选勾选、文本计数与系统编辑菜单;加入系统拖入与拖出文件、Windows 与 Linux 的透明窗口合成、系统验证,以及可中断的弹簧与位移动画,并修复大量 Linux、Windows 与 macOS 的输入、剪贴板和绘制问题。macOS 是参考平台。 + +v0.6.9 comes after v0.6.8: the component catalog gains a set of page-level packages (a step bar, a labelled-values list, a timeline, a star rating, a number field, date and time pickers, a two-list transfer, an alert, a tag, a breadcrumb, a card, an empty state, a result page, a pagination row, a popconfirm, an editable tab strip, an upload area, an image preview, mentions, a guided tour, an anchor table of contents and comments), the page controls gain ring and segmented progress, busy buttons and switches, table column titles with sorting, filtering and checking, text counting and the system's own edit menu; files drag into and out of a window, Transparent windows composite on Windows and Linux, system authentication arrives, and interruptible spring motion joins the element tree, with many Linux, Windows and macOS input, clipboard and painting fixes. macOS is the reference platform. + +## 拿到它 · Getting it + +`go get github.com/vivaui/viva@v0.6.9`,需要 Go 1.26 或更新;系统依赖与 v0.6.8 相同。每个 Release 附带 `viva` 命令的预编译压缩包、`SHA256SUMS`,以及 Homebrew 与 Scoop 清单(`brew install vivaui/tap/viva`,或 `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` 后 `scoop install viva`)。 + +`go get github.com/vivaui/viva@v0.6.9` needs Go 1.26 or newer; the system requirements are those of v0.6.8. 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`). + +## 有什么 · What is in it + +- `ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker` 与 `ui/transfer` 是可选的页面包,用页面自己的原语搭建,跟随页面的主题与密度。 +- `ui/alert`、`ui/tag` 与 `ui/result` 用共享的 `ui.Status`(default、success、warning、danger)表示结果;`Theme.Warning` 与 `WarningColor` 补上警告色,手工构造且没有设它的主题回退到危险色。 +- `ui/card` 是带可选页眉(标题、说明与末尾插槽)与页脚、紧凑尺寸和扁平形式的卡片;`ui/empty` 把图标、标题、可换行的说明与下一步操作居中。 +- `ui/breadcrumb` 把路径上更早的位置做成链接,`Max` 非零时把中间的层级折进一个省略号菜单;`ui/pagination` 从总数和 `State` 自己拼出页码、上一页与下一页、总数、每页条数与跳转。 +- `ui/popconfirm` 在被按下的按钮旁问一句,在交付按下的那一帧报告 `Confirmed` 或 `Cancelled`,Escape 与外部按下不回答;`ui/editabletabs` 是每个标签按标题宽度、带关闭与新增按钮、超出宽度会滚动并保持活动标签可见的标签条。 +- `ui/upload` 是带系统选择器按钮的拖放区,每个文件一行状态、进度、重试与移除,控件只报告 `Added`、`Rejected`、`Removed` 与 `Retried`;`Box.DropFiles` 与 `FileDropState` 让页面声明接受系统文件拖放的区域,`ui.Configure` 先把文件交给该区域,再交给应用自己的 `OnFileDrop`,`ui.OpenFiles` 包装系统选择器,`FileRef.Path` 与 `ui.FilePath` 在平台有时给出文件路径。 +- `ui/imagepreview` 在图片上打开预览对话框,带缩小、放大、适应与原始尺寸按钮,滚轮、`+`/`-`/`0` 与拖动平移都可用。 +- `ui/mentions` 在输入触发字符后列出候选,方向键、Enter、Tab 与 Escape 操作,选中后替换掉键入的词而不把键盘从字段拿走。 +- `ui/tour` 一次在一个控件旁显示一步说明并把窗口其余部分变暗,只有 Finish 算完成,找不到控件的步骤退化成普通说明;`ui/anchor` 是带当前章节标记的页内目录;`ui/comment` 排头像、作者、时间、正文、应用自己的操作按钮与嵌套回复。 +- `ui/divider` 是中间或靠端带字的横线;`ui/typography` 把文本截断到指定的几行,需要时展开,并用新加的 `ui.SetClipboardText` 把全文复制到剪贴板。 +- `ui/validate` 提供 `Required`、`MinLength`、`MaxLength`、`Min`、`Max`、`Pattern`、`Email`、`URL` 等带类型与自定义消息的规则,`Check` 取第一个失败,`Apply` 写进 `FormFieldState`;`ui.MaxLength(n)` 与 `ui.ShowCount()` 限制并显示文本字段的字符数。 +- 进度可以画成环(`Box.Circle`)或分段(`Box.Segments`),并按 `Box.Status` 取成功、警告或危险色;`gfx.PathBuilder.Arc` 用三次曲线画圆弧。 +- 按钮与开关都能进入忙碌态(`Box.Loading`),忙碌期间不上报也不响应按下,加载指示由页面作为 painter 提供,只用按钮不会把指示器链接进来。 +- 滑块在轨道上放带文字的刻度(`Box.Marks`);`Box.Warning` 让文本控件用警告色描边而不算校验失败;`ui.SelectGroups` 在选项列表里为每组加一行标题。 +- `ui.Table` 的每个 `TableColumn` 自带 `Title` 与 `Sortable`;`TableSpec.Checked` 与 `Selection` 加一列勾选框与表头全选,`TableColumn.Filterable` 在表头给出筛选按钮并由 `Box.FilterClicked` 报告。 +- 树的分支加载中可以用 `TreeNode.Loading` 把箭头换成指示器,这期间不响应按下,所以不会开始第二次请求。 +- 文本字段的二次按下打开系统的剪切、复制、粘贴与全选菜单(macOS 与 Windows),命令与键盘快捷键走同一条路径,密码不会被复制;Linux 与只读字段由页面自己画同样的菜单,词表来自 `Config.TextMenu`,与 `PageConfig.EditMenu` 共用。 +- `components` 的 toast 更紧凑,新增 `Toaster.Timeout`、`Toaster.Limit`、`ToastConfig{Action, Timeout, HideClose}`、`ShowConfig` 与 `ToastQueue.AddFor`,可以按窗口设策略、按条设动作与超时。 +- `Config.Transparent` 直接声明透明窗口,`CapabilityTransparentWindow` 报告平台是否支持,`OnTransparentChange` 在窗口创建后告诉应用桌面是否真的透出来;Windows 用 DirectComposition 合成,Linux 的 X11 外壳在有合成管理器时也可透明。 +- `app/systemauth` 用 Windows Hello 或 macOS 的 Touch ID/设备密码验证用户,`ContentWindow.SetConcealed` 在验证时盖住内容窗口。 +- 文件可以从窗口拖到其他程序:`StartFileDrag` 拖已经存在的路径,`FilePromise` 与 `StartFilePromiseDrag` 拖在放下时才生成的内容,例如从远端服务器下载的文件;`base.DragState.OnMove` 让页面驱动的拖动越过窗口边界。 +- `MenuItem.Toggled` 让菜单项切换设置而菜单保持打开;`OpenDirectoryOptions.InitialDirectory` 让原生文件夹选择器从指定目录开始;`WebView.ShowDevTools` 打开内嵌页面的开发者工具。 +- 元素树可以做出入与移动动画:`Box.Pose` 用弹簧或曲线移动、缩放、旋转与淡出单个元素(`Pose.Rotate` 连文字一起转),`Box.Glide` 从上一帧的位置滑到新的布局位置,`Box.Presence` 让被移除的元素淡出,列表与树的 `Glide` 让键控的行滑到新位置。 +- `gfx.SpringMotion` 是保留速度、可以在途中改目标的弹簧,`gfx.VelocityTracker`、`gfx.Project`、`gfx.Nearest`、`gfx.RubberBand` 与 `Canvas.Throw` 组成甩动、吸附与越界回弹,`gfx.RadiusOutset` 让外扩的焦点环与卡片在圆角为零时保持直角。 +- `Surface.Pixel` 读取保留表面上一个点的蓝、绿、红与 alpha,以及它是否在图内;它只读已经保留的块,O(1) 且不分配,应用可以据此画出与底下像素反色的指针。 +- Linux 剪贴板与选择:等待刚获得焦点的剪贴板所有者 (contributed by @szmcdull) (PR [#436](https://github.com/vivaui/viva/pull/436));X11 选择等待被中断时重试,PRIMARY 与 AT-SPI 只复制选中的文本 (contributed by @caichangqing1120) (PR [#448](https://github.com/vivaui/viva/pull/448), [#433](https://github.com/vivaui/viva/pull/433), [#434](https://github.com/vivaui/viva/pull/434))。 +- X11 文件拖放期间保留重绘 (contributed by @caichangqing1120) (PR [#447](https://github.com/vivaui/viva/pull/447)),GTK Wayland 在内容指针进入时保留预编辑 (contributed by @caichangqing1120) (PR [#421](https://github.com/vivaui/viva/pull/421))。 +- macOS 在非主线程启动时立即失败而不是挂起 (contributed by @Ezreal-byte) (PR [#435](https://github.com/vivaui/viva/pull/435));Windows 在读取 PNG 剪贴板失败时回退到 DIB (contributed by @DeanCen) (PR [#441](https://github.com/vivaui/viva/pull/441))。 +- `textview` 在请求的滚动行于当前帧绘制 (contributed by @1lck) (PR [#450](https://github.com/vivaui/viva/pull/450));文本域的自定义绘制保留选中文本 (contributed by @imjakey) (PR [#442](https://github.com/vivaui/viva/pull/442))。 +- `dbusmenu` 首次读取构建的布局不再报告为变化。 +- 更新后,安装器在 Windows 的「程序和功能」里写入新的版本与安装大小,包管理器不再反复提供同一个更新。 +- `viva feed` 并行切更新补丁,`--patch-max-ratio` 可以丢弃大到不值得下载的补丁;`viva init` 的组件模板刷新;组件页面的 API 表格由 `api.json` 生成。 +- headless 的 macOS 截图可以用 `VIVA_HEADLESS_METAL_DEVICE=low-power` 在双显卡的 Intel Mac 上使用集成显卡 (contributed by @shubo83) (PR [#437](https://github.com/vivaui/viva/pull/437))。 + +- `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker` and `ui/transfer` are opt-in page packages built from the page's own primitives, so they follow the page's theme and density. +- `ui/alert`, `ui/tag` and `ui/result` report an outcome in the shared `ui.Status` vocabulary (default, success, warning, danger); `Theme.Warning` and `WarningColor` add the warning color, falling back to the danger color for a hand-built theme that leaves it zero. +- `ui/card` is a raised surface with an optional header (title, description and a slot at its end) and footer, a compact size and a flat form; `ui/empty` centers an icon, a title, a wrapping description and a slot for the next step. +- `ui/breadcrumb` makes each earlier place a link and `Max` folds the middle places behind an ellipsis menu; `ui/pagination` builds the page numbers, previous and next, total, page size and jump field from a total and a `State`. +- `ui/popconfirm` asks by a pressed button and reports `Confirmed` or `Cancelled` in the paint that delivers the press, with Escape and an outside press closing it without an answer; `ui/editabletabs` is a tab strip as wide as its titles with close and add buttons that scrolls and keeps the active tab in view. +- `ui/upload` is a drop area with the system picker button and one row per file with its status, progress, retry and remove; `Box.DropFiles` with a `FileDropState` declares an area that takes files dragged from the system, `ui.Configure` gives the window's `OnFileDrop` to that area before the application's own handler, `ui.OpenFiles` wraps the system picker, and `FileRef.Path` and `ui.FilePath` give a file's path where the platform has one. +- `ui/imagepreview` opens a preview dialog over a picture with zoom out, zoom in, fit and actual-size buttons, the wheel, `+`/`-`/`0` and drag to pan. +- `ui/mentions` lists matching options after a trigger character, driven by the arrow keys, Enter, Tab and Escape, and writes the chosen option in place of the typed word without taking the keyboard from the field. +- `ui/tour` shows one step beside one control with the rest of the window dimmed; only Finish counts as finishing, and a step whose control is absent is shown as a plain note. `ui/anchor` is an in-page table of contents with a rail marking the section in view, and `ui/comment` lays out an avatar, author, time, text, the page's own actions and nested replies. +- `ui/divider` is a rule with a label in the middle or near an end; `ui/typography` cuts text to the given number of lines, expands it on request, and copies the whole text with the new `ui.SetClipboardText`. +- `ui/validate` provides `Required`, `MinLength`, `MaxLength`, `Min`, `Max`, `Pattern`, `Email` and `URL` rules with caller-supplied messages, `Check` for the first failure and `Apply` to set a `FormFieldState`; `ui.MaxLength(n)` and `ui.ShowCount()` cap and show a text field's character count. +- A Progress draws as a ring (`Box.Circle`) or in segments (`Box.Segments`) and takes the success, warning or danger color from `Box.Status`; `gfx.PathBuilder.Arc` draws circular arcs as cubic curves. +- A Button and a Switch take a busy state (`Box.Loading`) that reports and answers no press while it is on, with the indicator supplied by the page as a painter so a plain button does not link it in. +- A Slider shows a dot and a word at each mark (`Box.Marks`); `Box.Warning` gives a text control a warning border without calling it invalid; `ui.SelectGroups` puts a heading row before each group of a Select's options. +- Each `TableColumn` of a `ui.Table` carries its own `Title` and `Sortable`; `TableSpec.Checked` with a `Selection` adds a column of checkboxes and a header checkbox, and `TableColumn.Filterable` adds a filter button to a heading that `Box.FilterClicked` reports. +- A tree branch whose children are loading shows `TreeNode.Loading` in place of its chevron and takes no press there, so a second press cannot start a second fetch. +- A secondary press on a text field opens the system's own Cut, Copy, Paste and Select All menu on macOS and Windows, with each command on the same path as its keyboard chord and a secret never cut or copied; Linux and read-only fields draw the same menu in the page, with the words from `Config.TextMenu`, shared with `PageConfig.EditMenu`. +- The `components` toast is more compact, and `Toaster.Timeout`, `Toaster.Limit`, `ToastConfig{Action, Timeout, HideClose}`, `ShowConfig` and `ToastQueue.AddFor` set the policy for a window and the action and timeout for one toast. +- `Config.Transparent` names the request for a transparent window, `CapabilityTransparentWindow` reports whether the platform has one, and `OnTransparentChange` tells the application once the window exists whether the desktop shows through it; Windows composites it with DirectComposition, and the X11 shell on Linux does too where a compositing manager owns the screen. +- `app/systemauth` verifies the user with Windows Hello or macOS Touch ID and the device password, and `ContentWindow.SetConcealed` conceals an application's content windows while it does. +- Files drag out of a window: `StartFileDrag` takes paths that exist, and `FilePromise` with `StartFilePromiseDrag` takes files the application produces when the target asks, such as one downloaded from a remote server; `base.DragState.OnMove` lets a page-driven drag continue past the window. +- `MenuItem.Toggled` changes a setting without closing the menu, `OpenDirectoryOptions.InitialDirectory` starts a native folder picker in a given folder, and `WebView.ShowDevTools` opens the developer tools of an embedded page. +- The element tree animates entrances, exits and moves: `Box.Pose` moves, scales, turns and fades one element about its centre with a spring or a curve (`Pose.Rotate` turns its text too), `Box.Glide` slides an element from where the last frame painted it to where the layout now puts it, `Box.Presence` fades a removed element out, and `Glide` on a list or tree slides its keyed rows to their new places. +- `gfx.SpringMotion` is a closed-form spring that keeps its velocity when the target changes on the way; `gfx.VelocityTracker`, `gfx.Project`, `gfx.Nearest`, `gfx.RubberBand` and `Canvas.Throw` give a drag its release speed, snap point and pull past a range; and `gfx.RadiusOutset` keeps outset focus rings and cards square when the radius is zero. +- `Surface.Pixel` reads one point of a retained surface as blue, green, red and alpha, and whether the point is inside it; it reads the retained tiles in O(1) without allocating, so an application can draw a pointer that inverts the pixels under it. +- Linux clipboard and selection: the clipboard owner is waited for just after focus (contributed by @szmcdull) (PR [#436](https://github.com/vivaui/viva/pull/436)), an interrupted X11 selection wait is retried, and X11 PRIMARY and AT-SPI copy only the selected text (contributed by @caichangqing1120) (PR [#448](https://github.com/vivaui/viva/pull/448), [#433](https://github.com/vivaui/viva/pull/433), [#434](https://github.com/vivaui/viva/pull/434)). +- An X11 file drop keeps its redraws (contributed by @caichangqing1120) (PR [#447](https://github.com/vivaui/viva/pull/447)), and the GTK Wayland preedit survives the content pointer entering (contributed by @caichangqing1120) (PR [#421](https://github.com/vivaui/viva/pull/421)). +- macOS fails fast when started off the main thread instead of hanging (contributed by @Ezreal-byte) (PR [#435](https://github.com/vivaui/viva/pull/435)), and Windows falls back to DIB when the PNG clipboard read fails (contributed by @DeanCen) (PR [#441](https://github.com/vivaui/viva/pull/441)). +- `textview` paints the requested scroll line in the current frame (contributed by @1lck) (PR [#450](https://github.com/vivaui/viva/pull/450)), and a textarea's custom painter covers its selected text (contributed by @imjakey) (PR [#442](https://github.com/vivaui/viva/pull/442)). +- `dbusmenu` no longer announces the layout its own first read builds. +- After a payload update the installer writes the new version and size into Windows' Add or Remove Programs entry, so a package manager stops offering the same update again. +- `viva feed` cuts update patches in parallel and `--patch-max-ratio` drops a patch too large to be worth downloading; `viva init`'s component templates are refreshed; every component page's API tables are generated from `api.json`. +- Headless screenshots on macOS can use the integrated GPU of a dual-GPU Intel Mac with `VIVA_HEADLESS_METAL_DEVICE=low-power` (contributed by @shubo83) (PR [#437](https://github.com/vivaui/viva/pull/437)). + +## 注意 · Caveats + +- `TableSpec.Headers` 与 `TableSpec.Sortable` 移除,改为每个 `TableColumn` 的 `Title` 与 `Sortable`;没有任何列带 `Title` 的表格不再画表头,`Headers` 与空 `Columns` 共享宽度的写法要改成每列一个 `TableColumn`。 +- `TextFieldID`、`TextAreaID`、`RadioID`、`SelectID` 与 `ColorPickerID` 移除,身份改为写在固定参数末尾的 `ui.WithID(id)`;`PopoverWith` 改名为 `ui.Popover`、`ModalWith` 改名为 `ui.Modal`,spec 放在 body 之前,零值 `PopoverSpec` 居中而不是对齐起始边。 +- `app.StartFileDrag` 不再返回目标接受的效果:Windows 的拖动阻塞到放下才返回,macOS 与 Linux 在拖动进行时就返回。 +- `ui.Configure` 现在把窗口的文件拖放先交给页面声明的 `Box.DropFiles` 区域;只设自己的 `OnFileDrop`、没有声明区域的程序看到的事件与以前相同。 +- 细则见 [升级指南 / Upgrading](../upgrading.md#v069---identity-options-and-required-specs)。 + +- `TableSpec.Headers` and `TableSpec.Sortable` are removed; each `TableColumn` has a `Title` and a `Sortable` instead. A table none of whose columns has a `Title` draws no header row, and a table that shared its width between `Headers` and no `Columns` writes one `TableColumn` per column. +- `TextFieldID`, `TextAreaID`, `RadioID`, `SelectID` and `ColorPickerID` are removed: the identity is the `ui.WithID(id)` option at the end of the fixed arguments. `PopoverWith` is now `ui.Popover` and `ModalWith` is now `ui.Modal`, taking their spec before the body, and a zero `PopoverSpec` centers the popover instead of lining it up with the anchor's start. +- `app.StartFileDrag` no longer reports the effect the target took: the Windows drag blocks until the drop, while macOS and Linux return once the drag is running. +- `ui.Configure` now gives the window's file drop to a page's `Box.DropFiles` area first; an application that sets its own `OnFileDrop` and declares no area sees the same events as before. +- Details are in the [upgrading guide](../upgrading.md#v069---identity-options-and-required-specs). diff --git a/docs/upgrading.md b/docs/upgrading.md index c392e8a7..b94fac3f 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -14,14 +14,22 @@ with its own predecessor, not with whatever the application is on. ## Incompatible changes Newest first. This guide covers the incompatible changes documented here from -v0.2.2 through v0.6.0 and in v0.6.8, including package moves as well as removed -members and changed signatures. Read every entry newer than the application's -current version, together with the corresponding [release notes](releases/). For -a target between or newer than those, also check its intervening release notes; -this page is not a promise that other releases only add API. Releases before v0.2.2 are not -covered: the release-note archive begins there. +v0.2.2 through v0.6.0 and in v0.6.8 and v0.6.9, including package moves as well +as removed members and changed signatures. Read every entry newer than the +application's current version, together with the corresponding [release +notes](releases/). For a target between or newer than those, also check its +intervening release notes; this page is not a promise that other releases only +add API. Releases before v0.2.2 are not covered: the release-note archive begins +there. -### Unreleased - `ui.Configure` routes files dragged from the system +### v0.6.9 - `app.StartFileDrag` no longer reports the effect + +`StartFileDrag` returns only an error: the effect the target took is the +platform's own and is not reported, because the Windows drag blocks until the +drop while macOS and Linux return once the drag is running. Code that read the +effect must stop reading it. + +### v0.6.9 - `ui.Configure` routes files dragged from the system `ui.Configure` now sets the window's `OnFileDrop`: it gives the files to the `FileDropState` area (`Box.DropFiles`) under them, then to the `OnFileDrop` you @@ -29,7 +37,7 @@ passed when no area is there. An application that sets its own `OnFileDrop` and declares no area sees the same events as before. `ui.Host` has an `OnFileDrop` field for a host that calls `Page.Attach` itself. -### Unreleased - a `ui.Table` column carries its own title and sort flag +### v0.6.9 - a `ui.Table` column carries its own title and sort flag `TableSpec.Headers` and `TableSpec.Sortable` are removed; each `TableColumn` has a `Title` and a `Sortable` instead, so adding, dropping or reordering a column is one @@ -46,7 +54,7 @@ edit rather than three slices that must stay the same length. - `components.Table` is unchanged: it still takes `Header(headings)` separately and ignores `Title` and `Sortable`. -### Unreleased - identity options and required specs +### v0.6.9 - identity options and required specs The `...ID` and `...With` twins of a control are removed; each control has one function. diff --git a/gfx/bitmap_test.go b/gfx/bitmap_test.go index 27aeb102..44bfdf6d 100644 --- a/gfx/bitmap_test.go +++ b/gfx/bitmap_test.go @@ -50,3 +50,38 @@ func TestDrawBackdropIgnoresClipAndLayer(t *testing.T) { t.Fatalf("images = %+v", images) } } + +// A bitmap of the screen's own pixels lands on a device pixel at any display +// scale, and covers as many logical pixels as its device size says: 32 pixels +// at 125% cover 25.6 logical ones, not the 26 the painter would round them to. +func TestDrawBitmapPixelsKeepsTheBitmapOnDevicePixels(t *testing.T) { + pixels := make([]byte, 3*2*4) + var canvas Canvas + canvas.SetPixelScale(1.25) + covered := canvas.DrawBitmapPixels(Bitmap{Pix: pixels, Width: 3, Height: 2, Stride: 12, ID: 9}, Point{X: 2.4, Y: 4.8}) + images := canvas.Images() + if len(images) != 1 { + t.Fatalf("images = %d, want 1", len(images)) + } + image := images[0] + if !image.DevicePixels { + t.Fatal("the bitmap is not marked as device pixels") + } + // 2.4 logical pixels is device pixel 3, and 4.8 is device pixel 6. + if covered.X*1.25 != 3 || covered.Y*1.25 != 6 { + t.Fatalf("covered at %v, want device pixel 3,6", covered) + } + if covered.Width*1.25 != 3 || covered.Height*1.25 != 2 { + t.Fatalf("covered %v, want 3x2 device pixels", covered) + } + if image.Bounds != covered { + t.Fatalf("bounds %v, covered %v", image.Bounds, covered) + } + // Without a scale a device pixel is half a logical one, as Surface.DrawPixels + // takes it: the reference scale is 2. + var plain Canvas + plainCovered := plain.DrawBitmapPixels(Bitmap{Pix: pixels, Width: 3, Height: 2, Stride: 12}, Point{X: 1, Y: 1}) + if plainCovered.X != 1 || plainCovered.Y != 1 || plainCovered.Width != 1.5 || plainCovered.Height != 1 { + t.Fatalf("without a scale: %v", plainCovered) + } +} diff --git a/gfx/canvas.go b/gfx/canvas.go index 74a02862..ab76a5fb 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -1198,6 +1198,30 @@ func (canvas *Canvas) DrawBitmapShaded(bitmap Bitmap, source, bounds Rect, radiu // layer, so that translucent surfaces let it show through. It is not clipped and // belongs to no layer. At most one backdrop is meaningful; with several, they // stack in the order given. Invalid or empty bitmaps are ignored. +// DrawBitmapPixels paints bitmap with its top-left corner on the device pixel +// nearest origin, one bitmap pixel to one device pixel, and returns the logical +// rectangle it covers. It is DrawBitmapRegion for a picture whose pixels are the +// screen's, as Surface.DrawPixels is for a surface: the canvas must know the +// display scale (SetPixelScale), and without it a device pixel is taken to be +// half a logical one. +func (canvas *Canvas) DrawBitmapPixels(bitmap Bitmap, origin Point) Rect { + scale := canvas.PixelScale() + if scale <= 0 { + scale = 1 + } + left, top := deviceEdge(origin.X, scale), deviceEdge(origin.Y, scale) + covered := Rect{ + X: float32(left) / scale, Y: float32(top) / scale, + Width: float32(bitmap.Width) / scale, Height: float32(bitmap.Height) / scale, + } + before := len(canvas.images) + canvas.DrawBitmap(bitmap, covered) + if len(canvas.images) > before { + canvas.images[before].DevicePixels = true + } + return covered +} + func (canvas *Canvas) DrawBackdrop(bitmap Bitmap, source, bounds Rect) { before := len(canvas.images) canvas.DrawBitmapRegion(bitmap, source, bounds) diff --git a/gfx/surface.go b/gfx/surface.go index 76fbbbed..bad705d8 100644 --- a/gfx/surface.go +++ b/gfx/surface.go @@ -132,6 +132,20 @@ func (surface *Surface) Update(x, y, width, height int, pix []byte, stride int) } } +// Pixel returns the color of the picture at (x, y) as blue, green, red and +// alpha bytes, straight (not multiplied by alpha), and whether (x, y) is +// inside the picture. It reads the retained tiles, so it is exactly what Update +// last stored: the picture a renderer has, not one it is about to paint. +func (surface *Surface) Pixel(x, y int) (blue, green, red, alpha byte, ok bool) { + if x < 0 || y < 0 || x >= surface.width || y >= surface.height { + return 0, 0, 0, 0, false + } + edge := surface.edge + tile := &surface.tiles[(y/edge)*surface.columns+x/edge] + at := ((y%edge)*tile.width + x%edge) * 4 + return tile.pix[at], tile.pix[at+1], tile.pix[at+2], tile.pix[at+3], true +} + // Draw paints the whole picture scaled to bounds. Each tile's edges are rounded // to whole pixels on the way, so neighbours meet exactly at any scale: no seam // of the background shows between them and no pixel is drawn twice. diff --git a/gfx/surface_test.go b/gfx/surface_test.go index 75bc7a3b..7c27462a 100644 --- a/gfx/surface_test.go +++ b/gfx/surface_test.go @@ -70,6 +70,34 @@ func TestSurfaceUpdateChangesOnlyTheTilesItTouches(t *testing.T) { } } +// Pixel reads the retained picture itself, so an application can work out +// what is under one point of it without painting. The value is what Update +// stored, including the opaque alpha it gives every source. +func TestSurfacePixelReadsWhatUpdateStored(t *testing.T) { + var surface Surface + if _, _, _, _, ok := surface.Pixel(0, 0); ok { + t.Fatal("an empty surface has a pixel") + } + surface.Resize(300, 300) // the tiles meet at 256 + surface.Update(0, 0, 300, 300, patch(300, 300, 10, 20, 30), 300*4) + for _, point := range [][2]int{{0, 0}, {255, 255}, {256, 0}, {0, 256}, {256, 256}, {299, 299}} { + blue, green, red, alpha, ok := surface.Pixel(point[0], point[1]) + if !ok || blue != 10 || green != 20 || red != 30 || alpha != 255 { + t.Fatalf("pixel %v = %d,%d,%d,%d (%v)", point, blue, green, red, alpha, ok) + } + } + for _, point := range [][2]int{{-1, 0}, {0, -1}, {300, 0}, {0, 300}, {300, 300}} { + if _, _, _, _, ok := surface.Pixel(point[0], point[1]); ok { + t.Fatalf("pixel %v is outside the picture", point) + } + } + // A later Update changes what the same point reads. + surface.Update(257, 257, 1, 1, patch(1, 1, 1, 2, 3), 4) + if blue, _, _, _, _ := surface.Pixel(257, 257); blue != 1 { + t.Fatalf("updated pixel blue = %d", blue) + } +} + func TestSurfaceUpdateReadsASubrectangleOfALargerSource(t *testing.T) { var surface Surface surface.Resize(300, 300) diff --git a/headless/control.go b/headless/control.go index a8f24800..95587473 100644 --- a/headless/control.go +++ b/headless/control.go @@ -4,6 +4,7 @@ package headless import ( "bufio" + "errors" "fmt" "io" "os" @@ -92,6 +93,8 @@ import ( // appearance [light|dark|unknown] read or set the system appearance the run reports // clip [TEXT] read or replace the private clipboard // clipimage [PATH|clear] read (ok image N bytes | ok none) or replace the private clipboard's image with a PNG file +// clipfiles [PATH...|clear] read (ok N paths | ok none) or replace the private clipboard's files, as a file +// manager's copy does: their names are its text too, so a paste asks for files first // openedurl report the last public OpenURL request // openedpath report the last OpenPath request // revealedpath report the last RevealPath request @@ -256,6 +259,23 @@ func execute(session *Session, line string) (reply string, quit bool) { return finish(session.driver.QueueSaveFile("", app.ErrCanceled), "") } return finish(session.driver.QueueSaveFile(arguments[0], nil), "") + case "clipfiles": + switch { + case len(arguments) == 1 && arguments[0] == "clear": + session.driver.SetClipboardFiles(nil) + return finish(nil, "") + case len(arguments) == 0: + paths, err := app.ClipboardFiles() + if errors.Is(err, app.ErrNoFiles) { + return finish(nil, " none") + } + if err != nil { + return finish(err, "") + } + return finish(nil, " "+strconv.Itoa(len(paths))+" paths") + } + session.driver.SetClipboardFiles(arguments) + return finish(nil, "") case "move", "down", "up", "click", "dblclick", "rightclick": if command == "rightclick" && len(arguments) == 1 { return finish(session.RightClickLabel(arguments[0]), "") diff --git a/headless/control_system_test.go b/headless/control_system_test.go index 1122c344..54c04ada 100644 --- a/headless/control_system_test.go +++ b/headless/control_system_test.go @@ -183,3 +183,48 @@ func TestControlClipimageFeedsTheAppsClipboardImageReads(t *testing.T) { t.Fatalf("copying text leaves the image: %q", reply) } } + +// A script's clipfiles is the file manager's copy: the app reads the paths, and +// the paste the run performs delivers the names as text, which is what an +// app asks the files about before it inserts text. +func TestControlClipfilesFeedsTheAppsClipboardFileReads(t *testing.T) { + session, err := Open(app.Config{}, nil, Options{}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + + if reply, _ := execute(session, "clipfiles"); reply != "ok none\n" { + t.Fatalf("a fresh run has files on the clipboard: %q", reply) + } + first, second := filepath.Join(t.TempDir(), "notes.txt"), filepath.Join(t.TempDir(), "report.pdf") + os.WriteFile(first, []byte("plan\n"), 0o600) + if reply, _ := execute(session, "clipfiles "+strconv.Quote(first)+" "+strconv.Quote(second)); reply != "ok\n" { + t.Fatalf("clipfiles reply = %q", reply) + } + if reply, _ := execute(session, "clipfiles"); reply != "ok 2 paths\n" { + t.Fatalf("clipfiles query = %q", reply) + } + paths, err := app.ClipboardFiles() + if err != nil || len(paths) != 2 || paths[0] != first || paths[1] != second { + t.Fatalf("ClipboardFiles = %q, %v", paths, err) + } + if names := session.driver.Clipboard(); names != "notes.txt\nreport.pdf" { + t.Fatalf("the copied files' names are not the clipboard's text: %q", names) + } + if reply, _ := execute(session, "clipfiles clear"); reply != "ok\n" { + t.Fatalf("clipfiles clear = %q", reply) + } + if _, err := app.ClipboardFiles(); err != app.ErrNoFiles { + t.Fatalf("files survive clipfiles clear: %v", err) + } + if reply, _ := execute(session, "clipfiles "+strconv.Quote(first)); reply != "ok\n" { + t.Fatalf("clipfiles reply = %q", reply) + } + if reply, _ := execute(session, "clip note.txt"); reply != "ok \"note.txt\"\n" { + t.Fatalf("clip = %q", reply) + } + if _, err := app.ClipboardFiles(); err != app.ErrNoFiles { + t.Fatalf("copying text leaves the files: %v", err) + } +} diff --git a/internal/platform/linux/fonts_linux.go b/internal/platform/linux/fonts_linux.go index 0e9f7df4..b58f6f04 100644 --- a/internal/platform/linux/fonts_linux.go +++ b/internal/platform/linux/fonts_linux.go @@ -3,6 +3,7 @@ package linux import ( + "math" "sort" "strings" "unsafe" @@ -10,8 +11,17 @@ import ( "github.com/ebitengine/purego" ) -// fcMono is fontconfig's FC_MONO spacing: every glyph the same width. -const fcMono = 100 +const ( + // Fontconfig spacing values (fontconfig.h): FC_DUAL (90) is used by CJK + // dual-width terminal fonts, FC_MONO (100) by single-width monospace fonts, + // and FC_CHARCELL (110) by character-cell fonts. + fcDual = 90 + fcMono = 100 + fcCharCell = 110 + + monoMeasureSize = 14 + monoMeasureTolerance = 0.01 +) // fcFontSet is FcFontSet: how many patterns, and the array of them. type fcFontSet struct { @@ -29,7 +39,13 @@ func MonospaceFamilies() []string { return fontFamilies(true) } func FontFamilies() []string { return fontFamilies(false) } // fontFamilies asks fontconfig for the installed families, only the fixed-pitch -// ones (fontconfig's FC_MONO spacing) when mono is set. +// ones when mono is set. +// +// Trusting fontconfig's FC_MONO (100) alone leaves out dual-width CJK terminal +// fonts (FC_DUAL, 90, such as Sarasa Term) and monospace fonts whose spacing +// metadata is proportional or unset. Measuring each family through Pango with +// fallback disabled catches every family that draws printable ASCII on one grid; +// when Pango is unavailable, it falls back to fontconfig's fixed-pitch spacings. func fontFamilies(mono bool) []string { library, err := purego.Dlopen("libfontconfig.so.1", purego.RTLD_NOW|purego.RTLD_LOCAL) if err != nil { @@ -38,23 +54,23 @@ func fontFamilies(mono bool) []string { var ( patternCreate func() uintptr patternDestroy func(uintptr) - patternAddInteger func(pattern uintptr, object *byte, value int32) int32 objectSetCreate func() uintptr objectSetDestroy func(uintptr) objectSetAdd func(set uintptr, object *byte) int32 fontList func(config, pattern, set uintptr) *fcFontSet fontSetDestroy func(*fcFontSet) patternGetString func(pattern uintptr, object *byte, index int32, value **byte) int32 + patternGetInteger func(pattern uintptr, object *byte, index int32, value *int32) int32 ) purego.RegisterLibFunc(&patternCreate, library, "FcPatternCreate") purego.RegisterLibFunc(&patternDestroy, library, "FcPatternDestroy") - purego.RegisterLibFunc(&patternAddInteger, library, "FcPatternAddInteger") purego.RegisterLibFunc(&objectSetCreate, library, "FcObjectSetCreate") purego.RegisterLibFunc(&objectSetDestroy, library, "FcObjectSetDestroy") purego.RegisterLibFunc(&objectSetAdd, library, "FcObjectSetAdd") purego.RegisterLibFunc(&fontList, library, "FcFontList") purego.RegisterLibFunc(&fontSetDestroy, library, "FcFontSetDestroy") purego.RegisterLibFunc(&patternGetString, library, "FcPatternGetString") + purego.RegisterLibFunc(&patternGetInteger, library, "FcPatternGetInteger") spacing, family := []byte("spacing\x00"), []byte("family\x00") pattern := patternCreate() @@ -64,10 +80,10 @@ func fontFamilies(mono bool) []string { } defer patternDestroy(pattern) defer objectSetDestroy(set) - if mono && (patternAddInteger(pattern, &spacing[0], fcMono) == 0 || objectSetAdd(set, &family[0]) == 0) { + if objectSetAdd(set, &family[0]) == 0 { return nil } - if !mono && objectSetAdd(set, &family[0]) == 0 { + if mono && objectSetAdd(set, &spacing[0]) == 0 { return nil } fonts := fontList(0, pattern, set) @@ -76,25 +92,90 @@ func fontFamilies(mono bool) []string { } defer fontSetDestroy(fonts) - seen := make(map[string]struct{}) + seen := make(map[string]bool) for index := int32(0); index < fonts.count; index++ { font := *(*uintptr)(unsafe.Add(fonts.fonts, uintptr(index)*unsafe.Sizeof(uintptr(0)))) var value *byte if font == 0 || patternGetString(font, &family[0], 0, &value) != 0 || value == nil { continue } - if name := cStringAt(value); name != "" { - seen[name] = struct{}{} + name := cStringAt(value) + if name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "@") { + continue + } + if !mono { + seen[name] = true + continue + } + var sp int32 + hasSpacing := patternGetInteger(font, &spacing[0], 0, &sp) == 0 + isFixedSpacing := hasSpacing && (sp == fcDual || sp == fcMono || sp == fcCharCell) + if isFixedSpacing { + seen[name] = true + } else if _, exists := seen[name]; !exists { + seen[name] = false } } - names := make([]string, 0, len(seen)) - for name := range seen { - names = append(names, name) + + var names []string + if !mono { + names = make([]string, 0, len(seen)) + for name := range seen { + names = append(names, name) + } + } else if services, err := newTextServices(); err == nil { + defer services.close() + names = make([]string, 0, len(seen)) + for name := range seen { + if familyMeasuresMono(services, name) { + names = append(names, name) + } + } + } else { + names = make([]string, 0, len(seen)) + for name, fixed := range seen { + if fixed { + names = append(names, name) + } + } } sort.Slice(names, func(i, j int) bool { return strings.ToLower(names[i]) < strings.ToLower(names[j]) }) return names } +// familyMeasuresMono reports whether family draws printable ASCII on one advance, +// as a terminal's grid needs. Twenty i's and twenty W's come out the same width +// only when it does, with fallback disabled so another font never supplies the +// glyphs for a family that lacks them. +func familyMeasuresMono(services *textServices, family string) bool { + description, err := services.description(family, monoMeasureSize, 0, false) + if err != nil { + return false + } + defer services.fontFree(description) + if services.noFallback != 0 { + services.layoutSetAttributes(services.layout, services.noFallback) + defer services.layoutSetAttributes(services.layout, 0) + } + narrow, _, _ := services.layoutValue(description, "iiiiiiiiiiiiiiiiiiii") + if narrow.Width <= 0 { + return false + } + if services.noFallback != 0 && services.layoutGetUnknownGlyphs != nil && services.layoutGetUnknownGlyphs(services.layout) > 0 { + return false + } + wide, _, _ := services.layoutValue(description, "WWWWWWWWWWWWWWWWWWWW") + if wide.Width <= 0 { + return false + } + if services.noFallback != 0 && services.layoutGetUnknownGlyphs != nil && services.layoutGetUnknownGlyphs(services.layout) > 0 { + return false + } + narrowPx := float64(narrow.Width) / pangoScale + widePx := float64(wide.Width) / pangoScale + return math.Abs(narrowPx-widePx) < monoMeasureTolerance +} + // cStringAt reads the NUL-terminated string a C library returned. func cStringAt(start *byte) string { const limit = 256 diff --git a/internal/platform/linux/fonts_linux_test.go b/internal/platform/linux/fonts_linux_test.go new file mode 100644 index 00000000..dd11479f --- /dev/null +++ b/internal/platform/linux/fonts_linux_test.go @@ -0,0 +1,50 @@ +//go:build !android + +package linux + +import ( + "slices" + "testing" +) + +func TestMonospaceFamiliesIncludeFixedPitchAndExcludeProportional(t *testing.T) { + mono := MonospaceFamilies() + if len(mono) == 0 { + t.Skip("no fixed-pitch family installed") + } + all := FontFamilies() + for _, name := range mono { + if !slices.Contains(all, name) { + t.Errorf("MonospaceFamilies() listed %q which is missing from FontFamilies()", name) + } + } + for _, proportional := range []string{"DejaVu Sans", "DejaVu Serif", "Ubuntu", "Ubuntu Sans"} { + if slices.Contains(all, proportional) && slices.Contains(mono, proportional) { + t.Errorf("proportional family %q was listed by MonospaceFamilies()", proportional) + } + } +} + +func TestFamilyMeasuresMonoRejectsProportionalFamilies(t *testing.T) { + services, err := newTextServices() + if err != nil { + t.Skipf("no Pango on this machine: %v", err) + } + defer services.close() + + mono := MonospaceFamilies() + if len(mono) == 0 { + t.Skip("no fixed-pitch family installed") + } + if !familyMeasuresMono(services, mono[0]) { + t.Fatalf("familyMeasuresMono(%q) = false, want true", mono[0]) + } + all := FontFamilies() + for _, proportional := range []string{"DejaVu Sans", "Ubuntu"} { + // An unknown name is not tested: fontconfig answers it with the + // default font, which is monospace on some systems. + if slices.Contains(all, proportional) && familyMeasuresMono(services, proportional) { + t.Errorf("familyMeasuresMono(%q) = true, want false", proportional) + } + } +} diff --git a/internal/platform/linux/portal_directory_linux_test.go b/internal/platform/linux/portal_directory_linux_test.go new file mode 100644 index 00000000..60f6a647 --- /dev/null +++ b/internal/platform/linux/portal_directory_linux_test.go @@ -0,0 +1,50 @@ +package linux + +import ( + "testing" + + "github.com/vivaui/viva/internal/dbus" +) + +func TestDirectoryPortalRequestCarriesInitialDirectory(t *testing.T) { + for _, directory := range []string{"/tmp/My projects", "/tmp/项目/"} { + t.Run(directory, func(t *testing.T) { + request := directoryPortalRequest(OpenDirectoryOptions{Title: "Choose folder", InitialDirectory: directory}, "x11:2a") + decoder := dbus.NewDecoder(encodeFileRequest(request, "tok")) + if parent, title := decoder.String(), decoder.String(); parent != "x11:2a" || title != "Choose folder" { + t.Fatalf("parent %q title %q", parent, title) + } + seenFolder, seenDirectory := false, false + end := decoder.ArrayLength(8) + for decoder.Pos() < end && decoder.Err() == nil { + decoder.Align(8) + key, signature := decoder.String(), decoder.Signature() + switch key { + case "directory": + if signature != "b" || !decoder.Bool() { + t.Fatal("directory option is wrong") + } + seenDirectory = true + case "current_folder": + if signature != "ay" { + t.Fatalf("current_folder signature = %q", signature) + } + folderEnd := decoder.ArrayLength(1) + var folder []byte + for decoder.Pos() < folderEnd && decoder.Err() == nil { + folder = append(folder, decoder.Byte()) + } + if string(folder) != directory+"\x00" { + t.Fatalf("current_folder = %q; want %q", folder, directory+"\x00") + } + seenFolder = true + default: + decoder.Skip(signature) + } + } + if decoder.Err() != nil || !decoder.Done() || !seenFolder || !seenDirectory { + t.Fatalf("request: error %v, done %v, folder %v, directory %v", decoder.Err(), decoder.Done(), seenFolder, seenDirectory) + } + }) + } +} diff --git a/internal/platform/linux/portal_unix.go b/internal/platform/linux/portal_unix.go index ab8bb02c..045269c8 100644 --- a/internal/platform/linux/portal_unix.go +++ b/internal/platform/linux/portal_unix.go @@ -198,6 +198,7 @@ type portalFileRequest struct { multiple, directory bool filters []portalFilter currentName string + currentFolder string checkboxLabel string checkboxChecked bool } @@ -242,6 +243,16 @@ func encodeFileRequest(request portalFileRequest, token string) []byte { encoder.EndArray(list) }) } + if request.currentFolder != "" { + option("current_folder", "ay", func() { + folder := encoder.BeginArray(1) + for index := 0; index < len(request.currentFolder); index++ { + encoder.Byte(request.currentFolder[index]) + } + encoder.Byte(0) + encoder.EndArray(folder) + }) + } if request.currentName != "" { option("current_name", "s", func() { encoder.String(request.currentName) }) } diff --git a/internal/platform/linux/system_linux.go b/internal/platform/linux/system_linux.go index 9022dcd4..ca7d0ba6 100644 --- a/internal/platform/linux/system_linux.go +++ b/internal/platform/linux/system_linux.go @@ -771,10 +771,15 @@ func OpenFiles(options OpenFileOptions) ([]string, bool, error) { return paths, false, nil } +func directoryPortalRequest(options OpenDirectoryOptions, parent string) portalFileRequest { + return portalFileRequest{ + method: "OpenFile", parent: parent, title: options.Title, directory: true, + currentFolder: options.InitialDirectory, + } +} + func OpenDirectory(options OpenDirectoryOptions) (string, bool, error) { - paths, canceled, err := portalChoose(portalFileRequest{ - method: "OpenFile", parent: portalParent(), title: options.Title, directory: true, - }) + paths, canceled, err := portalChoose(directoryPortalRequest(options, portalParent())) if !errors.Is(err, errServiceMissing) { return firstPath(paths), canceled, singlePathError(paths, canceled, err, "open directory") } diff --git a/internal/platform/windows/clipboard_html_windows.go b/internal/platform/windows/clipboard_html_windows.go index 175959f1..3157c907 100644 --- a/internal/platform/windows/clipboard_html_windows.go +++ b/internal/platform/windows/clipboard_html_windows.go @@ -28,8 +28,8 @@ func SetClipboardHTML(html, alt string) error { binary.LittleEndian.PutUint16(text[index*2:], unit) } block := cfHTML(html) - clipboardMu.Lock() - defer clipboardMu.Unlock() + lockClipboardThread() + defer unlockClipboardThread() owner := activeOwnerWindow() if opened, _, callErr := openClipboard.Call(owner); opened == 0 { return windowsCallError("open clipboard", callErr) diff --git a/internal/platform/windows/clipboard_image_windows.go b/internal/platform/windows/clipboard_image_windows.go index fdaa2fc9..321e318e 100644 --- a/internal/platform/windows/clipboard_image_windows.go +++ b/internal/platform/windows/clipboard_image_windows.go @@ -36,8 +36,8 @@ func SetClipboardImage(png []byte) error { if err != nil { return err } - clipboardMu.Lock() - defer clipboardMu.Unlock() + lockClipboardThread() + defer unlockClipboardThread() owner := activeOwnerWindow() if err := openClipboardForWrite(owner); err != nil { return err diff --git a/internal/platform/windows/clipboard_rectangular_windows.go b/internal/platform/windows/clipboard_rectangular_windows.go index 6b16f9c3..e759e934 100644 --- a/internal/platform/windows/clipboard_rectangular_windows.go +++ b/internal/platform/windows/clipboard_rectangular_windows.go @@ -41,8 +41,8 @@ func SetClipboardRectangularText(value string) error { // ClipboardTextWithFormat reads text and its markers while the clipboard is open. func ClipboardTextWithFormat() (string, bool, error) { - clipboardMu.Lock() - defer clipboardMu.Unlock() + lockClipboardThread() + defer unlockClipboardThread() if opened, _, err := openClipboard.Call(0); opened == 0 { return "", false, windowsCallError("open clipboard", err) } diff --git a/internal/platform/windows/clipboard_rectangular_windows_test.go b/internal/platform/windows/clipboard_rectangular_windows_test.go index 1618f53e..4315e202 100644 --- a/internal/platform/windows/clipboard_rectangular_windows_test.go +++ b/internal/platform/windows/clipboard_rectangular_windows_test.go @@ -2,6 +2,7 @@ package windows import ( "errors" + "fmt" "os" "runtime" "syscall" @@ -14,6 +15,37 @@ import ( "github.com/vivaui/viva/text" ) +func TestColumnClipboardNativeReadsFromWorkerGoroutines(t *testing.T) { + columnClipboardWindow(t) + const value = "\u00e9\r\n\u6f22\r\n" + if err := SetClipboardRectangularText(value); err != nil { + t.Fatal(err) + } + const readers = 4 + done := make(chan error, readers) + for range readers { + go func() { + for range 32 { + if got, rectangular, err := ClipboardTextWithFormat(); err != nil || got != value || !rectangular { + done <- fmt.Errorf("worker read %q, rectangular=%v, error=%v", got, rectangular, err) + return + } + runtime.Gosched() + if got, err := ClipboardText(); err != nil || got != value { + done <- fmt.Errorf("worker text read %q: %v", got, err) + return + } + } + done <- nil + }() + } + for range readers { + if err := <-done; err != nil { + t.Error(err) + } + } +} + func columnClipboardWindow(t *testing.T) *windowState { t.Helper() if os.Getenv("VIVA_WINDOWS_CLIPBOARD") == "" { diff --git a/internal/platform/windows/system_windows.go b/internal/platform/windows/system_windows.go index ea6bb887..7458f5eb 100644 --- a/internal/platform/windows/system_windows.go +++ b/internal/platform/windows/system_windows.go @@ -121,6 +121,17 @@ var notificationMu sync.Mutex var notificationWindow uintptr var notificationAdded bool +// Win32 associates an open clipboard with the calling thread, not the process. +func lockClipboardThread() { + clipboardMu.Lock() + runtime.LockOSThread() +} + +func unlockClipboardThread() { + runtime.UnlockOSThread() + clipboardMu.Unlock() +} + var callNotifyIcon = func(operation uintptr, data *notifyIconData) (uintptr, uintptr, error) { return shellNotifyIcon.Call(operation, uintptr(unsafe.Pointer(data))) } @@ -131,8 +142,8 @@ var saveDialogClass = guid{Data1: 0xc0b4e2f3, Data2: 0xba21, Data3: 0x4773, Data var saveDialogInterface = guid{Data1: 0x84bccd23, Data2: 0x5fde, Data3: 0x4cdb, Data4: [8]byte{0xae, 0xa4, 0xaf, 0x64, 0xb8, 0x3d, 0x78, 0xab}} func ClipboardText() (string, error) { - clipboardMu.Lock() - defer clipboardMu.Unlock() + lockClipboardThread() + defer unlockClipboardThread() available, _, _ := clipboardFormatAvailable.Call(clipboardUnicodeText) if available == 0 { return "", nil @@ -221,8 +232,8 @@ func activeOwnerWindow() uintptr { // ClipboardImagePNG returns the clipboard's image as PNG bytes: the registered // "PNG" format as it is, otherwise CF_DIBV5 or CF_DIB converted. func ClipboardImagePNG() ([]byte, error) { - clipboardMu.Lock() - defer clipboardMu.Unlock() + lockClipboardThread() + defer unlockClipboardThread() if !HasClipboardImage() { return nil, platform.ErrNoClipboardImage } @@ -281,8 +292,8 @@ const maxClipboardFileListBytes = 16 << 20 // ClipboardFiles returns the paths of the files the clipboard holds: the // CF_HDROP list Explorer leaves there after a copy. func ClipboardFiles() ([]string, error) { - clipboardMu.Lock() - defer clipboardMu.Unlock() + lockClipboardThread() + defer unlockClipboardThread() if available, _, _ := clipboardFormatAvailable.Call(clipboardHDrop); available == 0 { return nil, platform.ErrNoClipboardFiles } @@ -348,8 +359,8 @@ func setClipboardText(value string, rectangular bool) error { if err != nil { return fmt.Errorf("windows: encode clipboard text: %w", err) } - clipboardMu.Lock() - defer clipboardMu.Unlock() + lockClipboardThread() + defer unlockClipboardThread() var columnFormat, borlandFormat, columnMarker, borlandMarker uintptr if rectangular { columnFormat, borlandFormat, err = rectangularClipboardFormats() @@ -430,8 +441,8 @@ func SetClipboardFiles(paths []string) error { if err != nil { return fmt.Errorf("windows: encode clipboard file names: %w", err) } - clipboardMu.Lock() - defer clipboardMu.Unlock() + lockClipboardThread() + defer unlockClipboardThread() owner := activeOwnerWindow() if opened, _, callErr := openClipboard.Call(owner); opened == 0 { return windowsCallError("open clipboard", callErr) diff --git a/ui/alert/alert_desktop_test.go b/ui/alert/alert_desktop_test.go new file mode 100644 index 00000000..c4669738 --- /dev/null +++ b/ui/alert/alert_desktop_test.go @@ -0,0 +1,90 @@ +//go:build darwin || windows || linux + +package alert_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/alert" +) + +var shown int // the paints in which ActionClicked was true + +func open(t *testing.T, a *alert.Alert, spec alert.Spec) *headless.Session { + t.Helper() + shown = 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + a.View(c, spec).FillWidth() + if a.ActionClicked() { + shown++ + } + ui.Button(c, "After") + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Alert", Width: 480, Height: 240}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// The notice announces its title as a status, with the words it was given. +func TestAlertIsAStatusNamedByItsTitle(t *testing.T) { + session := open(t, alert.New(), alert.Spec{Status: ui.StatusWarning, Title: "Host key changed", Description: "Review it."}) + node, ok := session.AccessByName("Host key changed") + if !ok || node.Role != gfx.RoleStatus { + t.Fatalf("access node = %+v, %v; want a status named by the title", node, ok) + } + if err := session.Expect("text", "Review it."); err != nil { + t.Fatal(err) + } +} + +// A press on the action is reported once, in the paint that delivered it. +func TestActionClickIsReported(t *testing.T) { + session := open(t, alert.New(), alert.Spec{Title: "Update", Action: "Review"}) + if err := session.ClickLabel("Review"); err != nil { + t.Fatal(err) + } + if shown != 1 { + t.Fatalf("ActionClicked was true in %d paints after one press, want 1", shown) + } +} + +// The close button closes the notice for good, until it is reopened. +func TestCloseButtonClosesTheNotice(t *testing.T) { + a := alert.New() + session := open(t, a, alert.Spec{Title: "Update", Closable: true}) + if err := session.ClickLabel("Close"); err != nil { + t.Fatal(err) + } + if !a.Closed() { + t.Fatal("Closed was false after the close button was pressed") + } + if _, ok := session.AccessByName("Update"); ok { + t.Fatal("a closed notice is still in the accessibility tree") + } + a.Reopen() + if err := session.Frame(); err != nil { + t.Fatal(err) + } + if _, ok := session.AccessByName("Update"); !ok { + t.Fatal("a reopened notice is not shown again") + } +} + +// A notice with no close button or action offers neither. +func TestPlainNoticeHasNoButtons(t *testing.T) { + session := open(t, alert.New(), alert.Spec{Title: "Saved", Status: ui.StatusSuccess}) + for _, name := range []string{"Close", "Review"} { + if _, err := session.Locate(name); err == nil { + t.Fatalf("a plain notice offers %q", name) + } + } +} diff --git a/ui/alert/alert_test.go b/ui/alert/alert_test.go index 6aea1071..fb988f8c 100644 --- a/ui/alert/alert_test.go +++ b/ui/alert/alert_test.go @@ -1,94 +1,13 @@ -//go:build !js - package alert_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/alert" ) -var shown int // the paints in which ActionClicked was true - -func open(t *testing.T, a *alert.Alert, spec alert.Spec) *headless.Session { - t.Helper() - shown = 0 - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - ui.Column(c).Pad(16).Children(func() { - a.View(c, spec).FillWidth() - if a.ActionClicked() { - shown++ - } - ui.Button(c, "After") - }) - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Alert", Width: 480, Height: 240}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(session.Close) - return session -} - -// The notice announces its title as a status, with the words it was given. -func TestAlertIsAStatusNamedByItsTitle(t *testing.T) { - session := open(t, alert.New(), alert.Spec{Status: ui.StatusWarning, Title: "Host key changed", Description: "Review it."}) - node, ok := session.AccessByName("Host key changed") - if !ok || node.Role != gfx.RoleStatus { - t.Fatalf("access node = %+v, %v; want a status named by the title", node, ok) - } - if err := session.Expect("text", "Review it."); err != nil { - t.Fatal(err) - } -} - -// A press on the action is reported once, in the paint that delivered it. -func TestActionClickIsReported(t *testing.T) { - session := open(t, alert.New(), alert.Spec{Title: "Update", Action: "Review"}) - if err := session.ClickLabel("Review"); err != nil { - t.Fatal(err) - } - if shown != 1 { - t.Fatalf("ActionClicked was true in %d paints after one press, want 1", shown) - } -} - -// The close button closes the notice for good, until it is reopened. -func TestCloseButtonClosesTheNotice(t *testing.T) { - a := alert.New() - session := open(t, a, alert.Spec{Title: "Update", Closable: true}) - if err := session.ClickLabel("Close"); err != nil { - t.Fatal(err) - } - if !a.Closed() { - t.Fatal("Closed was false after the close button was pressed") - } - if _, ok := session.AccessByName("Update"); ok { - t.Fatal("a closed notice is still in the accessibility tree") - } - a.Reopen() - if err := session.Frame(); err != nil { - t.Fatal(err) - } - if _, ok := session.AccessByName("Update"); !ok { - t.Fatal("a reopened notice is not shown again") - } -} - -// A notice with no close button or action offers neither. -func TestPlainNoticeHasNoButtons(t *testing.T) { - session := open(t, alert.New(), alert.Spec{Title: "Saved", Status: ui.StatusSuccess}) - for _, name := range []string{"Close", "Review"} { - if _, err := session.Locate(name); err == nil { - t.Fatalf("a plain notice offers %q", name) - } - } -} - func TestWarmPaintAllocatesNothing(t *testing.T) { for name, spec := range map[string]alert.Spec{ "plain": {Title: "Saved", Description: "All changes were written.", Status: ui.StatusSuccess}, diff --git a/ui/breadcrumb/breadcrumb_desktop_test.go b/ui/breadcrumb/breadcrumb_desktop_test.go new file mode 100644 index 00000000..70f47416 --- /dev/null +++ b/ui/breadcrumb/breadcrumb_desktop_test.go @@ -0,0 +1,88 @@ +//go:build darwin || windows || linux + +package breadcrumb_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/breadcrumb" +) + +var chosen []int + +func open(t *testing.T, b *breadcrumb.Breadcrumb, spec breadcrumb.Spec) *headless.Session { + t.Helper() + chosen = nil + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + b.View(c, "Location", spec) + if i, ok := b.Clicked(); ok { + chosen = append(chosen, i) + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Path", Width: 640, Height: 200}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// Every place but the last is a link that reports its index; the last is the +// current place and is not a control. +func TestLinksReportTheirIndexAndTheCurrentPlaceIsNotOne(t *testing.T) { + session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: places}) + if err := session.ClickLabel("Hosts"); err != nil { + t.Fatal(err) + } + if len(chosen) != 1 || chosen[0] != 1 { + t.Fatalf("chosen = %v after a click on Hosts, want [1]", chosen) + } + if _, err := session.Locate("Logs"); err == nil { + t.Fatal("the current place is a control") + } + if err := session.Expect("text", "Logs"); err != nil { + t.Fatal(err) + } +} + +// A disabled place is shown and offers nothing to press. +func TestDisabledPlaceTakesNoPress(t *testing.T) { + items := []breadcrumb.Item{{Label: "Home"}, {Label: "Archive", Disabled: true}, {Label: "2025"}} + session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: items}) + if _, err := session.Locate("Archive"); err == nil { + t.Fatal("a disabled place is a control") + } + if err := session.Expect("text", "Archive"); err != nil { + t.Fatal(err) + } +} + +// With Max the middle places collapse behind an ellipsis; choosing one in its +// menu reports that place's index in the whole path. +func TestCollapsedPlacesAreChosenFromTheMenu(t *testing.T) { + session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: places, Max: 3}) + for _, hidden := range []string{"Hosts", "Production"} { + if _, err := session.Locate(hidden); err == nil { + t.Fatalf("%q is shown though it collapsed", hidden) + } + } + if err := session.ClickLabel("More"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("Production"); err != nil { + t.Fatal(err) + } + if len(chosen) != 1 || chosen[0] != 2 { + t.Fatalf("chosen = %v after choosing Production in the menu, want [2]", chosen) + } + for _, shown := range []string{"Home", "build-01", "Logs"} { + if err := session.Expect("text", shown); err != nil { + t.Fatal(err) + } + } +} diff --git a/ui/breadcrumb/breadcrumb_test.go b/ui/breadcrumb/breadcrumb_test.go index e1e370a5..6865d339 100644 --- a/ui/breadcrumb/breadcrumb_test.go +++ b/ui/breadcrumb/breadcrumb_test.go @@ -1,13 +1,9 @@ -//go:build !js - package breadcrumb_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/breadcrumb" ) @@ -16,82 +12,6 @@ var places = []breadcrumb.Item{ {Label: "Home"}, {Label: "Hosts"}, {Label: "Production"}, {Label: "build-01"}, {Label: "Logs"}, } -var chosen []int - -func open(t *testing.T, b *breadcrumb.Breadcrumb, spec breadcrumb.Spec) *headless.Session { - t.Helper() - chosen = nil - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - ui.Column(c).Pad(16).Children(func() { - b.View(c, "Location", spec) - if i, ok := b.Clicked(); ok { - chosen = append(chosen, i) - } - }) - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Path", Width: 640, Height: 200}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(session.Close) - return session -} - -// Every place but the last is a link that reports its index; the last is the -// current place and is not a control. -func TestLinksReportTheirIndexAndTheCurrentPlaceIsNotOne(t *testing.T) { - session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: places}) - if err := session.ClickLabel("Hosts"); err != nil { - t.Fatal(err) - } - if len(chosen) != 1 || chosen[0] != 1 { - t.Fatalf("chosen = %v after a click on Hosts, want [1]", chosen) - } - if _, err := session.Locate("Logs"); err == nil { - t.Fatal("the current place is a control") - } - if err := session.Expect("text", "Logs"); err != nil { - t.Fatal(err) - } -} - -// A disabled place is shown and offers nothing to press. -func TestDisabledPlaceTakesNoPress(t *testing.T) { - items := []breadcrumb.Item{{Label: "Home"}, {Label: "Archive", Disabled: true}, {Label: "2025"}} - session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: items}) - if _, err := session.Locate("Archive"); err == nil { - t.Fatal("a disabled place is a control") - } - if err := session.Expect("text", "Archive"); err != nil { - t.Fatal(err) - } -} - -// With Max the middle places collapse behind an ellipsis; choosing one in its -// menu reports that place's index in the whole path. -func TestCollapsedPlacesAreChosenFromTheMenu(t *testing.T) { - session := open(t, breadcrumb.New(), breadcrumb.Spec{Items: places, Max: 3}) - for _, hidden := range []string{"Hosts", "Production"} { - if _, err := session.Locate(hidden); err == nil { - t.Fatalf("%q is shown though it collapsed", hidden) - } - } - if err := session.ClickLabel("More"); err != nil { - t.Fatal(err) - } - if err := session.ClickLabel("Production"); err != nil { - t.Fatal(err) - } - if len(chosen) != 1 || chosen[0] != 2 { - t.Fatalf("chosen = %v after choosing Production in the menu, want [2]", chosen) - } - for _, shown := range []string{"Home", "build-01", "Logs"} { - if err := session.Expect("text", shown); err != nil { - t.Fatal(err) - } - } -} - func TestWarmPaintAllocatesNothing(t *testing.T) { for name, spec := range map[string]breadcrumb.Spec{ "all": {Items: places}, diff --git a/ui/color_paint.go b/ui/color_paint.go index e92c92a5..6c21c430 100644 --- a/ui/color_paint.go +++ b/ui/color_paint.go @@ -63,7 +63,10 @@ func paintColorPickerPanel(s *ColorPickerState, d *DrawContext, c C, ID gfx.ID, options.Scope = s.GetHandlers().GetParts().At(8) options.Hex = s.HexPtr().Snapshot(c.GetF(), ids.Hex, labels.Hex, "#3B82F6") if s.GetInvalid() { - options.Error = "Invalid color" + options.Error = labels.InvalidColor + if options.Error == "" { + options.Error = "Invalid color" + } } } picker := components.BeginColorPicker(canvas, *d.Theme, d.Rect, options) diff --git a/ui/color_test.go b/ui/color_test.go index 105bc0a3..058c255e 100644 --- a/ui/color_test.go +++ b/ui/color_test.go @@ -3,6 +3,7 @@ package ui_test import ( "testing" + "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -62,6 +63,40 @@ func TestColorPickerAppliesATypedHex(t *testing.T) { } } +func TestColorPickerInvalidHexUsesPanelLabel(t *testing.T) { + for _, tc := range []struct{ name, label, want string }{ + {"localized", "颜色格式无效", "颜色格式无效"}, + {"default", "", "Invalid color"}, + } { + t.Run(tc.name, func(t *testing.T) { + var state ui.ColorPickerState + original := gfx.RGB(10, 20, 30) + color := original + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.ColorPicker(c, &state, &color, "Accent").PanelLabels(base.ColorPickerLabels{InvalidColor: tc.label}) + }) + }) + d.click("Accent") + d.click("Hex color") + state.SetHexText("#wrong") + d.click("OK") + if !state.Open() || state.Applied() || color != original { + t.Fatal("invalid input changed or applied the color") + } + found := false + for _, label := range d.driver.Snapshot().Labels { + if label.Value == tc.want { + found = true + } + } + if !found { + t.Fatalf("panel did not paint validation message %q", tc.want) + } + }) + } +} + func TestColorPickerCancelAndEscapeKeepTheColor(t *testing.T) { var state ui.ColorPickerState color := gfx.RGB(10, 20, 30) diff --git a/ui/datepicker/datepicker_paint_test.go b/ui/datepicker/datepicker_paint_test.go new file mode 100644 index 00000000..9e4bf92c --- /dev/null +++ b/ui/datepicker/datepicker_paint_test.go @@ -0,0 +1,51 @@ +package datepicker_test + +import ( + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/datepicker" +) + +func date(y int, m time.Month, d int) time.Time { return time.Date(y, m, d, 0, 0, 0, 0, time.Local) } + +var today = func() time.Time { return time.Date(2026, 11, 25, 15, 30, 0, 0, time.Local) } + +func TestWarmPaintAllocatesNothing(t *testing.T) { + value := date(2026, 11, 18) + d := datepicker.New().Clock(today) + view := func(c ui.C) { d.View(c, "Due", &value).Width(220) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 460}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + value := date(2026, 11, 18) + d := datepicker.New().Clock(today) + view := func(c ui.C) { d.View(c, "Due", &value).Width(220) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 460}, view) + canvas.EndFrame() + } +} diff --git a/ui/datepicker/datepicker_test.go b/ui/datepicker/datepicker_test.go index e6762bdd..6dad1db7 100644 --- a/ui/datepicker/datepicker_test.go +++ b/ui/datepicker/datepicker_test.go @@ -1,4 +1,4 @@ -//go:build !js +//go:build darwin || windows || linux package datepicker_test @@ -7,16 +7,11 @@ import ( "time" "github.com/vivaui/viva/app" - "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/datepicker" ) -func date(y int, m time.Month, d int) time.Time { return time.Date(y, m, d, 0, 0, 0, 0, time.Local) } - -var today = func() time.Time { return time.Date(2026, 11, 25, 15, 30, 0, 0, time.Local) } - // changes counts the paints that reported a change, as a page reads Changed. var changes int @@ -144,26 +139,6 @@ func TestTodayOpensTheMonthAndDatesAreMidnight(t *testing.T) { } } -func TestWarmPaintAllocatesNothing(t *testing.T) { - value := date(2026, 11, 18) - d := datepicker.New().Clock(today) - view := func(c ui.C) { d.View(c, "Due", &value).Width(220) } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - draw := func() { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 420, Height: 460}, view) - canvas.EndFrame() - } - draw() - if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { - t.Fatalf("warm paint allocated %v times, want 0", allocations) - } -} - // An open month repaints without allocating too: the numbers and the title are // made once, and the days are values. func TestOpenMonthAllocatesNothing(t *testing.T) { @@ -177,20 +152,3 @@ func TestOpenMonthAllocatesNothing(t *testing.T) { t.Fatalf("an open month allocated %v times a frame, want 0", allocations) } } - -func BenchmarkViewPaint(b *testing.B) { - value := date(2026, 11, 18) - d := datepicker.New().Clock(today) - view := func(c ui.C) { d.View(c, "Due", &value).Width(220) } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - b.ReportAllocs() - for range b.N { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 420, Height: 460}, view) - canvas.EndFrame() - } -} diff --git a/ui/editabletabs/editabletabs_desktop_test.go b/ui/editabletabs/editabletabs_desktop_test.go new file mode 100644 index 00000000..0c82ca9a --- /dev/null +++ b/ui/editabletabs/editabletabs_desktop_test.go @@ -0,0 +1,173 @@ +//go:build darwin || windows || linux + +package editabletabs_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/editabletabs" +) + +func (m *model) open(t *testing.T, width int, addable bool) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Children(func() { + m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: addable}).FillWidth() + // The page owns the tabs: it removes what the strip reports closed. + if i, ok := m.strip.Closed(); ok { + m.closed = append(m.closed, i) + m.tabs = append(m.tabs[:i], m.tabs[i+1:]...) + if m.active > i || m.active >= len(m.tabs) { + m.active = max(m.active-1, 0) + } + } + if m.strip.Added() { + m.added++ + m.tabs = append(m.tabs, editabletabs.Tab{Title: "new"}) + m.active = len(m.tabs) - 1 + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Tabs", Width: width, Height: 160}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// A click on a tab makes it active. +func TestClickActivates(t *testing.T) { + m := newModel("alpha", "beta", "gamma") + session := m.open(t, 600, false) + if err := session.ClickLabel("gamma"); err != nil { + t.Fatal(err) + } + if m.active != 2 { + t.Fatalf("active = %d after a click on gamma, want 2", m.active) + } +} + +// The close button of a tab, the Delete key and a middle click each report the +// tab, and a pinned tab offers none of them. +func TestClosingReportsTheTab(t *testing.T) { + m := newModel("alpha", "beta", "gamma") + m.tabs[0].Pinned = true + session := m.open(t, 600, false) + closeButtons := 0 + var first gfx.Hit + for _, hit := range session.Driver().Snapshot().Hits { + if hit.Label == "Close" { + if closeButtons == 0 { + first = hit + } + closeButtons++ + } + } + if closeButtons != 2 { + t.Fatalf("close buttons = %d, want one for each tab that is not pinned (2)", closeButtons) + } + if err := session.Click(first.Bounds.X+first.Bounds.Width/2, first.Bounds.Y+first.Bounds.Height/2); err != nil { + t.Fatal(err) + } + if len(m.closed) != 1 || m.closed[0] != 1 { + t.Fatalf("closed = %v after the close button of beta, want [1]", m.closed) + } + // Delete on the focused tab closes it; the pinned first tab is not closed by it. + if err := session.ClickLabel("alpha"); err != nil { + t.Fatal(err) + } + if err := session.Keys("delete"); err != nil { + t.Fatal(err) + } + if len(m.closed) != 1 { + t.Fatalf("Delete closed a pinned tab: %v", m.closed) + } + if err := session.Keys("right"); err != nil { + t.Fatal(err) + } + if err := session.Keys("delete"); err != nil { + t.Fatal(err) + } + if len(m.closed) != 2 || m.closed[1] != 1 { + t.Fatalf("closed = %v after Right and Delete, want [1 1]", m.closed) + } +} + +func TestMiddleClickClosesATab(t *testing.T) { + m := newModel("alpha", "beta") + session := m.open(t, 600, false) + hit, err := session.Locate("beta") + if err != nil { + t.Fatal(err) + } + x, y := hit.Bounds.X+hit.Bounds.Width/3, hit.Bounds.Y+hit.Bounds.Height/2 + if err := session.Driver().ClickButton(x, y, gfx.PointerButtonMiddle); err != nil { + t.Fatal(err) + } + if len(m.closed) != 1 || m.closed[0] != 1 { + t.Fatalf("closed = %v after a middle click on beta, want [1]", m.closed) + } +} + +// The arrow keys move the focus and make the tab active, Home and End go to the +// ends, and the add button is reached with Right and pressed with Enter. +func TestKeysMoveThroughTheStripAndAdd(t *testing.T) { + m := newModel("alpha", "beta", "gamma") + session := m.open(t, 600, true) + if err := session.Keys("tab"); err != nil { + t.Fatal(err) + } + for _, step := range []struct { + key string + want int + }{{"right", 1}, {"end", 2}, {"left", 1}, {"home", 0}} { + if err := session.Keys(step.key); err != nil { + t.Fatal(err) + } + if m.active != step.want { + t.Fatalf("active = %d after %q, want %d", m.active, step.key, step.want) + } + } + session.Keys("end") + session.Keys("right") // past the last tab: onto the add button + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if m.added != 1 || len(m.tabs) != 4 || m.active != 3 { + t.Fatalf("added %d, tabs %d, active %d after Enter on the add button; want 1, 4, 3", m.added, len(m.tabs), m.active) + } +} + +// The add button is a button of its own, and absent unless asked for. +func TestAddButtonOnlyWhenAddable(t *testing.T) { + for _, addable := range []bool{false, true} { + m := newModel("alpha") + session := m.open(t, 600, addable) + _, err := session.Locate("Add tab") + if (err == nil) != addable { + t.Fatalf("addable %v: add button present = %v", addable, err == nil) + } + } +} + +// A strip longer than its room scrolls with the wheel and keeps the active tab in view. +func TestLongStripScrollsAndKeepsTheActiveTabInView(t *testing.T) { + m := newModel("first tab", "second tab", "third tab", "fourth tab", "fifth tab", "sixth tab") + session := m.open(t, 300, false) + if err := session.ClickLabel("first tab"); err != nil { + t.Fatal(err) + } + session.Keys("end") + hit, err := session.Locate("sixth tab") + if err != nil { + t.Fatal(err) + } + if hit.Bounds.X+hit.Bounds.Width > 300.5 || hit.Bounds.X < -0.5 { + t.Fatalf("the active tab is at %+v, outside a 300 wide strip", hit.Bounds) + } +} diff --git a/ui/editabletabs/editabletabs_test.go b/ui/editabletabs/editabletabs_test.go index a25f4fe2..2f0359ab 100644 --- a/ui/editabletabs/editabletabs_test.go +++ b/ui/editabletabs/editabletabs_test.go @@ -1,13 +1,9 @@ -//go:build !js - package editabletabs_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/editabletabs" ) @@ -28,166 +24,6 @@ func newModel(titles ...string) *model { return m } -func (m *model) open(t *testing.T, width int, addable bool) *headless.Session { - t.Helper() - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - ui.Column(c).Children(func() { - m.strip.View(c, "Sessions", &m.active, editabletabs.Spec{Tabs: m.tabs, Addable: addable}).FillWidth() - // The page owns the tabs: it removes what the strip reports closed. - if i, ok := m.strip.Closed(); ok { - m.closed = append(m.closed, i) - m.tabs = append(m.tabs[:i], m.tabs[i+1:]...) - if m.active > i || m.active >= len(m.tabs) { - m.active = max(m.active-1, 0) - } - } - if m.strip.Added() { - m.added++ - m.tabs = append(m.tabs, editabletabs.Tab{Title: "new"}) - m.active = len(m.tabs) - 1 - } - }) - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Tabs", Width: width, Height: 160}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(session.Close) - return session -} - -// A click on a tab makes it active. -func TestClickActivates(t *testing.T) { - m := newModel("alpha", "beta", "gamma") - session := m.open(t, 600, false) - if err := session.ClickLabel("gamma"); err != nil { - t.Fatal(err) - } - if m.active != 2 { - t.Fatalf("active = %d after a click on gamma, want 2", m.active) - } -} - -// The close button of a tab, the Delete key and a middle click each report the -// tab, and a pinned tab offers none of them. -func TestClosingReportsTheTab(t *testing.T) { - m := newModel("alpha", "beta", "gamma") - m.tabs[0].Pinned = true - session := m.open(t, 600, false) - closeButtons := 0 - var first gfx.Hit - for _, hit := range session.Driver().Snapshot().Hits { - if hit.Label == "Close" { - if closeButtons == 0 { - first = hit - } - closeButtons++ - } - } - if closeButtons != 2 { - t.Fatalf("close buttons = %d, want one for each tab that is not pinned (2)", closeButtons) - } - if err := session.Click(first.Bounds.X+first.Bounds.Width/2, first.Bounds.Y+first.Bounds.Height/2); err != nil { - t.Fatal(err) - } - if len(m.closed) != 1 || m.closed[0] != 1 { - t.Fatalf("closed = %v after the close button of beta, want [1]", m.closed) - } - // Delete on the focused tab closes it; the pinned first tab is not closed by it. - if err := session.ClickLabel("alpha"); err != nil { - t.Fatal(err) - } - if err := session.Keys("delete"); err != nil { - t.Fatal(err) - } - if len(m.closed) != 1 { - t.Fatalf("Delete closed a pinned tab: %v", m.closed) - } - if err := session.Keys("right"); err != nil { - t.Fatal(err) - } - if err := session.Keys("delete"); err != nil { - t.Fatal(err) - } - if len(m.closed) != 2 || m.closed[1] != 1 { - t.Fatalf("closed = %v after Right and Delete, want [1 1]", m.closed) - } -} - -func TestMiddleClickClosesATab(t *testing.T) { - m := newModel("alpha", "beta") - session := m.open(t, 600, false) - hit, err := session.Locate("beta") - if err != nil { - t.Fatal(err) - } - x, y := hit.Bounds.X+hit.Bounds.Width/3, hit.Bounds.Y+hit.Bounds.Height/2 - if err := session.Driver().ClickButton(x, y, gfx.PointerButtonMiddle); err != nil { - t.Fatal(err) - } - if len(m.closed) != 1 || m.closed[0] != 1 { - t.Fatalf("closed = %v after a middle click on beta, want [1]", m.closed) - } -} - -// The arrow keys move the focus and make the tab active, Home and End go to the -// ends, and the add button is reached with Right and pressed with Enter. -func TestKeysMoveThroughTheStripAndAdd(t *testing.T) { - m := newModel("alpha", "beta", "gamma") - session := m.open(t, 600, true) - if err := session.Keys("tab"); err != nil { - t.Fatal(err) - } - for _, step := range []struct { - key string - want int - }{{"right", 1}, {"end", 2}, {"left", 1}, {"home", 0}} { - if err := session.Keys(step.key); err != nil { - t.Fatal(err) - } - if m.active != step.want { - t.Fatalf("active = %d after %q, want %d", m.active, step.key, step.want) - } - } - session.Keys("end") - session.Keys("right") // past the last tab: onto the add button - if err := session.Keys("enter"); err != nil { - t.Fatal(err) - } - if m.added != 1 || len(m.tabs) != 4 || m.active != 3 { - t.Fatalf("added %d, tabs %d, active %d after Enter on the add button; want 1, 4, 3", m.added, len(m.tabs), m.active) - } -} - -// The add button is a button of its own, and absent unless asked for. -func TestAddButtonOnlyWhenAddable(t *testing.T) { - for _, addable := range []bool{false, true} { - m := newModel("alpha") - session := m.open(t, 600, addable) - _, err := session.Locate("Add tab") - if (err == nil) != addable { - t.Fatalf("addable %v: add button present = %v", addable, err == nil) - } - } -} - -// A strip longer than its room scrolls with the wheel and keeps the active tab in view. -func TestLongStripScrollsAndKeepsTheActiveTabInView(t *testing.T) { - m := newModel("first tab", "second tab", "third tab", "fourth tab", "fifth tab", "sixth tab") - session := m.open(t, 300, false) - if err := session.ClickLabel("first tab"); err != nil { - t.Fatal(err) - } - session.Keys("end") - hit, err := session.Locate("sixth tab") - if err != nil { - t.Fatal(err) - } - if hit.Bounds.X+hit.Bounds.Width > 300.5 || hit.Bounds.X < -0.5 { - t.Fatalf("the active tab is at %+v, outside a 300 wide strip", hit.Bounds) - } -} - func TestWarmPaintAllocatesNothing(t *testing.T) { m := newModel("alpha", "beta", "gamma") m.tabs[0].Pinned = true diff --git a/ui/inputnumber/inputnumber_paint_test.go b/ui/inputnumber/inputnumber_paint_test.go new file mode 100644 index 00000000..c4022f3e --- /dev/null +++ b/ui/inputnumber/inputnumber_paint_test.go @@ -0,0 +1,46 @@ +package inputnumber_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputnumber" +) + +func TestWarmPaintAllocatesNothing(t *testing.T) { + value := 12.5 + n := inputnumber.New().Step(0.5).Min(0).Max(100) + view := func(c ui.C) { n.View(c, "Port", &value).Width(200) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 360, Height: 200}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + value := 12.5 + n := inputnumber.New().Step(0.5).Min(0).Max(100) + view := func(c ui.C) { n.View(c, "Port", &value).Width(200) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 360, Height: 200}, view) + canvas.EndFrame() + } +} diff --git a/ui/inputnumber/inputnumber_test.go b/ui/inputnumber/inputnumber_test.go index dbcf6a3e..54b1d9f5 100644 --- a/ui/inputnumber/inputnumber_test.go +++ b/ui/inputnumber/inputnumber_test.go @@ -1,4 +1,4 @@ -//go:build !js +//go:build darwin || windows || linux package inputnumber_test @@ -6,7 +6,6 @@ import ( "testing" "github.com/vivaui/viva/app" - "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/inputnumber" @@ -186,40 +185,3 @@ func TestReadOnlyTakesNoInput(t *testing.T) { t.Fatalf("value = %v after input on a read only field, want 3", value) } } - -func TestWarmPaintAllocatesNothing(t *testing.T) { - value := 12.5 - n := inputnumber.New().Step(0.5).Min(0).Max(100) - view := func(c ui.C) { n.View(c, "Port", &value).Width(200) } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - draw := func() { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 360, Height: 200}, view) - canvas.EndFrame() - } - draw() - if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { - t.Fatalf("warm paint allocated %v times, want 0", allocations) - } -} - -func BenchmarkViewPaint(b *testing.B) { - value := 12.5 - n := inputnumber.New().Step(0.5).Min(0).Max(100) - view := func(c ui.C) { n.View(c, "Port", &value).Width(200) } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - b.ReportAllocs() - for range b.N { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 360, Height: 200}, view) - canvas.EndFrame() - } -} diff --git a/ui/pagination/pagination_desktop_test.go b/ui/pagination/pagination_desktop_test.go new file mode 100644 index 00000000..fadfccd5 --- /dev/null +++ b/ui/pagination/pagination_desktop_test.go @@ -0,0 +1,134 @@ +//go:build darwin || windows || linux + +package pagination_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/pagination" +) + +var changes int + +func open(t *testing.T, state *pagination.State, spec pagination.Spec) *headless.Session { + t.Helper() + changes = 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + pagination.View(c, "Pages", state, spec) + if state.Changed() { + changes++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Pages", Width: 900, Height: 160}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// Next and Previous move one page, and the numbers jump; each change is reported +// once. +func TestControlsMoveThroughThePages(t *testing.T) { + state := &pagination.State{PageSize: 10} + session := open(t, state, pagination.Spec{Total: 95}) + if state.Page != 1 { + t.Fatalf("Page = %d at the start, want 1", state.Page) + } + if err := session.ClickLabel("Next"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("5"); err != nil { + t.Fatal(err) + } + if state.Page != 5 || changes != 2 { + t.Fatalf("Page = %d after Next and 5, changes %d; want 5 and 2", state.Page, changes) + } + if err := session.ClickLabel("Previous"); err != nil { + t.Fatal(err) + } + if state.Page != 4 { + t.Fatalf("Page = %d after Previous, want 4", state.Page) + } +} + +// Previous is dimmed on the first page and Next on the last. +func TestEndsOfTheRangeCannotBePressed(t *testing.T) { + state := &pagination.State{PageSize: 10, Page: 1} + session := open(t, state, pagination.Spec{Total: 25}) + if err := session.ClickLabel("Previous"); err == nil { + t.Fatal("Previous could be pressed on the first page") + } + state.Page = 3 + session.Frame() + if err := session.ClickLabel("Next"); err == nil { + t.Fatal("Next could be pressed on the last page") + } +} + +// A Total that shrinks brings the page back into range; the row of a long run of +// pages keeps the first and last page and a window around the current one. +func TestPageIsKeptInRangeAndLongRunsCollapse(t *testing.T) { + state := &pagination.State{PageSize: 10, Page: 9} + session := open(t, state, pagination.Spec{Total: 30}) + if state.Page != 3 { + t.Fatalf("Page = %d after Total shrank to 3 pages, want 3", state.Page) + } + long := &pagination.State{PageSize: 10, Page: 10} + session = open(t, long, pagination.Spec{Total: 200}) + buttons := map[string]bool{} + for _, node := range session.Access() { + if node.Role == gfx.RoleButton { + buttons[node.Label] = true + } + } + for _, shown := range []string{"1", "9", "10", "11", "20"} { + if !buttons[shown] { + t.Fatalf("page %s is not in the row", shown) + } + } + for _, hidden := range []string{"2", "5", "15"} { + if buttons[hidden] { + t.Fatalf("page %s is in the row though it collapsed", hidden) + } + } +} + +// Changing the page size keeps the first row of the page in view. +func TestPageSizeChangeKeepsTheFirstRow(t *testing.T) { + state := &pagination.State{PageSize: 10, Page: 5} // rows 40..49 + session := open(t, state, pagination.Spec{Total: 200, SizeOptions: []int{10, 20, 50}}) + if err := session.ClickLabel("Rows per page"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("20"); err != nil { + t.Fatal(err) + } + if state.PageSize != 20 || state.Page != 3 { + t.Fatalf("PageSize %d, Page %d after choosing 20 on page 5 of 10, want 20 and 3", state.PageSize, state.Page) + } +} + +// The jumper takes a page number and goes to it, clamped. +func TestJumperGoesToThePage(t *testing.T) { + state := &pagination.State{PageSize: 10} + session := open(t, state, pagination.Spec{Total: 95, Jumper: true}) + if err := session.ClickLabel("Go to page"); err != nil { + t.Fatal(err) + } + if err := session.Type("7"); err != nil { + t.Fatal(err) + } + if err := session.Keys("enter"); err != nil { + t.Fatal(err) + } + if state.Page != 7 { + t.Fatalf("Page = %d after typing 7 and Enter, want 7", state.Page) + } +} diff --git a/ui/pagination/pagination_test.go b/ui/pagination/pagination_test.go index 05499222..8445cbed 100644 --- a/ui/pagination/pagination_test.go +++ b/ui/pagination/pagination_test.go @@ -1,138 +1,13 @@ -//go:build !js - package pagination_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/pagination" ) -var changes int - -func open(t *testing.T, state *pagination.State, spec pagination.Spec) *headless.Session { - t.Helper() - changes = 0 - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - ui.Column(c).Pad(16).Children(func() { - pagination.View(c, "Pages", state, spec) - if state.Changed() { - changes++ - } - }) - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Pages", Width: 900, Height: 160}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(session.Close) - return session -} - -// Next and Previous move one page, and the numbers jump; each change is reported -// once. -func TestControlsMoveThroughThePages(t *testing.T) { - state := &pagination.State{PageSize: 10} - session := open(t, state, pagination.Spec{Total: 95}) - if state.Page != 1 { - t.Fatalf("Page = %d at the start, want 1", state.Page) - } - if err := session.ClickLabel("Next"); err != nil { - t.Fatal(err) - } - if err := session.ClickLabel("5"); err != nil { - t.Fatal(err) - } - if state.Page != 5 || changes != 2 { - t.Fatalf("Page = %d after Next and 5, changes %d; want 5 and 2", state.Page, changes) - } - if err := session.ClickLabel("Previous"); err != nil { - t.Fatal(err) - } - if state.Page != 4 { - t.Fatalf("Page = %d after Previous, want 4", state.Page) - } -} - -// Previous is dimmed on the first page and Next on the last. -func TestEndsOfTheRangeCannotBePressed(t *testing.T) { - state := &pagination.State{PageSize: 10, Page: 1} - session := open(t, state, pagination.Spec{Total: 25}) - if err := session.ClickLabel("Previous"); err == nil { - t.Fatal("Previous could be pressed on the first page") - } - state.Page = 3 - session.Frame() - if err := session.ClickLabel("Next"); err == nil { - t.Fatal("Next could be pressed on the last page") - } -} - -// A Total that shrinks brings the page back into range; the row of a long run of -// pages keeps the first and last page and a window around the current one. -func TestPageIsKeptInRangeAndLongRunsCollapse(t *testing.T) { - state := &pagination.State{PageSize: 10, Page: 9} - session := open(t, state, pagination.Spec{Total: 30}) - if state.Page != 3 { - t.Fatalf("Page = %d after Total shrank to 3 pages, want 3", state.Page) - } - long := &pagination.State{PageSize: 10, Page: 10} - session = open(t, long, pagination.Spec{Total: 200}) - buttons := map[string]bool{} - for _, node := range session.Access() { - if node.Role == gfx.RoleButton { - buttons[node.Label] = true - } - } - for _, shown := range []string{"1", "9", "10", "11", "20"} { - if !buttons[shown] { - t.Fatalf("page %s is not in the row", shown) - } - } - for _, hidden := range []string{"2", "5", "15"} { - if buttons[hidden] { - t.Fatalf("page %s is in the row though it collapsed", hidden) - } - } -} - -// Changing the page size keeps the first row of the page in view. -func TestPageSizeChangeKeepsTheFirstRow(t *testing.T) { - state := &pagination.State{PageSize: 10, Page: 5} // rows 40..49 - session := open(t, state, pagination.Spec{Total: 200, SizeOptions: []int{10, 20, 50}}) - if err := session.ClickLabel("Rows per page"); err != nil { - t.Fatal(err) - } - if err := session.ClickLabel("20"); err != nil { - t.Fatal(err) - } - if state.PageSize != 20 || state.Page != 3 { - t.Fatalf("PageSize %d, Page %d after choosing 20 on page 5 of 10, want 20 and 3", state.PageSize, state.Page) - } -} - -// The jumper takes a page number and goes to it, clamped. -func TestJumperGoesToThePage(t *testing.T) { - state := &pagination.State{PageSize: 10} - session := open(t, state, pagination.Spec{Total: 95, Jumper: true}) - if err := session.ClickLabel("Go to page"); err != nil { - t.Fatal(err) - } - if err := session.Type("7"); err != nil { - t.Fatal(err) - } - if err := session.Keys("enter"); err != nil { - t.Fatal(err) - } - if state.Page != 7 { - t.Fatalf("Page = %d after typing 7 and Enter, want 7", state.Page) - } -} - func TestWarmPaintAllocatesNothing(t *testing.T) { state := &pagination.State{PageSize: 10, Page: 5} spec := pagination.Spec{Total: 500, ShowTotal: true, SizeOptions: []int{10, 20, 50}, Jumper: true} diff --git a/ui/popconfirm/popconfirm_desktop_test.go b/ui/popconfirm/popconfirm_desktop_test.go new file mode 100644 index 00000000..845fc045 --- /dev/null +++ b/ui/popconfirm/popconfirm_desktop_test.go @@ -0,0 +1,93 @@ +//go:build darwin || windows || linux + +package popconfirm_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/popconfirm" +) + +type model struct { + pc *popconfirm.Popconfirm + danger bool + confirmed, cancelled int +} + +func (m *model) open(t *testing.T) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + trigger := ui.Button(c, "Remove").Outline() + if trigger.Clicked() { + m.pc.Open() + } + m.pc.View(c, trigger, popconfirm.Spec{Title: "Remove build-01?", Description: "It cannot be undone.", OkLabel: "Yes", Danger: m.danger}) + if m.pc.Confirmed() { + m.confirmed++ + } + if m.pc.Cancelled() { + m.cancelled++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Pop", Width: 480, Height: 320}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// The question shows only after the trigger opens it; confirming reports once and +// closes it. +func TestConfirmReportsOnceAndCloses(t *testing.T) { + m := &model{pc: popconfirm.New()} + session := m.open(t) + if err := session.Expect("text", "Remove build-01?"); err == nil { + t.Fatal("the question shows before it was opened") + } + if err := session.ClickLabel("Remove"); err != nil { + t.Fatal(err) + } + if err := session.Expect("text", "Remove build-01?"); err != nil { + t.Fatal(err) + } + if err := session.ClickLabel("Yes"); err != nil { + t.Fatal(err) + } + if m.confirmed != 1 || m.cancelled != 0 { + t.Fatalf("confirmed %d, cancelled %d after pressing Yes, want 1, 0", m.confirmed, m.cancelled) + } + if m.pc.IsOpen() { + t.Fatal("the question stayed open after an answer") + } +} + +func TestCancelReportsAndCloses(t *testing.T) { + m := &model{pc: popconfirm.New()} + session := m.open(t) + session.ClickLabel("Remove") + if err := session.ClickLabel("Cancel"); err != nil { + t.Fatal(err) + } + if m.cancelled != 1 || m.confirmed != 0 || m.pc.IsOpen() { + t.Fatalf("cancelled %d, confirmed %d, open %v after Cancel", m.cancelled, m.confirmed, m.pc.IsOpen()) + } +} + +// Escape closes the question without answering it. +func TestEscapeClosesWithoutAnswering(t *testing.T) { + m := &model{pc: popconfirm.New()} + session := m.open(t) + session.ClickLabel("Remove") + if err := session.Keys("escape"); err != nil { + t.Fatal(err) + } + if m.pc.IsOpen() || m.confirmed != 0 || m.cancelled != 0 { + t.Fatalf("open %v, confirmed %d, cancelled %d after Escape", m.pc.IsOpen(), m.confirmed, m.cancelled) + } +} diff --git a/ui/popconfirm/popconfirm_test.go b/ui/popconfirm/popconfirm_test.go index 398ddffa..389edf01 100644 --- a/ui/popconfirm/popconfirm_test.go +++ b/ui/popconfirm/popconfirm_test.go @@ -1,98 +1,13 @@ -//go:build !js - package popconfirm_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/popconfirm" ) -type model struct { - pc *popconfirm.Popconfirm - danger bool - confirmed, cancelled int -} - -func (m *model) open(t *testing.T) *headless.Session { - t.Helper() - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - ui.Column(c).Pad(16).Children(func() { - trigger := ui.Button(c, "Remove").Outline() - if trigger.Clicked() { - m.pc.Open() - } - m.pc.View(c, trigger, popconfirm.Spec{Title: "Remove build-01?", Description: "It cannot be undone.", OkLabel: "Yes", Danger: m.danger}) - if m.pc.Confirmed() { - m.confirmed++ - } - if m.pc.Cancelled() { - m.cancelled++ - } - }) - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Pop", Width: 480, Height: 320}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(session.Close) - return session -} - -// The question shows only after the trigger opens it; confirming reports once and -// closes it. -func TestConfirmReportsOnceAndCloses(t *testing.T) { - m := &model{pc: popconfirm.New()} - session := m.open(t) - if err := session.Expect("text", "Remove build-01?"); err == nil { - t.Fatal("the question shows before it was opened") - } - if err := session.ClickLabel("Remove"); err != nil { - t.Fatal(err) - } - if err := session.Expect("text", "Remove build-01?"); err != nil { - t.Fatal(err) - } - if err := session.ClickLabel("Yes"); err != nil { - t.Fatal(err) - } - if m.confirmed != 1 || m.cancelled != 0 { - t.Fatalf("confirmed %d, cancelled %d after pressing Yes, want 1, 0", m.confirmed, m.cancelled) - } - if m.pc.IsOpen() { - t.Fatal("the question stayed open after an answer") - } -} - -func TestCancelReportsAndCloses(t *testing.T) { - m := &model{pc: popconfirm.New()} - session := m.open(t) - session.ClickLabel("Remove") - if err := session.ClickLabel("Cancel"); err != nil { - t.Fatal(err) - } - if m.cancelled != 1 || m.confirmed != 0 || m.pc.IsOpen() { - t.Fatalf("cancelled %d, confirmed %d, open %v after Cancel", m.cancelled, m.confirmed, m.pc.IsOpen()) - } -} - -// Escape closes the question without answering it. -func TestEscapeClosesWithoutAnswering(t *testing.T) { - m := &model{pc: popconfirm.New()} - session := m.open(t) - session.ClickLabel("Remove") - if err := session.Keys("escape"); err != nil { - t.Fatal(err) - } - if m.pc.IsOpen() || m.confirmed != 0 || m.cancelled != 0 { - t.Fatalf("open %v, confirmed %d, cancelled %d after Escape", m.pc.IsOpen(), m.confirmed, m.cancelled) - } -} - func TestWarmPaintAllocatesNothing(t *testing.T) { pc := popconfirm.New() pc.Open() diff --git a/ui/rate/rate_paint_test.go b/ui/rate/rate_paint_test.go new file mode 100644 index 00000000..be119296 --- /dev/null +++ b/ui/rate/rate_paint_test.go @@ -0,0 +1,46 @@ +package rate_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/rate" +) + +func TestWarmPaintAllocatesNothing(t *testing.T) { + score := float32(3.5) + r := rate.New().AllowHalf() + view := func(c ui.C) { r.View(c, "Rating", &score) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 120}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + score := float32(3.5) + r := rate.New().AllowHalf() + view := func(c ui.C) { r.View(c, "Rating", &score) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 120}, view) + canvas.EndFrame() + } +} diff --git a/ui/rate/rate_test.go b/ui/rate/rate_test.go index 0a176222..a75b3ad9 100644 --- a/ui/rate/rate_test.go +++ b/ui/rate/rate_test.go @@ -1,4 +1,4 @@ -//go:build !js +//go:build darwin || windows || linux package rate_test @@ -6,7 +6,6 @@ import ( "testing" "github.com/vivaui/viva/app" - "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/rate" @@ -161,40 +160,3 @@ func TestScoreIsKeptInRange(t *testing.T) { } } } - -func TestWarmPaintAllocatesNothing(t *testing.T) { - score := float32(3.5) - r := rate.New().AllowHalf() - view := func(c ui.C) { r.View(c, "Rating", &score) } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - draw := func() { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 320, Height: 120}, view) - canvas.EndFrame() - } - draw() - if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { - t.Fatalf("warm paint allocated %v times, want 0", allocations) - } -} - -func BenchmarkViewPaint(b *testing.B) { - score := float32(3.5) - r := rate.New().AllowHalf() - view := func(c ui.C) { r.View(c, "Rating", &score) } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - b.ReportAllocs() - for range b.N { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 320, Height: 120}, view) - canvas.EndFrame() - } -} diff --git a/ui/result/result_desktop_test.go b/ui/result/result_desktop_test.go new file mode 100644 index 00000000..9890d2ce --- /dev/null +++ b/ui/result/result_desktop_test.go @@ -0,0 +1,27 @@ +//go:build darwin || windows || linux + +package result_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/result" +) + +func TestResultIsAStatusNamedByItsTitle(t *testing.T) { + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + result.View(c, result.Spec{Status: ui.StatusSuccess, Title: "Key imported"}, nil).Fill() + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Result", Width: 480, Height: 320}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + if node, ok := session.AccessByName("Key imported"); !ok || node.Role != gfx.RoleStatus { + t.Fatalf("access node = %+v, %v; want a status named by the title", node, ok) + } +} diff --git a/ui/result/result_test.go b/ui/result/result_test.go index b35a6eb6..ac07a06e 100644 --- a/ui/result/result_test.go +++ b/ui/result/result_test.go @@ -1,13 +1,9 @@ -//go:build !js - package result_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/result" ) @@ -32,9 +28,7 @@ func open(t testing.TB, view func(ui.C)) (*ui.Page, *gfx.Canvas) { return page, canvas } -// The icon takes the color of the status, and the result is announced as a -// status named by its title. -func TestStatusColorsTheIconAndNamesTheResult(t *testing.T) { +func TestStatusColorsTheIcon(t *testing.T) { theme := gfx.LightTheme() for name, test := range map[string]struct { status ui.Status @@ -58,17 +52,6 @@ func TestStatusColorsTheIconAndNamesTheResult(t *testing.T) { t.Fatalf("%s: no part of the icon is painted in %+v", name, test.want) } } - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - result.View(c, result.Spec{Status: ui.StatusSuccess, Title: "Key imported"}, nil).Fill() - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Result", Width: 480, Height: 320}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - defer session.Close() - if node, ok := session.AccessByName("Key imported"); !ok || node.Role != gfx.RoleStatus { - t.Fatalf("access node = %+v, %v; want a status named by the title", node, ok) - } } // The actions sit under the words and are page controls of their own. diff --git a/ui/steps/steps_desktop_test.go b/ui/steps/steps_desktop_test.go new file mode 100644 index 00000000..d3766014 --- /dev/null +++ b/ui/steps/steps_desktop_test.go @@ -0,0 +1,32 @@ +//go:build darwin || windows || linux + +package steps_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/steps" +) + +// A clickable step is a button for the keyboard too: Tab reaches it and Enter +// chooses it. +func TestStepsChooseWithTheKeyboard(t *testing.T) { + current := 0 + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + steps.View(c, "Checkout", ¤t, steps.Spec{Steps: items, Clickable: true}).FillWidth() + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Steps", Width: 480, Height: 200}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + session.Keys("tab") + session.Keys("tab") + session.Keys("enter") + if current != 1 { + t.Fatalf("current = %d after Tab, Tab and Enter, want the second step", current) + } +} diff --git a/ui/steps/steps_test.go b/ui/steps/steps_test.go index 7031fff8..5f3927ef 100644 --- a/ui/steps/steps_test.go +++ b/ui/steps/steps_test.go @@ -1,13 +1,9 @@ -//go:build !js - package steps_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/steps" ) @@ -137,26 +133,6 @@ func TestStepsClickMovesTheCurrentStep(t *testing.T) { } } -// A clickable step is a button for the keyboard too: Tab reaches it and Enter -// chooses it. -func TestStepsChooseWithTheKeyboard(t *testing.T) { - current := 0 - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - steps.View(c, "Checkout", ¤t, steps.Spec{Steps: items, Clickable: true}).FillWidth() - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Steps", Width: 480, Height: 200}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(session.Close) - session.Keys("tab") - session.Keys("tab") - session.Keys("enter") - if current != 1 { - t.Fatalf("current = %d after Tab, Tab and Enter, want the second step", current) - } -} - func TestWarmPaintAllocatesNothing(t *testing.T) { for name, spec := range map[string]steps.Spec{ "horizontal": {Steps: items, Clickable: true}, diff --git a/ui/tag/tag_desktop_test.go b/ui/tag/tag_desktop_test.go new file mode 100644 index 00000000..c95645f5 --- /dev/null +++ b/ui/tag/tag_desktop_test.go @@ -0,0 +1,75 @@ +//go:build darwin || windows || linux + +package tag_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/tag" +) + +// open runs a page of one tag and reports what the page read from it. +func open(t *testing.T, spec tag.Spec, closed, toggled *int) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + result := tag.View(c, "production", spec) + if result.Closed { + *closed++ + } + if result.Toggled { + *toggled++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Tag", Width: 320, Height: 120}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + return session +} + +// A press on the close button is reported as Closed once, and not as a toggle. +func TestCloseButtonIsReported(t *testing.T) { + var closed, toggled int + session := open(t, tag.Spec{Closable: true}, &closed, &toggled) + if err := session.ClickLabel("Remove"); err != nil { + t.Fatal(err) + } + if closed != 1 || toggled != 0 { + t.Fatalf("closed %d, toggled %d after a press on the close button, want 1, 0", closed, toggled) + } +} + +// A checkable tag is a checkbox that reports each press, and shows its state to +// assistive technology. +func TestCheckableTagToggles(t *testing.T) { + var closed, toggled int + session := open(t, tag.Spec{Checkable: true, Checked: true}, &closed, &toggled) + node, ok := session.AccessByName("production") + if !ok || node.Role != gfx.RoleCheckbox || !node.Checked { + t.Fatalf("access node = %+v, %v; want a checked checkbox", node, ok) + } + if err := session.ClickLabel("production"); err != nil { + t.Fatal(err) + } + if toggled != 1 { + t.Fatalf("toggled %d after one press, want 1", toggled) + } +} + +// A plain tag takes no input: no control to press. +func TestPlainTagOffersNothingToPress(t *testing.T) { + var closed, toggled int + session := open(t, tag.Spec{}, &closed, &toggled) + for _, name := range []string{"production", "Remove"} { + if _, err := session.Locate(name); err == nil { + t.Fatalf("a plain tag offers %q as a control", name) + } + } +} diff --git a/ui/tag/tag_test.go b/ui/tag/tag_test.go index 18bd4274..2d113003 100644 --- a/ui/tag/tag_test.go +++ b/ui/tag/tag_test.go @@ -1,79 +1,13 @@ -//go:build !js - package tag_test import ( "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/tag" ) -// open runs a page of one tag and reports what the page read from it. -func open(t *testing.T, spec tag.Spec, closed, toggled *int) *headless.Session { - t.Helper() - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - ui.Column(c).Pad(16).Children(func() { - result := tag.View(c, "production", spec) - if result.Closed { - *closed++ - } - if result.Toggled { - *toggled++ - } - }) - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Tag", Width: 320, Height: 120}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(session.Close) - return session -} - -// A press on the close button is reported as Closed once, and not as a toggle. -func TestCloseButtonIsReported(t *testing.T) { - var closed, toggled int - session := open(t, tag.Spec{Closable: true}, &closed, &toggled) - if err := session.ClickLabel("Remove"); err != nil { - t.Fatal(err) - } - if closed != 1 || toggled != 0 { - t.Fatalf("closed %d, toggled %d after a press on the close button, want 1, 0", closed, toggled) - } -} - -// A checkable tag is a checkbox that reports each press, and shows its state to -// assistive technology. -func TestCheckableTagToggles(t *testing.T) { - var closed, toggled int - session := open(t, tag.Spec{Checkable: true, Checked: true}, &closed, &toggled) - node, ok := session.AccessByName("production") - if !ok || node.Role != gfx.RoleCheckbox || !node.Checked { - t.Fatalf("access node = %+v, %v; want a checked checkbox", node, ok) - } - if err := session.ClickLabel("production"); err != nil { - t.Fatal(err) - } - if toggled != 1 { - t.Fatalf("toggled %d after one press, want 1", toggled) - } -} - -// A plain tag takes no input: no control to press. -func TestPlainTagOffersNothingToPress(t *testing.T) { - var closed, toggled int - session := open(t, tag.Spec{}, &closed, &toggled) - for _, name := range []string{"production", "Remove"} { - if _, err := session.Locate(name); err == nil { - t.Fatalf("a plain tag offers %q as a control", name) - } - } -} - // Each status paints its words in its color, and a checked tag takes the primary. func TestStatusAndCheckColorTheLabel(t *testing.T) { theme := gfx.LightTheme() diff --git a/ui/timepicker/timepicker_paint_test.go b/ui/timepicker/timepicker_paint_test.go new file mode 100644 index 00000000..85a0eca7 --- /dev/null +++ b/ui/timepicker/timepicker_paint_test.go @@ -0,0 +1,50 @@ +package timepicker_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/timepicker" +) + +func at(hour, minute, second int) timepicker.Value { + return timepicker.Value{Hour: hour, Minute: minute, Second: second, Valid: true} +} + +func TestWarmPaintAllocatesNothing(t *testing.T) { + value := at(9, 30, 0) + p := timepicker.New().Seconds() + view := func(c ui.C) { p.View(c, "Start", &value).Width(220) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 420}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + value := at(9, 30, 0) + p := timepicker.New().Seconds() + view := func(c ui.C) { p.View(c, "Start", &value).Width(220) } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 420}, view) + canvas.EndFrame() + } +} diff --git a/ui/timepicker/timepicker_test.go b/ui/timepicker/timepicker_test.go index 7a792b57..160c8e49 100644 --- a/ui/timepicker/timepicker_test.go +++ b/ui/timepicker/timepicker_test.go @@ -1,4 +1,4 @@ -//go:build !js +//go:build darwin || windows || linux package timepicker_test @@ -6,7 +6,6 @@ import ( "testing" "github.com/vivaui/viva/app" - "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/timepicker" @@ -35,10 +34,6 @@ func open(t *testing.T, p *timepicker.TimePicker, value *timepicker.Value) *head return session } -func at(hour, minute, second int) timepicker.Value { - return timepicker.Value{Hour: hour, Minute: minute, Second: second, Valid: true} -} - // A click on a number sets that part of the time at once. func TestClickingANumberSetsThatPart(t *testing.T) { value := at(9, 30, 0) @@ -126,26 +121,6 @@ func TestTimesAreKeptOnTheSteps(t *testing.T) { } } -func TestWarmPaintAllocatesNothing(t *testing.T) { - value := at(9, 30, 0) - p := timepicker.New().Seconds() - view := func(c ui.C) { p.View(c, "Start", &value).Width(220) } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - draw := func() { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 420, Height: 420}, view) - canvas.EndFrame() - } - draw() - if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { - t.Fatalf("warm paint allocated %v times, want 0", allocations) - } -} - // Open columns repaint without allocating too. func TestOpenColumnsAllocateNothing(t *testing.T) { value := at(9, 30, 0) @@ -158,20 +133,3 @@ func TestOpenColumnsAllocateNothing(t *testing.T) { t.Fatalf("open columns allocated %v times a frame, want 0", allocations) } } - -func BenchmarkViewPaint(b *testing.B) { - value := at(9, 30, 0) - p := timepicker.New().Seconds() - view := func(c ui.C) { p.View(c, "Start", &value).Width(220) } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - b.ReportAllocs() - for range b.N { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 420, Height: 420}, view) - canvas.EndFrame() - } -} diff --git a/ui/transfer/transfer_paint_test.go b/ui/transfer/transfer_paint_test.go new file mode 100644 index 00000000..7e7c510e --- /dev/null +++ b/ui/transfer/transfer_paint_test.go @@ -0,0 +1,49 @@ +package transfer_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/transfer" +) + +func TestWarmPaintAllocatesNothing(t *testing.T) { + items := []transfer.Item{{Title: "alpha"}, {Title: "beta", Checked: true}, {Title: "gamma", Target: true}} + tr := transfer.New() + view := func(c ui.C) { tr.View(c, "Groups", transfer.Spec{Items: items}).FillWidth() } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 420}, view) + canvas.EndFrame() + } + draw() + if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { + t.Fatalf("warm paint allocated %v times, want 0", allocations) + } +} + +func BenchmarkViewPaint(b *testing.B) { + items := make([]transfer.Item, 200) + for i := range items { + items[i] = transfer.Item{Title: "host", Target: i%3 == 0, Checked: i%5 == 0} + } + tr := transfer.New() + view := func(c ui.C) { tr.View(c, "Groups", transfer.Spec{Items: items}).FillWidth() } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + b.ReportAllocs() + for range b.N { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 640, Height: 420}, view) + canvas.EndFrame() + } +} diff --git a/ui/transfer/transfer_test.go b/ui/transfer/transfer_test.go index 2cf59434..0ee34996 100644 --- a/ui/transfer/transfer_test.go +++ b/ui/transfer/transfer_test.go @@ -1,4 +1,4 @@ -//go:build !js +//go:build darwin || windows || linux package transfer_test @@ -6,7 +6,6 @@ import ( "testing" "github.com/vivaui/viva/app" - "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/transfer" @@ -117,43 +116,3 @@ func TestTickForAllFollowsTheItems(t *testing.T) { t.Fatalf("items stayed ticked after the tick for all was cleared: %v %v", items[0].Checked, items[1].Checked) } } - -func TestWarmPaintAllocatesNothing(t *testing.T) { - items := []transfer.Item{{Title: "alpha"}, {Title: "beta", Checked: true}, {Title: "gamma", Target: true}} - tr := transfer.New() - view := func(c ui.C) { tr.View(c, "Groups", transfer.Spec{Items: items}).FillWidth() } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - draw := func() { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 640, Height: 420}, view) - canvas.EndFrame() - } - draw() - if allocations := testing.AllocsPerRun(100, draw); allocations != 0 { - t.Fatalf("warm paint allocated %v times, want 0", allocations) - } -} - -func BenchmarkViewPaint(b *testing.B) { - items := make([]transfer.Item, 200) - for i := range items { - items[i] = transfer.Item{Title: "host", Target: i%3 == 0, Checked: i%5 == 0} - } - tr := transfer.New() - view := func(c ui.C) { tr.View(c, "Groups", transfer.Spec{Items: items}).FillWidth() } - theme := gfx.LightTheme() - page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) - canvas := &gfx.Canvas{} - canvas.SetReduceMotion(true) - b.ReportAllocs() - for range b.N { - canvas.BeginFrame() - canvas.Reset() - page.Draw(canvas, gfx.Rect{Width: 640, Height: 420}, view) - canvas.EndFrame() - } -} diff --git a/ui/typography/typography_desktop_test.go b/ui/typography/typography_desktop_test.go new file mode 100644 index 00000000..4b23c351 --- /dev/null +++ b/ui/typography/typography_desktop_test.go @@ -0,0 +1,96 @@ +//go:build darwin || windows || linux + +package typography_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/typography" +) + +func open(t *testing.T, tx *typography.Text, value string, spec typography.Spec) *headless.Session { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { tx.View(c, value, spec).FillWidth() }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Text", Width: 420, Height: 360}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + session.Frame() // the second paint knows the width and so whether the text is cut + return session +} + +func lines(session *headless.Session) int { + n := 0 + for _, text := range session.Driver().Snapshot().Texts { + if len(text.Value) > 20 { + n++ + } + } + return n +} + +// A text longer than Rows is cut to Rows lines with a button to read the rest, and +// the button takes the rest away again. +func TestLongTextIsCutAndExpands(t *testing.T) { + tx := typography.New() + session := open(t, tx, long, typography.Spec{Rows: 2, Expandable: true}) + if got := lines(session); got != 2 { + t.Fatalf("lines shown = %d, want 2", got) + } + if err := session.ClickLabel("More"); err != nil { + t.Fatal(err) + } + if !tx.Expanded() || lines(session) <= 2 { + t.Fatalf("expanded %v, lines %d after More; want all the lines", tx.Expanded(), lines(session)) + } + if err := session.ClickLabel("Less"); err != nil { + t.Fatal(err) + } + if tx.Expanded() || lines(session) != 2 { + t.Fatalf("expanded %v, lines %d after Less; want cut to 2", tx.Expanded(), lines(session)) + } +} + +// A text that fits in Rows offers nothing to expand. +func TestShortTextHasNoMoreButton(t *testing.T) { + session := open(t, typography.New(), "A short line.", typography.Spec{Rows: 2, Expandable: true}) + if _, err := session.Locate("More"); err == nil { + t.Fatal("a text that fits offers More") + } +} + +// The copy button puts the whole text, not the cut one, on the clipboard, and +// Copied is reported in the paint that delivers the press. +func TestCopyPutsTheWholeTextOnTheClipboard(t *testing.T) { + tx := typography.New() + copied := 0 + spec := typography.Spec{Rows: 2, Copyable: true} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + tx.View(c, long, spec).FillWidth() + if tx.Copied() { + copied++ + } + }) + }}) + session, err := headless.Open(ui.Configure(page, app.Config{Title: "Text", Width: 420, Height: 360}), nil, headless.Options{Scale: 1}) + if err != nil { + t.Fatal(err) + } + defer session.Close() + if err := session.ClickLabel("Copy"); err != nil { + t.Fatal(err) + } + if copied != 1 { + t.Fatalf("Copied was reported in %d paints after one press, want 1", copied) + } + if got := session.Driver().Clipboard(); got != long { + t.Fatalf("clipboard holds %d characters, want the whole text (%d)", len(got), len(long)) + } +} diff --git a/ui/typography/typography_test.go b/ui/typography/typography_test.go index 0a03daf7..57a8b8cb 100644 --- a/ui/typography/typography_test.go +++ b/ui/typography/typography_test.go @@ -1,104 +1,16 @@ -//go:build !js - package typography_test import ( "strings" "testing" - "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" - "github.com/vivaui/viva/headless" "github.com/vivaui/viva/ui" "github.com/vivaui/viva/ui/typography" ) var long = strings.Repeat("Keeps scene nodes and repaints only when the content changes. ", 8) -func open(t *testing.T, tx *typography.Text, value string, spec typography.Spec) *headless.Session { - t.Helper() - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - ui.Column(c).Pad(16).Children(func() { tx.View(c, value, spec).FillWidth() }) - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Text", Width: 420, Height: 360}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - t.Cleanup(session.Close) - session.Frame() // the second paint knows the width and so whether the text is cut - return session -} - -func lines(session *headless.Session) int { - n := 0 - for _, text := range session.Driver().Snapshot().Texts { - if len(text.Value) > 20 { - n++ - } - } - return n -} - -// A text longer than Rows is cut to Rows lines with a button to read the rest, and -// the button takes the rest away again. -func TestLongTextIsCutAndExpands(t *testing.T) { - tx := typography.New() - session := open(t, tx, long, typography.Spec{Rows: 2, Expandable: true}) - if got := lines(session); got != 2 { - t.Fatalf("lines shown = %d, want 2", got) - } - if err := session.ClickLabel("More"); err != nil { - t.Fatal(err) - } - if !tx.Expanded() || lines(session) <= 2 { - t.Fatalf("expanded %v, lines %d after More; want all the lines", tx.Expanded(), lines(session)) - } - if err := session.ClickLabel("Less"); err != nil { - t.Fatal(err) - } - if tx.Expanded() || lines(session) != 2 { - t.Fatalf("expanded %v, lines %d after Less; want cut to 2", tx.Expanded(), lines(session)) - } -} - -// A text that fits in Rows offers nothing to expand. -func TestShortTextHasNoMoreButton(t *testing.T) { - session := open(t, typography.New(), "A short line.", typography.Spec{Rows: 2, Expandable: true}) - if _, err := session.Locate("More"); err == nil { - t.Fatal("a text that fits offers More") - } -} - -// The copy button puts the whole text, not the cut one, on the clipboard, and -// Copied is reported in the paint that delivers the press. -func TestCopyPutsTheWholeTextOnTheClipboard(t *testing.T) { - tx := typography.New() - copied := 0 - spec := typography.Spec{Rows: 2, Copyable: true} - page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { - ui.Column(c).Pad(16).Children(func() { - tx.View(c, long, spec).FillWidth() - if tx.Copied() { - copied++ - } - }) - }}) - session, err := headless.Open(ui.Configure(page, app.Config{Title: "Text", Width: 420, Height: 360}), nil, headless.Options{Scale: 1}) - if err != nil { - t.Fatal(err) - } - defer session.Close() - if err := session.ClickLabel("Copy"); err != nil { - t.Fatal(err) - } - if copied != 1 { - t.Fatalf("Copied was reported in %d paints after one press, want 1", copied) - } - if got := session.Driver().Clipboard(); got != long { - t.Fatalf("clipboard holds %d characters, want the whole text (%d)", len(got), len(long)) - } -} - func TestWarmPaintAllocatesNothing(t *testing.T) { tx := typography.New() spec := typography.Spec{Rows: 2, Expandable: true, Copyable: true} diff --git a/website/content/guides/en/getting-started.md b/website/content/guides/en/getting-started.md index d626db12..b57b0077 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.8`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.8`. 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.9`. Pin it by naming the version: `go get github.com/vivaui/viva@v0.6.9`. 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 b710f80b..d7d0ed80 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.8`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.8`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 +`go get` 不带版本号时取最新的正式版本,目前就是 `v0.6.9`。要固定版本就写明:`go get github.com/vivaui/viva@v0.6.9`。Viva 还没有到 1.0,所以小版本之间 `go.mod` 的 API 仍可能变化;升级前看一眼发版说明。 如果你是在 Viva 仓库里改框架本身、而不是使用它,改用 `replace` 指向检出目录: