From 9031a925852c5d97078af50e24ccd8e39e8929e2 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 23:26:22 +0800 Subject: [PATCH 01/23] test(ui): cover a menu taller than the window --- ui/menu_test.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/ui/menu_test.go b/ui/menu_test.go index 777516209..df0e8e548 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -4,6 +4,7 @@ import ( "testing" "time" + "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -509,3 +510,48 @@ func TestMenuAbove(t *testing.T) { t.Fatalf("the menu at %v is not over its anchor at %v", item, anchor) } } + +type tallMenuModel struct { + open bool + chosen string +} + +// A menu taller than the window scrolls: the keyboard reaches its last item and +// brings it into view, the wheel moves it, and choosing the last item works. +func TestMenuTallerThanTheWindowScrollsToItsLastItem(t *testing.T) { + m := &tallMenuModel{open: true} + names := []string{"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve"} + d := openPageWith(t, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + anchor := ui.Button(c, "More") + ui.Menu(c, anchor, &m.open, func(menu *ui.MenuItems) { + for _, name := range names { + if menu.Item(name).Clicked() { + m.chosen = name + } + } + }) + }) + }}, app.Config{Width: 300, Height: 160}) + window := gfx.Rect{Width: 300, Height: 160} + inside := func(label string) bool { + for _, hit := range d.driver.Snapshot().Hits { + if hit.Label == label && hit.Role == gfx.RoleMenuItem { + return hit.Bounds.Y >= 0 && hit.Bounds.Y+hit.Bounds.Height <= window.Height + } + } + return false + } + if !inside("One") || inside("Twelve") { + t.Fatalf("the first item is shown %v and the last %v before anything scrolled", inside("One"), inside("Twelve")) + } + d.key(gfx.KeyDown) + d.key(gfx.KeyEnd) + if !inside("Twelve") { + t.Fatal("End did not bring the last item into view") + } + d.click("Twelve") + if m.chosen != "Twelve" || m.open { + t.Fatalf("chosen %q, open %v", m.chosen, m.open) + } +} From 4168d4b48251762cbee174eeecd00cc99f54b001 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:39:58 +0800 Subject: [PATCH 02/23] fix(text): keep CRLF intact in line editing and code rows --- cmd/viva/templates/code_editor.go.txt | 3 +- cmd/viva/templates/code_editor_layout.go.txt | 6 +- components/code_editor.go | 3 +- components/code_editor_layout.go | 6 +- components/code_editor_test.go | 16 ++ components/code_editor_whitespace_test.go | 16 ++ text/editing.go | 51 ++++-- text/editing_test.go | 173 +++++++++++++++++++ 8 files changed, 256 insertions(+), 18 deletions(-) diff --git a/cmd/viva/templates/code_editor.go.txt b/cmd/viva/templates/code_editor.go.txt index 50e2117c1..00e041016 100644 --- a/cmd/viva/templates/code_editor.go.txt +++ b/cmd/viva/templates/code_editor.go.txt @@ -963,7 +963,8 @@ func (paint *codePaint) row(index int, y float32) { if paint.showWhitespace { paint.whitespace(row, y, left) } - if paint.showEOL && !editor.softWrapped(index) && rowEnd < len(paint.value) && paint.value[rowEnd] == '\n' { + if paint.showEOL && !editor.softWrapped(index) && rowEnd < len(paint.value) && + (paint.value[rowEnd] == '\n' || paint.value[rowEnd] == '\r' && rowEnd+1 < len(paint.value) && paint.value[rowEnd+1] == '\n') { paint.lineEnding(row, y, left) } if paint.showWrapSymbol && editor.softWrapped(index) { diff --git a/cmd/viva/templates/code_editor_layout.go.txt b/cmd/viva/templates/code_editor_layout.go.txt index 7b57ad48d..527c91970 100644 --- a/cmd/viva/templates/code_editor_layout.go.txt +++ b/cmd/viva/templates/code_editor_layout.go.txt @@ -158,6 +158,10 @@ func (editor *CodeEditor) fitWithRepresentations(value string, cols int, wrap bo if newline := strings.IndexByte(value[start:], '\n'); newline >= 0 { end = start + newline } + rowEnd := end + if end < len(value) && end > start && value[end-1] == '\r' { + rowEnd-- + } for foldIndex < len(editor.folds) && editor.folds[foldIndex].LastLine < line { foldIndex++ } @@ -167,7 +171,7 @@ func (editor *CodeEditor) fitWithRepresentations(value string, cols int, wrap bo hidden = fold.Header >= 0 && fold.LastLine > fold.Header && fold.Header < line && line <= fold.LastLine } if !hidden { - editor.appendLine(value, start, end, line) + editor.appendLine(value, start, rowEnd, line) } if end >= len(value) { break diff --git a/components/code_editor.go b/components/code_editor.go index b86a53d89..d4ed045cf 100644 --- a/components/code_editor.go +++ b/components/code_editor.go @@ -963,7 +963,8 @@ func (paint *codePaint) row(index int, y float32) { if paint.showWhitespace { paint.whitespace(row, y, left) } - if paint.showEOL && !editor.softWrapped(index) && rowEnd < len(paint.value) && paint.value[rowEnd] == '\n' { + if paint.showEOL && !editor.softWrapped(index) && rowEnd < len(paint.value) && + (paint.value[rowEnd] == '\n' || paint.value[rowEnd] == '\r' && rowEnd+1 < len(paint.value) && paint.value[rowEnd+1] == '\n') { paint.lineEnding(row, y, left) } if paint.showWrapSymbol && editor.softWrapped(index) { diff --git a/components/code_editor_layout.go b/components/code_editor_layout.go index 3060ee089..b633fe37f 100644 --- a/components/code_editor_layout.go +++ b/components/code_editor_layout.go @@ -158,6 +158,10 @@ func (editor *CodeEditor) fitWithRepresentations(value string, cols int, wrap bo if newline := strings.IndexByte(value[start:], '\n'); newline >= 0 { end = start + newline } + rowEnd := end + if end < len(value) && end > start && value[end-1] == '\r' { + rowEnd-- + } for foldIndex < len(editor.folds) && editor.folds[foldIndex].LastLine < line { foldIndex++ } @@ -167,7 +171,7 @@ func (editor *CodeEditor) fitWithRepresentations(value string, cols int, wrap bo hidden = fold.Header >= 0 && fold.LastLine > fold.Header && fold.Header < line && line <= fold.LastLine } if !hidden { - editor.appendLine(value, start, end, line) + editor.appendLine(value, start, rowEnd, line) } if end >= len(value) { break diff --git a/components/code_editor_test.go b/components/code_editor_test.go index 6f92db26c..5fc3dbb60 100644 --- a/components/code_editor_test.go +++ b/components/code_editor_test.go @@ -413,6 +413,22 @@ func TestCodeEditorMoveKeepsTheColumnAcrossShortLines(t *testing.T) { } } +func TestCodeEditorCRLFLineEndStopsBeforeThePair(t *testing.T) { + const value = "ab\r\ncd" + for _, wrap := range []bool{false, true} { + fixture := newCodeFixture(value) + fixture.snapshot.Wrap = wrap + fixture.paint() + if got := fixture.editor.Move(value, 1, TextareaMoveLineEnd); got != 2 { + t.Fatalf("wrap=%t: End offset=%d, want before CRLF", wrap, got) + } + point := gfx.Point{X: fixture.editor.content.X + fixture.editor.content.Width, Y: fixture.editor.content.Y + fixture.editor.lineHeight/2} + if got, ok := fixture.editor.OffsetAt(point); !ok || got != 2 { + t.Fatalf("wrap=%t: click past line end offset=%d, ok=%t, want before CRLF", wrap, got, ok) + } + } +} + func TestCodeEditorHomeGoesToTheFirstCharacterFirst(t *testing.T) { value := "x\n ab" f := newCodeFixture(value) diff --git a/components/code_editor_whitespace_test.go b/components/code_editor_whitespace_test.go index f06819429..91d958a4f 100644 --- a/components/code_editor_whitespace_test.go +++ b/components/code_editor_whitespace_test.go @@ -93,6 +93,22 @@ func TestCodeEditorEOLLabelsCanVaryPerLogicalLine(t *testing.T) { } } +func TestCodeEditorCRLFShowsOneHardLineEnding(t *testing.T) { + fixture := newCodeFixture("ab\r\ncd") + fixture.snapshot.ShowEOL = true + fixture.snapshot.EOLLabel = "CRLF" + fixture.paint() + count := 0 + for _, label := range fixture.canvas.Texts() { + if label.Value == "CRLF" { + count++ + } + } + if count != 1 { + t.Fatalf("CRLF marker count=%d, want 1", count) + } +} + func TestCodeEditorWhitespaceMarkersStopAtTheVisibleColumns(t *testing.T) { // One minified line: walking it end to end would be megabytes per paint, // for markers that are all off screen. diff --git a/text/editing.go b/text/editing.go index 8ae9d32f0..528da98f9 100644 --- a/text/editing.go +++ b/text/editing.go @@ -154,14 +154,21 @@ func (editor *Editor) DeleteWord(forward bool) { editor.record(change, before, editor.selectionState(), editSeparate) } -// lineBoundary is the start or end of the logical line the caret is on: the -// nearest newline, or the end of the text. +func (editor *Editor) insideCRLF(at int) bool { + return at > 0 && at < len(editor.runes) && editor.runes[at-1] == '\r' && editor.runes[at] == '\n' +} + +// lineBoundary finds the logical line's start or the first rune of its LF or +// CRLF ending, or the end of the text. func (editor *Editor) lineBoundary(end bool) int { at := editor.caret if end { for at < len(editor.runes) && editor.runes[at] != '\n' { at++ } + if at > 0 && at < len(editor.runes) && editor.runes[at-1] == '\r' { + at-- + } } else { for at > 0 && editor.runes[at-1] != '\n' { at-- @@ -172,7 +179,11 @@ func (editor *Editor) lineBoundary(end bool) int { // MoveLineBoundary implements Home/End for an unwrapped logical line. func (editor *Editor) MoveLineBoundary(end, extend bool) { + anchorInsideCRLF := extend && editor.insideCRLF(editor.anchor) editor.MoveTo(editor.lineBoundary(end), extend) + if anchorInsideCRLF { + editor.anchor-- + } } // DeleteToLineBoundary removes a selection, or the text from the caret to the @@ -190,19 +201,31 @@ func (editor *Editor) DeleteToLineBoundary(end bool) { editor.BreakUndoGroup() return } + before := editor.selectionState() + if editor.insideCRLF(editor.caret) { + // A caret between CR and LF is at the start of that ending for line + // purposes. Normalizing it first keeps the boundary and the deletion on + // one position, so the pair is never split. + editor.collapse(previousBoundary(editor.runes, editor.caret)) + } boundary := editor.lineBoundary(end) - if boundary == editor.caret { - if end { - editor.DeleteForward() - } else { - editor.DeleteBackward() + target := ordered(Range{Start: editor.caret, End: boundary}) + kind := editSeparate + if target.Start == target.End { + // A caret already on the boundary removes the grapheme beyond it, which + // joins the line, as DeleteForward and DeleteBackward do. + if end && editor.caret < len(editor.runes) { + target = Range{Start: editor.caret, End: nextBoundary(editor.runes, editor.caret)} + kind = editDeleteForward + } else if !end && editor.caret > 0 { + target = Range{Start: previousBoundary(editor.runes, editor.caret), End: editor.caret} + kind = editDeleteBackward } - editor.BreakUndoGroup() - return } - before := editor.selectionState() - target := ordered(Range{Start: editor.caret, End: boundary}) - change := editor.replace(target, "", false) - editor.collapse(target.Start) - editor.record(change, before, editor.selectionState(), editSeparate) + if target.Start != target.End { + change := editor.replace(target, "", false) + editor.collapse(target.Start) + editor.record(change, before, editor.selectionState(), kind) + } + editor.BreakUndoGroup() } diff --git a/text/editing_test.go b/text/editing_test.go index 91c66f590..b65f251fe 100644 --- a/text/editing_test.go +++ b/text/editing_test.go @@ -82,6 +82,179 @@ func TestDeleteToLineBoundaryStopsAtNewlinesAndUndoesAsOne(t *testing.T) { } } +func TestLineEndNavigationKeepsCRLFAtomic(t *testing.T) { + for _, separator := range []string{"\n", "\r\n"} { + t.Run(lineEndingName(separator), func(t *testing.T) { + original := "ab" + separator + "cd" + editor := NewEditor(original) + editor.MoveTo(1, false) + editor.MoveLineBoundary(true, false) + if editor.Caret() != 2 { + t.Fatalf("End caret=%d, want before %q", editor.Caret(), separator) + } + editor.Insert("X") + committed := "abX" + separator + "cd" + if editor.String() != committed || !editor.Undo() || editor.String() != original || !editor.Redo() || editor.String() != committed { + t.Fatalf("End insertion history=%q, want %q", editor.String(), committed) + } + + editor = NewEditor(original) + editor.MoveTo(1, false) + editor.MoveLineBoundary(true, true) + if editor.Selection() != (Range{Start: 1, End: 2}) || editor.Caret() != 2 { + t.Fatalf("Shift-End selection=%+v caret=%d", editor.Selection(), editor.Caret()) + } + }) + } +} + +func TestDeleteToLineEndKeepsCRLFAtomic(t *testing.T) { + for _, separator := range []string{"\n", "\r\n"} { + t.Run(lineEndingName(separator), func(t *testing.T) { + original := "ab" + separator + "cd" + editor := NewEditor(original) + editor.MoveTo(1, false) + editor.DeleteToLineBoundary(true) + remaining := "a" + separator + "cd" + if editor.String() != remaining || !editor.Undo() || editor.String() != original || !editor.Redo() || editor.String() != remaining { + t.Fatalf("delete to End history=%q, want %q", editor.String(), remaining) + } + + editor = NewEditor(original) + editor.MoveTo(2, false) + editor.DeleteToLineBoundary(true) + if editor.String() != "abcd" || !editor.Undo() || editor.String() != original || !editor.Redo() || editor.String() != "abcd" { + t.Fatalf("delete at End history=%q, want joined lines", editor.String()) + } + }) + } +} + +func TestLineNavigationFromInsideCRLFDoesNotSelectHalfTheEnding(t *testing.T) { + const original = "ab\r\ncd" + for _, scenario := range []struct { + name string + end bool + extend bool + selection Range + caret int + }{ + {"End", true, false, Range{Start: 2, End: 2}, 2}, + {"Shift-End", true, true, Range{Start: 2, End: 2}, 2}, + {"Home", false, false, Range{}, 0}, + {"Shift-Home", false, true, Range{Start: 0, End: 2}, 0}, + } { + t.Run(scenario.name, func(t *testing.T) { + editor := NewEditor(original) + editor.MoveTo(3, false) + editor.MoveLineBoundary(scenario.end, scenario.extend) + if editor.Selection() != scenario.selection || editor.Caret() != scenario.caret { + t.Fatalf("selection=%+v caret=%d, want %+v caret=%d", editor.Selection(), editor.Caret(), scenario.selection, scenario.caret) + } + }) + } + t.Run("reverse-anchor", func(t *testing.T) { + editor := NewEditor(original) + editor.SetSelection(Range{Start: 3, End: 1}) + editor.MoveLineBoundary(false, true) + if editor.Selection() != (Range{Start: 0, End: 2}) || editor.Caret() != 0 { + t.Fatalf("selection=%+v caret=%d", editor.Selection(), editor.Caret()) + } + }) +} + +func TestDeleteToLineBoundaryFromInsideCRLFPreservesThePair(t *testing.T) { + const original = "ab\r\ncd" + for _, scenario := range []struct { + name string + end bool + want string + caret int + }{ + {"to-end", true, "abcd", 2}, + {"to-start", false, "\r\ncd", 0}, + } { + t.Run(scenario.name, func(t *testing.T) { + editor := NewEditor(original) + editor.MoveTo(3, false) + editor.DeleteToLineBoundary(scenario.end) + if editor.String() != scenario.want || editor.Caret() != scenario.caret { + t.Fatalf("deleted=%q caret=%d, want %q caret=%d", editor.String(), editor.Caret(), scenario.want, scenario.caret) + } + if !editor.Undo() || editor.String() != original || editor.Caret() != 3 { + t.Fatalf("Undo restored %q caret=%d", editor.String(), editor.Caret()) + } + if !editor.Redo() || editor.String() != scenario.want || editor.Caret() != scenario.caret { + t.Fatalf("Redo restored %q caret=%d", editor.String(), editor.Caret()) + } + }) + } +} + +func TestDeleteToLineBoundaryJoinsLinesFromInsideEmptyCRLF(t *testing.T) { + const original = "x\n\r\ncd" // the caret at 3 sits between CR and LF of the empty line + for _, scenario := range []struct { + name string + end bool + want string + }{ + {"to-start", false, "x\r\ncd"}, + {"to-end", true, "x\ncd"}, + } { + t.Run(scenario.name, func(t *testing.T) { + editor := NewEditor(original) + editor.MoveTo(3, false) + editor.DeleteToLineBoundary(scenario.end) + if editor.String() != scenario.want { + t.Fatalf("deleted=%q, want %q", editor.String(), scenario.want) + } + if !editor.Undo() || editor.String() != original { + t.Fatalf("Undo restored %q, want %q", editor.String(), original) + } + }) + } +} + +func lineEndingName(separator string) string { + if separator == "\r\n" { + return "CRLF" + } + return "LF" +} + +func BenchmarkLineEndBoundary(b *testing.B) { + for _, separator := range []string{"\n", "\r\n"} { + b.Run(lineEndingName(separator), func(b *testing.B) { + editor := NewEditor("ab" + separator + "cd") + editor.MoveTo(1, false) + b.ReportAllocs() + position := 0 + for b.Loop() { + position = editor.lineBoundary(true) + } + if position < 0 { + b.Fatal(position) + } + }) + } +} + +func BenchmarkMoveLineBoundary(b *testing.B) { + for _, separator := range []string{"\n", "\r\n"} { + b.Run(lineEndingName(separator), func(b *testing.B) { + editor := NewEditor("ab" + separator + "cd") + b.ReportAllocs() + for b.Loop() { + editor.MoveTo(1, false) + editor.MoveLineBoundary(true, false) + } + if editor.Caret() < 0 { + b.Fatal(editor.Caret()) + } + }) + } +} + // Typing into a single-line field folds every insert, so a clean rune must not // allocate; only text that actually has something to fold may. func TestSingleLineTypingDoesNotAllocate(t *testing.T) { From 7fce686ee827a1394576cb12bc53c7e43feb6006 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:40:03 +0800 Subject: [PATCH 03/23] fix(darwin): keep suggested save extensions intact --- internal/platform/darwin/save_panel_darwin.h | 9 +++++ internal/platform/darwin/save_panel_darwin.m | 18 +++++++++ .../platform/darwin/save_panel_darwin_test.go | 26 +++++++++++++ internal/platform/darwin/system_darwin.m | 13 +------ .../platform/darwin/testdata/save_panel.m | 37 +++++++++++++++++++ 5 files changed, 92 insertions(+), 11 deletions(-) create mode 100644 internal/platform/darwin/save_panel_darwin.h create mode 100644 internal/platform/darwin/save_panel_darwin.m create mode 100644 internal/platform/darwin/save_panel_darwin_test.go create mode 100644 internal/platform/darwin/testdata/save_panel.m diff --git a/internal/platform/darwin/save_panel_darwin.h b/internal/platform/darwin/save_panel_darwin.h new file mode 100644 index 000000000..dad39ea63 --- /dev/null +++ b/internal/platform/darwin/save_panel_darwin.h @@ -0,0 +1,9 @@ +#ifndef VIVA_SAVE_PANEL_DARWIN_H +#define VIVA_SAVE_PANEL_DARWIN_H + +#import + +/* Sets the allowed types, then the suggested name, on a save panel. Main thread only. */ +void viva_configure_save_panel(NSSavePanel *panel, NSString *name, NSArray *allowed); + +#endif diff --git a/internal/platform/darwin/save_panel_darwin.m b/internal/platform/darwin/save_panel_darwin.m new file mode 100644 index 000000000..5f8ba990c --- /dev/null +++ b/internal/platform/darwin/save_panel_darwin.m @@ -0,0 +1,18 @@ +#import "save_panel_darwin.h" + +void viva_configure_save_panel(NSSavePanel *panel, NSString *name, NSArray *allowed) { + if (allowed.count > 0) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + panel.allowedFileTypes = allowed; +#pragma clang diagnostic pop + // With other types disallowed, AppKit rewrites a name whose extension is not + // in allowed (export.log -> export.log.txt). Keep such a name intact, as Linux + // and Windows do; an extensionless name still takes the first allowed type. + panel.allowsOtherFileTypes = name.pathExtension.length > 0; + panel.extensionHidden = NO; + } + if (name.length > 0) { + panel.nameFieldStringValue = name; + } +} diff --git a/internal/platform/darwin/save_panel_darwin_test.go b/internal/platform/darwin/save_panel_darwin_test.go new file mode 100644 index 000000000..11822623f --- /dev/null +++ b/internal/platform/darwin/save_panel_darwin_test.go @@ -0,0 +1,26 @@ +//go:build darwin + +package darwin + +import ( + "context" + "os/exec" + "path/filepath" + "testing" + "time" +) + +func TestNativeSavePanelDoesNotDuplicateSuggestedExtension(t *testing.T) { + testContext, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + executable := filepath.Join(t.TempDir(), "save-panel") + command := exec.CommandContext(testContext, "xcrun", "clang", "-fno-objc-arc", "-Werror", + "-Wno-deprecated-declarations", "testdata/save_panel.m", "-o", executable, + "-framework", "Cocoa") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native save panel test: %v\n%s", err, output) + } + if output, err := exec.CommandContext(testContext, executable, t.TempDir()).CombinedOutput(); err != nil { + t.Fatalf("native save panel suggested name: %v\n%s", err, output) + } +} diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m index 4addd74dd..bd15c259b 100644 --- a/internal/platform/darwin/system_darwin.m +++ b/internal/platform/darwin/system_darwin.m @@ -7,6 +7,7 @@ #include "system_darwin.h" #include "cursor_owner_darwin.h" +#include "save_panel_darwin.h" static const size_t viva_max_clipboard_bytes = 64u << 20; @@ -873,17 +874,7 @@ static int viva_system_save_file_internal( if (panelTitle.length > 0) { panel.title = panelTitle; } - if (name.length > 0) { - panel.nameFieldStringValue = name; - } - if (allowed.count > 0) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - panel.allowedFileTypes = allowed; -#pragma clang diagnostic pop - panel.allowsOtherFileTypes = NO; - panel.extensionHidden = NO; - } + viva_configure_save_panel(panel, name, allowed); NSModalResponse response = viva_run_panel(panel); if (response == NSModalResponseCancel) { status = 1; diff --git a/internal/platform/darwin/testdata/save_panel.m b/internal/platform/darwin/testdata/save_panel.m new file mode 100644 index 000000000..a3238225d --- /dev/null +++ b/internal/platform/darwin/testdata/save_panel.m @@ -0,0 +1,37 @@ +#import "../save_panel_darwin.m" +#include +#include + +int main(int argc, const char *argv[]) { + if (argc != 2) { + return 2; + } + @autoreleasepool { + [NSApplication sharedApplication].activationPolicy = NSApplicationActivationPolicyAccessory; + NSURL *directory = [NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[1]] isDirectory:YES]; + NSArray *names = @[@"draft.go", @"note.mh", @"draft", @"note.mh", @"aa.bb.go", @"export.log"]; + NSArray *> *types = @[@[@"go"], @[@"mh"], @[@"go"], @[@"go", @"mh"], @[@"go"], @[@"txt"]]; + NSArray *expected = @[@"draft.go", @"note.mh", @"draft.go", @"note.mh", @"aa.bb.go", @"export.log"]; + for (NSUInteger index = 0; index < names.count; index++) { + NSSavePanel *panel = [NSSavePanel savePanel]; + panel.directoryURL = directory; + viva_configure_save_panel(panel, names[index], types[index]); + [panel orderFront:nil]; + NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:2.0]; + while ((panel.URL == nil || [panel.URL.lastPathComponent isEqualToString:@"Untitled"]) && + deadline.timeIntervalSinceNow > 0) { + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode + beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.02]]; + } + NSString *filename = panel.URL.lastPathComponent; + if (![filename isEqualToString:expected[index]]) { + fprintf(stderr, "%s: panel URL is %s, want %s\n", names[index].UTF8String, + filename.UTF8String, expected[index].UTF8String); + [panel orderOut:nil]; + return 1; + } + [panel orderOut:nil]; + } + } + return 0; +} From e8f7a235c5b2b6af27bdc5ad1bbccde389f9195d Mon Sep 17 00:00:00 2001 From: ezreal <71426102+Ezreal-byte@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:40:08 +0800 Subject: [PATCH 04/23] feat(components): add composable avatar crop editor --- cmd/viva/components_gen.go | 2 + cmd/viva/templates/avatar_editor.go.txt | 693 +++++++++++++++++++++++ components/avatar_editor.go | 681 ++++++++++++++++++++++ components/avatar_editor_driver_test.go | 117 ++++ components/avatar_editor_test.go | 355 ++++++++++++ components/doc.go | 9 + internal/componentdemo/avatar_editor.go | 120 ++++ internal/componentdemo/catalog_a.go | 1 + internal/componentdemo/catalog_a_test.go | 2 +- internal/componentdemo/state.go | 21 +- 10 files changed, 1990 insertions(+), 11 deletions(-) create mode 100644 cmd/viva/templates/avatar_editor.go.txt create mode 100644 components/avatar_editor.go create mode 100644 components/avatar_editor_driver_test.go create mode 100644 components/avatar_editor_test.go create mode 100644 internal/componentdemo/avatar_editor.go diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go index 8c9ca0710..f5d229f51 100644 --- a/cmd/viva/components_gen.go +++ b/cmd/viva/components_gen.go @@ -10,6 +10,7 @@ var componentFiles = map[string]string{ "aspect-ratio": "aspect_ratio.go.txt", "attachment": "attachment.go.txt", "avatar": "avatar.go.txt", + "avatar-editor": "avatar_editor.go.txt", "badge": "badge.go.txt", "breadcrumb": "breadcrumb.go.txt", "bubble": "bubble.go.txt", @@ -107,6 +108,7 @@ var componentRequires = map[string][]string{ "accordion": {"button", "tree"}, "alert-dialog": {"button", "dialog"}, "attachment": {"bubble", "button"}, + "avatar-editor": {"button", "direction", "slider"}, "badge": {"button"}, "breadcrumb": {"tree"}, "bubble": {"button"}, diff --git a/cmd/viva/templates/avatar_editor.go.txt b/cmd/viva/templates/avatar_editor.go.txt new file mode 100644 index 000000000..345c673dc --- /dev/null +++ b/cmd/viva/templates/avatar_editor.go.txt @@ -0,0 +1,693 @@ +package {{PACKAGE}} + +import ( + "math" + "sync" + + "github.com/vivaui/viva/gfx" +) + +// AvatarEditorIDs are caller-owned, stable identities. A zero ID omits that +// control. Canvas enables dragging, wheel zoom and keyboard editing; Reset +// adds a reset button when there is room. +type AvatarEditorIDs struct { + Canvas, Zoom, ZoomOut, ZoomIn, Reset gfx.ID +} + +// AvatarEditorLabels localizes the accessible names and empty states. Empty +// fields use English defaults. +type AvatarEditorLabels struct { + Hint, Canvas, Zoom, ZoomOut, ZoomIn, Reset string + Loading, Unavailable string +} + +// AvatarEditorState is caller-owned and survives paints. Zoom 1 fits the +// largest crop of the requested aspect ratio inside the source. CenterX and +// CenterY are normalized source coordinates. Use the zero value for a new +// image or to reset to the largest centered crop allowed by the options. +type AvatarEditorState struct { + Zoom, CenterX, CenterY float32 + gesture avatarEditorGesture + dragX, dragY float32 +} + +type avatarEditorGesture uint8 + +const ( + avatarEditorGestureNone avatarEditorGesture = iota + avatarEditorGestureCanvas + avatarEditorGestureZoom +) + +// AvatarEditorOptions is a snapshot for one paint. The bitmap remains owned +// by the caller; its dimensions define the coordinate space for Crop. See +// gfx.Bitmap for pixel format and cache identity. +type AvatarEditorOptions struct { + IDs AvatarEditorIDs + Labels AvatarEditorLabels + Bitmap gfx.Bitmap + State AvatarEditorState + + // AspectRatio is width / height, defaulting to 1. + AspectRatio float32 + // MinZoom defaults to 1 and cannot go below it. MaxZoom defaults to 8 + // (or MinZoom, if larger). Set both equal for a fixed zoom. + MinZoom, MaxZoom float32 + // MaxStageSize caps the preview's longest edge, defaulting to 320 + // logical pixels. The preview also fits inside the supplied bounds. + MaxStageSize float32 + // Circular masks a square preview; Crop is still a rectangle. Backdrop + // must match the containing surface's solid, opaque color and defaults + // to theme.Background. + Circular bool + Backdrop gfx.Color + // Loading or Error disables editing, even if Bitmap is still present. + // Error takes precedence when both are set. + Loading bool + Error string +} + +// AvatarEditorLayout describes the current frame and routes its input. Keep +// it until the next paint. When Ready, Crop is the selected rectangle in +// bitmap pixels and Stage is the preview in logical window coordinates. +type AvatarEditorLayout struct { + Stage, Crop gfx.Rect + Ready bool + State AvatarEditorState + + ids AvatarEditorIDs + zoomBounds gfx.Rect + geometry avatarCropGeometry +} + +// AvatarEditor paints a crop surface. Loading an image, choosing a container +// and applying or exporting the crop are the caller's responsibility. +type AvatarEditor struct { + canvas *gfx.Canvas + theme gfx.Theme + bounds gfx.Rect + options AvatarEditorOptions +} + +// BeginAvatarEditor prepares a crop surface for the caller-provided bounds. +func BeginAvatarEditor(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, options AvatarEditorOptions) AvatarEditor { + return AvatarEditor{canvas: canvas, theme: theme, bounds: bounds, options: options} +} + +// Paint draws the preview and the controls that fit. Save the returned State +// so zoom and reset button clicks persist, and save the layout to route input. +func (editor AvatarEditor) Paint() AvatarEditorLayout { + c, theme, bounds, o := editor.canvas, editor.theme, editor.bounds, editor.options + out := AvatarEditorLayout{State: o.State, ids: o.IDs} + if c == nil || !finiteAvatarValue(bounds.Width) || !finiteAvatarValue(bounds.Height) || + bounds.Width <= 0 || bounds.Height <= 0 { + return out + } + labels := normalizedAvatarEditorLabels(o.Labels) + aspect, minZoom, maxZoom := avatarEditorLimits(o) + stageMax := o.MaxStageSize + if !finiteAvatarValue(stageMax) || stageMax <= 0 { + stageMax = 320 + } + + c.Clip(bounds) + defer c.Unclip() + row := avatarEditorControls(c, theme, bounds, o.IDs, labels.Reset) + availableHeight := bounds.Height + if row.height > 0 { + availableHeight -= row.height + avatarEditorRowGap + } + width, height := min(bounds.Width, stageMax), min(availableHeight, stageMax) + if aspect >= 1 { + width = min(width, height*aspect) + height = width / aspect + } else { + height = min(height, width/aspect) + width = height * aspect + } + stage := gfx.Rect{X: bounds.X + (bounds.Width-width)/2, Y: bounds.Y, Width: width, Height: height} + out.Stage = stage + if width <= 0 || height <= 0 { + return out + } + controls := row.at(bounds.X+(bounds.Width-row.width)/2, stage.Y+stage.Height+avatarEditorRowGap) + out.zoomBounds = controls[1] + + ready := !o.Loading && o.Error == "" && avatarBitmapReady(o.Bitmap) + if ready { + out.geometry = newAvatarCropGeometry(o.Bitmap, aspect, minZoom, maxZoom) + } + state := o.State + if ready { + state = out.geometry.normalize(state) + // Apply button clicks before drawing so Crop and the preview agree. + switch { + case controls[0].Width > 0 && c.Clicked(o.IDs.ZoomOut): + state = out.geometry.zoom(state, state.Zoom/1.2, .5, .5) + case controls[2].Width > 0 && c.Clicked(o.IDs.ZoomIn): + state = out.geometry.zoom(state, state.Zoom*1.2, .5, .5) + case controls[3].Width > 0 && c.Clicked(o.IDs.Reset): + state = out.geometry.normalize(AvatarEditorState{}) + } + out.Crop = out.geometry.crop(state) + ready = out.Crop.X+out.Crop.Width > out.Crop.X && out.Crop.Y+out.Crop.Height > out.Crop.Y + if !ready { + out.Crop = gfx.Rect{} + } + } else { + state.gesture = avatarEditorGestureNone + } + out.State, out.Ready = state, ready + + avatarEditorPaintStage(c, theme, stage, out, o, labels, o.Circular && aspect == 1) + if controls[0].Width > 0 { + avatarEditorZoomButton(c, theme, controls[0], o.IDs.ZoomOut, avatarEditorZoomOutIcon, labels.ZoomOut, !ready || state.Zoom <= minZoom) + } + if controls[1].Width > 0 { + avatarEditorPaintZoom(c, theme, o.IDs.Zoom, controls[1], state.Zoom, minZoom, maxZoom, ready, labels.Zoom) + } + if controls[2].Width > 0 { + avatarEditorZoomButton(c, theme, controls[2], o.IDs.ZoomIn, avatarEditorZoomInIcon, labels.ZoomIn, !ready || state.Zoom >= maxZoom) + } + if controls[3].Width > 0 { + reset := BeginButton(c, theme, o.IDs.Reset, controls[3]).Small() + if !ready { + reset = reset.Disabled() + } + reset.Outline(labels.Reset) + } + return out +} + +const avatarEditorRowGap = 12 + +type avatarEditorControlRow struct { + widths [4]float32 + width, gap, height float32 +} + +func avatarEditorControls(c *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, ids AvatarEditorIDs, resetLabel string) avatarEditorControlRow { + height := max(float32(32), theme.Metrics.ControlHeight) + if bounds.Height <= height+avatarEditorRowGap { + return avatarEditorControlRow{} + } + row := avatarEditorControlRow{height: height, gap: max(float32(10), theme.Metrics.GapItem)} + if !ids.ZoomOut.IsZero() { + row.widths[0] = height + } + if !ids.Zoom.IsZero() { + row.widths[1] = 24 + } + if !ids.ZoomIn.IsZero() { + row.widths[2] = height + } + if !ids.Reset.IsZero() { + row.widths[3] = max(float32(56), c.TextWidthWeight(resetLabel, theme.Metrics.FontSizeS, gfx.WeightMedium)+24) + } + row.width = avatarEditorRowWidth(row.widths, row.gap) + if row.width > bounds.Width { + row.widths[3] = 0 // Give the zoom controls priority over reset. + row.width = avatarEditorRowWidth(row.widths, row.gap) + } + if row.width > bounds.Width && row.widths[1] > 0 { + row.widths[0], row.widths[2] = 0, 0 + row.width = row.widths[1] + } + if row.width <= 0 || row.width > bounds.Width { + return avatarEditorControlRow{} + } + if row.widths[1] > 0 { + extra := max(0, bounds.Width-24-row.width) + row.widths[1] += extra + row.width += extra + } + return row +} + +func avatarEditorRowWidth(widths [4]float32, gap float32) float32 { + var width float32 + for _, w := range widths { + if w > 0 { + if width > 0 { + width += gap + } + width += w + } + } + return width +} + +func (row avatarEditorControlRow) at(x, y float32) (controls [4]gfx.Rect) { + for i, width := range row.widths { + if width > 0 { + controls[i] = gfx.Rect{X: x, Y: y, Width: width, Height: row.height} + x += width + row.gap + } + } + return controls +} + +func avatarEditorPaintStage(c *gfx.Canvas, theme gfx.Theme, stage gfx.Rect, out AvatarEditorLayout, o AvatarEditorOptions, labels AvatarEditorLabels, circular bool) { + c.Clip(stage) + if circular { + c.DrawPath(avatarEditorCircleFillPath(), stage, gfx.PathStyle{Fill: theme.Muted}) + } else { + c.Fill(stage, theme.Muted) + } + if out.Ready { + // Sample the source directly in one draw, including when magnified. + c.DrawBitmapRegion(o.Bitmap, out.Crop, stage) + if circular { + backdrop := o.Backdrop + if backdrop.Alpha == 0 { + backdrop = theme.Background + } + c.DrawPath(avatarEditorCircleMaskPath(), stage, gfx.PathStyle{Fill: backdrop, FillRule: gfx.PathFillEvenOdd}) + } else { + avatarEditorPaintGuides(c, theme, stage) + } + } else { + message, color := labels.Unavailable, theme.Danger + if o.Error != "" { + message = o.Error + } else if o.Loading { + message, color = labels.Loading, theme.MutedForeground + } + c.LabelCenter(message, stage, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}) + } + id := o.IDs.Canvas + border := theme.Border + if !id.IsZero() && (c.Pressed() == id || c.FocusVisible() == id || out.State.gesture == avatarEditorGestureCanvas) { + border = theme.Ring + } + if circular { + c.DrawPath(avatarEditorCircleRingPath(), stage, gfx.PathStyle{Fill: border, FillRule: gfx.PathFillEvenOdd}) + } else { + c.RoundedBorder(stage, 0, 1.5, border, gfx.Color{}) + } + c.Unclip() + if !id.IsZero() { + cursor := gfx.PointerCursorHand + if out.State.gesture == avatarEditorGestureCanvas { + cursor = gfx.PointerCursorGrabbing + } + c.HitWithOptions(id, stage, labels.Canvas, gfx.HitOptions{ + Role: gfx.RoleGroup, Cursor: cursor, Hint: labels.Hint, Disabled: !out.Ready, + }) + } +} + +func avatarEditorZoomButton(c *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, id gfx.ID, icon gfx.Icon, label string, disabled bool) { + button := BeginButton(c, theme, id, bounds).IconSmall().WithIcon(icon) + if disabled { + button = button.Disabled() + } + button.Ghost(label) +} + +// Pointer handles primary-button drags of the preview or zoom slider. +func (layout AvatarEditorLayout) Pointer(event gfx.PointerEvent, state AvatarEditorState) (AvatarEditorState, gfx.EventResult) { + if !layout.Ready || event.Button != gfx.PointerButtonPrimary && event.Button != gfx.PointerButtonNone { + return state, gfx.EventResult{} + } + if event.Kind == gfx.PointerExit && !event.Captured && state.gesture != avatarEditorGestureNone { + state.gesture = avatarEditorGestureNone + return state, gfx.EventResult{Repaint: true} + } + canvas := !layout.ids.Canvas.IsZero() && event.Target == layout.ids.Canvas + slider := layout.zoomEnabled() && event.Target == layout.ids.Zoom + if !canvas && !slider { + return state, gfx.EventResult{} + } + switch event.Kind { + case gfx.PointerDown: + state = layout.geometry.normalize(state) + if slider { + state.gesture = avatarEditorGestureZoom + state = layout.zoomAtX(state, event.X) + } else { + state.gesture = avatarEditorGestureCanvas + state.dragX, state.dragY = event.X, event.Y + } + case gfx.PointerMove: + if !event.Captured { + return state, gfx.EventResult{} + } + switch { + case canvas && state.gesture == avatarEditorGestureCanvas: + state = layout.pan(state, state.dragX-event.X, state.dragY-event.Y) + state.dragX, state.dragY = event.X, event.Y + case slider && state.gesture == avatarEditorGestureZoom: + state = layout.zoomAtX(state, event.X) + default: + return state, gfx.EventResult{} + } + case gfx.PointerUp: + if !(canvas && state.gesture == avatarEditorGestureCanvas || slider && state.gesture == avatarEditorGestureZoom) { + return state, gfx.EventResult{} + } + state.gesture = avatarEditorGestureNone + default: + return state, gfx.EventResult{} + } + return state, gfx.EventResult{Handled: true, Repaint: true} +} + +// Scroll zooms around the pointer. At a zoom limit, a scroll that would go +// farther is left for the containing page to handle. +func (layout AvatarEditorLayout) Scroll(event gfx.ScrollEvent, state AvatarEditorState) (AvatarEditorState, gfx.EventResult) { + if !layout.Ready || layout.ids.Canvas.IsZero() || event.Target != layout.ids.Canvas || event.DeltaY == 0 { + return state, gfx.EventResult{} + } + view := layout.geometry.normalize(state) + delta := min(float32(8), max(float32(-8), event.StepY(1))) + target := view.Zoom * float32(math.Pow(1.15, -float64(delta))) + stage := layout.Stage + focusX := min(1, max(0, (event.X-stage.X)/stage.Width)) + focusY := min(1, max(0, (event.Y-stage.Y)/stage.Height)) + next := layout.geometry.zoom(view, target, focusX, focusY) + if next.Zoom == view.Zoom { + return state, gfx.EventResult{} + } + return next, gfx.EventResult{Handled: true, Repaint: true} +} + +// Key handles unmodified editing keys (and Shift for larger moves). Canvas +// arrows pan, +/- and Page Up/Down zoom, and Home resets the view. The zoom +// slider follows standard slider keys. Enter and app shortcuts pass through. +func (layout AvatarEditorLayout) Key(event gfx.KeyEvent, state AvatarEditorState) (AvatarEditorState, gfx.EventResult) { + if !layout.Ready || event.Release || event.Modifiers&(gfx.ModifierControl|gfx.ModifierMeta|gfx.ModifierAlt) != 0 || + event.Target.IsZero() { + return state, gfx.EventResult{} + } + view := layout.geometry.normalize(state) + result := gfx.EventResult{Handled: true, Repaint: true} + if event.Target == layout.ids.Zoom && layout.zoomEnabled() { + g := layout.geometry + value, handled := SliderKeyDownLarge(view.Zoom, g.minZoom, g.maxZoom, avatarEditorZoomStep, 1, LTR, event.Key, event.Modifiers) + if !handled { + return state, gfx.EventResult{} + } + // Home and End select the exact endpoints, including custom bounds that + // aren't an integer number of steps apart. + if event.Key == gfx.KeyEnd { + value = g.maxZoom + } + return g.zoom(view, value, .5, .5), result + } + if event.Target != layout.ids.Canvas { + return state, gfx.EventResult{} + } + step := float32(8) + if event.Modifiers&gfx.ModifierShift != 0 { + step = 24 + } + switch event.Key { + case gfx.KeyLeft: + view = layout.pan(view, -step, 0) + case gfx.KeyRight: + view = layout.pan(view, step, 0) + case gfx.KeyUp: + view = layout.pan(view, 0, -step) + case gfx.KeyDown: + view = layout.pan(view, 0, step) + case gfx.KeyPageUp: + view = layout.geometry.zoom(view, view.Zoom*1.15, .5, .5) + case gfx.KeyPageDown: + view = layout.geometry.zoom(view, view.Zoom/1.15, .5, .5) + case gfx.KeyHome: + view = layout.geometry.normalize(AvatarEditorState{}) + default: + switch event.Text { + case "+", "=": + view = layout.geometry.zoom(view, view.Zoom*1.15, .5, .5) + case "-": + view = layout.geometry.zoom(view, view.Zoom/1.15, .5, .5) + default: + return state, gfx.EventResult{} + } + } + return view, result +} + +func normalizedAvatarEditorLabels(labels AvatarEditorLabels) AvatarEditorLabels { + if labels.Hint == "" { + labels.Hint = "Drag to reposition. Scroll, use the slider, or use the zoom buttons." + } + if labels.Canvas == "" { + labels.Canvas = "Image crop" + } + if labels.Zoom == "" { + labels.Zoom = "Zoom" + } + if labels.ZoomOut == "" { + labels.ZoomOut = "Zoom out" + } + if labels.ZoomIn == "" { + labels.ZoomIn = "Zoom in" + } + if labels.Reset == "" { + labels.Reset = "Reset" + } + if labels.Loading == "" { + labels.Loading = "Loading image…" + } + if labels.Unavailable == "" { + labels.Unavailable = "This image could not be displayed." + } + return labels +} + +func finiteAvatarValue(value float32) bool { + return value >= -math.MaxFloat32 && value <= math.MaxFloat32 +} + +func avatarEditorLimits(o AvatarEditorOptions) (aspect, minZoom, maxZoom float32) { + aspect = o.AspectRatio + if !finiteAvatarValue(aspect) || aspect <= 0 { + aspect = 1 + } + minZoom = o.MinZoom + if !finiteAvatarValue(minZoom) || minZoom < 1 { + minZoom = 1 + } + maxZoom = o.MaxZoom + if !finiteAvatarValue(maxZoom) || maxZoom < minZoom { + maxZoom = max(8, minZoom) + } + return aspect, minZoom, maxZoom +} + +func avatarBitmapReady(bitmap gfx.Bitmap) bool { + if bitmap.Width <= 0 || bitmap.Height <= 0 || bitmap.Width > len(bitmap.Pix)/4 || bitmap.Stride < bitmap.Width*4 { + return false + } + return (len(bitmap.Pix)-bitmap.Width*4)/bitmap.Stride >= bitmap.Height-1 +} + +type avatarCropGeometry struct { + image, base gfx.Size + minZoom, maxZoom float32 +} + +func newAvatarCropGeometry(bitmap gfx.Bitmap, aspect, minZoom, maxZoom float32) avatarCropGeometry { + image := gfx.Size{Width: float32(bitmap.Width), Height: float32(bitmap.Height)} + base := image + if image.Width/image.Height > aspect { + base.Width = image.Height * aspect + } else { + base.Height = image.Width / aspect + } + return avatarCropGeometry{image: image, base: base, minZoom: minZoom, maxZoom: maxZoom} +} + +func (g avatarCropGeometry) normalize(state AvatarEditorState) AvatarEditorState { + if !finiteAvatarValue(state.Zoom) || state.Zoom <= 0 { + state.Zoom, state.CenterX, state.CenterY = 1, .5, .5 + } + state.Zoom = min(g.maxZoom, max(g.minZoom, state.Zoom)) + if !finiteAvatarValue(state.CenterX) { + state.CenterX = .5 + } + if !finiteAvatarValue(state.CenterY) { + state.CenterY = .5 + } + width, height := g.base.Width/state.Zoom, g.base.Height/state.Zoom + halfWidth, halfHeight := width/g.image.Width/2, height/g.image.Height/2 + state.CenterX = min(1-halfWidth, max(halfWidth, state.CenterX)) + state.CenterY = min(1-halfHeight, max(halfHeight, state.CenterY)) + return state +} + +func (g avatarCropGeometry) crop(state AvatarEditorState) gfx.Rect { + width, height := g.base.Width/state.Zoom, g.base.Height/state.Zoom + return gfx.Rect{ + X: min(g.image.Width-width, max(0, state.CenterX*g.image.Width-width/2)), + Y: min(g.image.Height-height, max(0, state.CenterY*g.image.Height-height/2)), + Width: width, Height: height, + } +} + +func (g avatarCropGeometry) zoom(state AvatarEditorState, target, focusX, focusY float32) AvatarEditorState { + if math.IsNaN(float64(target)) { + return state + } + target = min(g.maxZoom, max(g.minZoom, target)) + if state.Zoom == target { + return state + } + before := g.crop(state) + state.Zoom = target + state.CenterX = (before.X + focusX*before.Width + (.5-focusX)*g.base.Width/target) / g.image.Width + state.CenterY = (before.Y + focusY*before.Height + (.5-focusY)*g.base.Height/target) / g.image.Height + return g.normalize(state) +} + +func (layout AvatarEditorLayout) pan(state AvatarEditorState, dx, dy float32) AvatarEditorState { + g := layout.geometry + state = g.normalize(state) + // Use the latest draft zoom even if the caller has not painted again yet. + state.CenterX += dx * (g.base.Width / state.Zoom / g.image.Width) / layout.Stage.Width + state.CenterY += dy * (g.base.Height / state.Zoom / g.image.Height) / layout.Stage.Height + return g.normalize(state) +} + +func (layout AvatarEditorLayout) zoomEnabled() bool { + return layout.zoomBounds.Width > 0 && layout.geometry.maxZoom > layout.geometry.minZoom +} + +const ( + avatarEditorZoomThumb = 14 + avatarEditorZoomStep = .1 +) + +func (layout AvatarEditorLayout) zoomAtX(state AvatarEditorState, x float32) AvatarEditorState { + track := layout.zoomBounds + fraction := min(1, max(0, (x-track.X-avatarEditorZoomThumb/2)/(track.Width-avatarEditorZoomThumb))) + g := layout.geometry + return g.zoom(g.normalize(state), g.minZoom+fraction*(g.maxZoom-g.minZoom), .5, .5) +} + +func avatarEditorPaintGuides(c *gfx.Canvas, theme gfx.Theme, stage gfx.Rect) { + color := theme.Foreground + color.Alpha = .22 + for _, fraction := range [...]float32{1.0 / 3, 2.0 / 3} { + c.Fill(gfx.Rect{X: stage.X + stage.Width*fraction, Y: stage.Y, Width: 1, Height: stage.Height}, color) + c.Fill(gfx.Rect{X: stage.X, Y: stage.Y + stage.Height*fraction, Width: stage.Width, Height: 1}, color) + } +} + +func avatarEditorPaintZoom(c *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect, zoom, minZoom, maxZoom float32, ready bool, label string) { + centerY := bounds.Y + bounds.Height/2 + track := gfx.Rect{X: bounds.X + avatarEditorZoomThumb/2, Y: centerY - 2, Width: bounds.Width - avatarEditorZoomThumb, Height: 4} + c.Rounded(track, 2, theme.Muted) + fraction := float32(0) + if ready && maxZoom > minZoom { + fraction = min(1, max(0, (zoom-minZoom)/(maxZoom-minZoom))) + c.Rounded(gfx.Rect{X: track.X, Y: track.Y, Width: track.Width * fraction, Height: track.Height}, 2, theme.Primary) + } + if ready { + thumbX := track.X + track.Width*fraction + thumb := gfx.Rect{X: thumbX - avatarEditorZoomThumb/2, Y: centerY - avatarEditorZoomThumb/2, Width: avatarEditorZoomThumb, Height: avatarEditorZoomThumb} + if c.FocusVisible() == id { + c.Rounded(expand(thumb, 3), avatarEditorZoomThumb/2+3, theme.Ring) + } + c.Rounded(thumb, avatarEditorZoomThumb/2, theme.Background) + c.RoundedBorder(thumb, avatarEditorZoomThumb/2, 1.5, theme.Primary, gfx.Color{}) + } else { + zoom = minZoom + } + c.HitWithOptions(id, bounds, label, gfx.HitOptions{ + Role: gfx.RoleSlider, + Range: gfx.ValueRange{Min: float64(minZoom), Max: float64(maxZoom), Now: float64(zoom), Step: avatarEditorZoomStep, Set: true}, + Disabled: !ready || maxZoom == minZoom, Cursor: gfx.PointerCursorHand, + }) +} + +var ( + avatarEditorCirclePathsOnce sync.Once + avatarEditorCircleMask gfx.Path + avatarEditorCircleFill gfx.Path + avatarEditorCircleRing gfx.Path +) + +func avatarEditorCircleMaskPath() gfx.Path { + avatarEditorCirclePathsOnce.Do(initAvatarEditorCirclePaths) + return avatarEditorCircleMask +} + +func avatarEditorCircleRingPath() gfx.Path { + avatarEditorCirclePathsOnce.Do(initAvatarEditorCirclePaths) + return avatarEditorCircleRing +} + +func avatarEditorCircleFillPath() gfx.Path { + avatarEditorCirclePathsOnce.Do(initAvatarEditorCirclePaths) + return avatarEditorCircleFill +} + +func initAvatarEditorCirclePaths() { + avatarEditorCircleMask = gfx.NewPath(100, 100, + // Keep the square edge away from the circle's four tangent points. + // Otherwise even-odd tessellation leaves a seam across the bottom of + // the stage where the circle contour touches the outer contour. + gfx.MoveTo(-2, -2), gfx.LineTo(102, -2), gfx.LineTo(102, 102), gfx.LineTo(-2, 102), gfx.ClosePath(), + gfx.MoveTo(50, 0), + gfx.CubicTo(77.614, 0, 100, 22.386, 100, 50), + gfx.CubicTo(100, 77.614, 77.614, 100, 50, 100), + gfx.CubicTo(22.386, 100, 0, 77.614, 0, 50), + gfx.CubicTo(0, 22.386, 22.386, 0, 50, 0), + gfx.ClosePath(), + ) + avatarEditorCircleFill = gfx.NewPath(100, 100, + gfx.MoveTo(50, 0), + gfx.CubicTo(77.614, 0, 100, 22.386, 100, 50), + gfx.CubicTo(100, 77.614, 77.614, 100, 50, 100), + gfx.CubicTo(22.386, 100, 0, 77.614, 0, 50), + gfx.CubicTo(0, 22.386, 22.386, 0, 50, 0), + gfx.ClosePath(), + ) + avatarEditorCircleRing = gfx.NewPath(100, 100, + gfx.MoveTo(50, 0), + gfx.CubicTo(77.614, 0, 100, 22.386, 100, 50), + gfx.CubicTo(100, 77.614, 77.614, 100, 50, 100), + gfx.CubicTo(22.386, 100, 0, 77.614, 0, 50), + gfx.CubicTo(0, 22.386, 22.386, 0, 50, 0), + gfx.ClosePath(), + gfx.MoveTo(50, .4), + gfx.CubicTo(77.393, .4, 99.6, 22.607, 99.6, 50), + gfx.CubicTo(99.6, 77.393, 77.393, 99.6, 50, 99.6), + gfx.CubicTo(22.607, 99.6, .4, 77.393, .4, 50), + gfx.CubicTo(.4, 22.607, 22.607, .4, 50, .4), + gfx.ClosePath(), + ) +} + +var avatarEditorZoomOutIcon = gfx.Icon{ + ViewBox: 24, Stroke: 1.8, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{ + gfx.MoveTo(10.5, 4), + gfx.CubicTo(14.09, 4, 17, 6.91, 17, 10.5), + gfx.CubicTo(17, 14.09, 14.09, 17, 10.5, 17), + gfx.CubicTo(6.91, 17, 4, 14.09, 4, 10.5), + gfx.CubicTo(4, 6.91, 6.91, 4, 10.5, 4), + gfx.ClosePath(), + gfx.MoveTo(15.2, 15.2), gfx.LineTo(20, 20), + gfx.MoveTo(7.2, 10.5), gfx.LineTo(13.8, 10.5), + }, +} + +var avatarEditorZoomInIcon = gfx.Icon{ + ViewBox: 24, Stroke: 1.8, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{ + gfx.MoveTo(10.5, 4), + gfx.CubicTo(14.09, 4, 17, 6.91, 17, 10.5), + gfx.CubicTo(17, 14.09, 14.09, 17, 10.5, 17), + gfx.CubicTo(6.91, 17, 4, 14.09, 4, 10.5), + gfx.CubicTo(4, 6.91, 6.91, 4, 10.5, 4), + gfx.ClosePath(), + gfx.MoveTo(15.2, 15.2), gfx.LineTo(20, 20), + gfx.MoveTo(7.2, 10.5), gfx.LineTo(13.8, 10.5), + gfx.MoveTo(10.5, 7.2), gfx.LineTo(10.5, 13.8), + }, +} diff --git a/components/avatar_editor.go b/components/avatar_editor.go new file mode 100644 index 000000000..2c37f0bb4 --- /dev/null +++ b/components/avatar_editor.go @@ -0,0 +1,681 @@ +package components + +import ( + "math" + "sync" + + "github.com/vivaui/viva/gfx" +) + +// AvatarEditorIDs are caller-owned, stable identities. A zero ID omits that +// control. Canvas enables dragging, wheel zoom and keyboard editing; Reset +// adds a reset button when there is room. +type AvatarEditorIDs struct { + Canvas, Zoom, ZoomOut, ZoomIn, Reset gfx.ID +} + +// AvatarEditorLabels localizes the accessible names and empty states. Empty +// fields use English defaults. +type AvatarEditorLabels struct { + Hint, Canvas, Zoom, ZoomOut, ZoomIn, Reset string + Loading, Unavailable string +} + +// AvatarEditorState is caller-owned and survives paints. Zoom 1 fits the +// largest crop of the requested aspect ratio inside the source. CenterX and +// CenterY are normalized source coordinates. Use the zero value for a new +// image or to reset to the largest centered crop allowed by the options. +type AvatarEditorState struct { + Zoom, CenterX, CenterY float32 + gesture avatarEditorGesture + dragX, dragY float32 +} + +type avatarEditorGesture uint8 + +const ( + avatarEditorGestureNone avatarEditorGesture = iota + avatarEditorGestureCanvas + avatarEditorGestureZoom +) + +// AvatarEditorOptions is a snapshot for one paint. The bitmap remains owned +// by the caller; its dimensions define the coordinate space for Crop. See +// gfx.Bitmap for pixel format and cache identity. +type AvatarEditorOptions struct { + IDs AvatarEditorIDs + Labels AvatarEditorLabels + Bitmap gfx.Bitmap + State AvatarEditorState + + // AspectRatio is width / height, defaulting to 1. + AspectRatio float32 + // MinZoom defaults to 1 and cannot go below it. MaxZoom defaults to 8 + // (or MinZoom, if larger). Set both equal for a fixed zoom. + MinZoom, MaxZoom float32 + // MaxStageSize caps the preview's longest edge, defaulting to 320 + // logical pixels. The preview also fits inside the supplied bounds. + MaxStageSize float32 + // Circular masks a square preview; Crop is still a rectangle. Backdrop + // must match the containing surface's solid, opaque color and defaults + // to theme.Background. + Circular bool + Backdrop gfx.Color + // Loading or Error disables editing, even if Bitmap is still present. + // Error takes precedence when both are set. + Loading bool + Error string +} + +// AvatarEditorLayout describes the current frame and routes its input. Keep +// it until the next paint. When Ready, Crop is the selected rectangle in +// bitmap pixels and Stage is the preview in logical window coordinates. +type AvatarEditorLayout struct { + Stage, Crop gfx.Rect + Ready bool + State AvatarEditorState + + ids AvatarEditorIDs + zoomBounds gfx.Rect + geometry avatarCropGeometry +} + +// AvatarEditor paints a crop surface. Loading an image, choosing a container +// and applying or exporting the crop are the caller's responsibility. +type AvatarEditor struct { + canvas *gfx.Canvas + theme gfx.Theme + bounds gfx.Rect + options AvatarEditorOptions +} + +// BeginAvatarEditor prepares a crop surface for the caller-provided bounds. +func BeginAvatarEditor(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, options AvatarEditorOptions) AvatarEditor { + return AvatarEditor{canvas: canvas, theme: theme, bounds: bounds, options: options} +} + +// Paint draws the preview and the controls that fit. Save the returned State +// so zoom and reset button clicks persist, and save the layout to route input. +func (editor AvatarEditor) Paint() AvatarEditorLayout { + c, theme, bounds, o := editor.canvas, editor.theme, editor.bounds, editor.options + out := AvatarEditorLayout{State: o.State, ids: o.IDs} + if c == nil || !finiteAvatarValue(bounds.Width) || !finiteAvatarValue(bounds.Height) || + bounds.Width <= 0 || bounds.Height <= 0 { + return out + } + labels := normalizedAvatarEditorLabels(o.Labels) + aspect, minZoom, maxZoom := avatarEditorLimits(o) + stageMax := o.MaxStageSize + if !finiteAvatarValue(stageMax) || stageMax <= 0 { + stageMax = 320 + } + + c.Clip(bounds) + defer c.Unclip() + row := avatarEditorControls(c, theme, bounds, o.IDs, labels.Reset) + availableHeight := bounds.Height + if row.height > 0 { + availableHeight -= row.height + avatarEditorRowGap + } + width, height := min(bounds.Width, stageMax), min(availableHeight, stageMax) + if aspect >= 1 { + width = min(width, height*aspect) + height = width / aspect + } else { + height = min(height, width/aspect) + width = height * aspect + } + stage := gfx.Rect{X: bounds.X + (bounds.Width-width)/2, Y: bounds.Y, Width: width, Height: height} + out.Stage = stage + if width <= 0 || height <= 0 { + return out + } + controls := row.at(bounds.X+(bounds.Width-row.width)/2, stage.Y+stage.Height+avatarEditorRowGap) + out.zoomBounds = controls[1] + + ready := !o.Loading && o.Error == "" && avatarBitmapReady(o.Bitmap) + if ready { + out.geometry = newAvatarCropGeometry(o.Bitmap, aspect, minZoom, maxZoom) + } + state := o.State + if ready { + state = out.geometry.normalize(state) + // Apply button clicks before drawing so Crop and the preview agree. + switch { + case controls[0].Width > 0 && c.Clicked(o.IDs.ZoomOut): + state = out.geometry.zoom(state, state.Zoom/1.2, .5, .5) + case controls[2].Width > 0 && c.Clicked(o.IDs.ZoomIn): + state = out.geometry.zoom(state, state.Zoom*1.2, .5, .5) + case controls[3].Width > 0 && c.Clicked(o.IDs.Reset): + state = out.geometry.normalize(AvatarEditorState{}) + } + out.Crop = out.geometry.crop(state) + ready = out.Crop.X+out.Crop.Width > out.Crop.X && out.Crop.Y+out.Crop.Height > out.Crop.Y + if !ready { + out.Crop = gfx.Rect{} + } + } else { + state.gesture = avatarEditorGestureNone + } + out.State, out.Ready = state, ready + + avatarEditorPaintStage(c, theme, stage, out, o, labels, o.Circular && aspect == 1) + if controls[0].Width > 0 { + avatarEditorZoomButton(c, theme, controls[0], o.IDs.ZoomOut, avatarEditorZoomOutIcon, labels.ZoomOut, !ready || state.Zoom <= minZoom) + } + if controls[1].Width > 0 { + avatarEditorPaintZoom(c, theme, o.IDs.Zoom, controls[1], state.Zoom, minZoom, maxZoom, ready, labels.Zoom) + } + if controls[2].Width > 0 { + avatarEditorZoomButton(c, theme, controls[2], o.IDs.ZoomIn, avatarEditorZoomInIcon, labels.ZoomIn, !ready || state.Zoom >= maxZoom) + } + if controls[3].Width > 0 { + reset := BeginButton(c, theme, o.IDs.Reset, controls[3]).Small() + if !ready { + reset = reset.Disabled() + } + reset.Outline(labels.Reset) + } + return out +} + +const avatarEditorRowGap = 12 + +type avatarEditorControlRow struct { + widths [4]float32 + width, gap, height float32 +} + +func avatarEditorControls(c *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, ids AvatarEditorIDs, resetLabel string) avatarEditorControlRow { + height := max(float32(32), theme.Metrics.ControlHeight) + if bounds.Height <= height+avatarEditorRowGap { + return avatarEditorControlRow{} + } + row := avatarEditorControlRow{height: height, gap: max(float32(10), theme.Metrics.GapItem)} + if !ids.ZoomOut.IsZero() { + row.widths[0] = height + } + if !ids.Zoom.IsZero() { + row.widths[1] = 24 + } + if !ids.ZoomIn.IsZero() { + row.widths[2] = height + } + if !ids.Reset.IsZero() { + row.widths[3] = max(float32(56), c.TextWidthWeight(resetLabel, theme.Metrics.FontSizeS, gfx.WeightMedium)+24) + } + row.width = avatarEditorRowWidth(row.widths, row.gap) + if row.width > bounds.Width { + row.widths[3] = 0 // Give the zoom controls priority over reset. + row.width = avatarEditorRowWidth(row.widths, row.gap) + } + if row.width > bounds.Width && row.widths[1] > 0 { + row.widths[0], row.widths[2] = 0, 0 + row.width = row.widths[1] + } + if row.width <= 0 || row.width > bounds.Width { + return avatarEditorControlRow{} + } + if row.widths[1] > 0 { + extra := max(0, bounds.Width-24-row.width) + row.widths[1] += extra + row.width += extra + } + return row +} + +func avatarEditorRowWidth(widths [4]float32, gap float32) float32 { + var width float32 + for _, w := range widths { + if w > 0 { + if width > 0 { + width += gap + } + width += w + } + } + return width +} + +func (row avatarEditorControlRow) at(x, y float32) (controls [4]gfx.Rect) { + for i, width := range row.widths { + if width > 0 { + controls[i] = gfx.Rect{X: x, Y: y, Width: width, Height: row.height} + x += width + row.gap + } + } + return controls +} + +func avatarEditorPaintStage(c *gfx.Canvas, theme gfx.Theme, stage gfx.Rect, out AvatarEditorLayout, o AvatarEditorOptions, labels AvatarEditorLabels, circular bool) { + c.Clip(stage) + if circular { + c.DrawPath(avatarEditorCircleFillPath(), stage, gfx.PathStyle{Fill: theme.Muted}) + } else { + c.Fill(stage, theme.Muted) + } + if out.Ready { + // Sample the source directly in one draw, including when magnified. + c.DrawBitmapRegion(o.Bitmap, out.Crop, stage) + if circular { + backdrop := o.Backdrop + if backdrop.Alpha == 0 { + backdrop = theme.Background + } + c.DrawPath(avatarEditorCircleMaskPath(), stage, gfx.PathStyle{Fill: backdrop, FillRule: gfx.PathFillEvenOdd}) + } else { + avatarEditorPaintGuides(c, theme, stage) + } + } else { + message, color := labels.Unavailable, theme.Danger + if o.Error != "" { + message = o.Error + } else if o.Loading { + message, color = labels.Loading, theme.MutedForeground + } + c.LabelCenter(message, stage, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}) + } + id := o.IDs.Canvas + border := theme.Border + if !id.IsZero() && (c.Pressed() == id || c.FocusVisible() == id || out.State.gesture == avatarEditorGestureCanvas) { + border = theme.Ring + } + if circular { + // A stroke is centred on its path, so the path sits half a width inside + // the stage to keep the whole ring visible, as Avatar does. + half := avatarEditorBorderWidth / 2 + ring := gfx.Rect{X: stage.X + half, Y: stage.Y + half, Width: stage.Width - 2*half, Height: stage.Height - 2*half} + c.DrawPath(avatarEditorCircleFillPath(), ring, gfx.PathStyle{Stroke: border, StrokeWidth: avatarEditorBorderWidth}) + } else { + c.RoundedBorder(stage, 0, avatarEditorBorderWidth, border, gfx.Color{}) + } + c.Unclip() + if !id.IsZero() { + cursor := gfx.PointerCursorHand + if out.State.gesture == avatarEditorGestureCanvas { + cursor = gfx.PointerCursorGrabbing + } + c.HitWithOptions(id, stage, labels.Canvas, gfx.HitOptions{ + Role: gfx.RoleGroup, Cursor: cursor, Hint: labels.Hint, Disabled: !out.Ready, + }) + } +} + +func avatarEditorZoomButton(c *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, id gfx.ID, icon gfx.Icon, label string, disabled bool) { + button := BeginButton(c, theme, id, bounds).IconSmall().WithIcon(icon) + if disabled { + button = button.Disabled() + } + button.Ghost(label) +} + +// Pointer handles primary-button drags of the preview or zoom slider. +func (layout AvatarEditorLayout) Pointer(event gfx.PointerEvent, state AvatarEditorState) (AvatarEditorState, gfx.EventResult) { + if !layout.Ready || event.Button != gfx.PointerButtonPrimary && event.Button != gfx.PointerButtonNone { + return state, gfx.EventResult{} + } + if event.Kind == gfx.PointerExit && !event.Captured && state.gesture != avatarEditorGestureNone { + state.gesture = avatarEditorGestureNone + return state, gfx.EventResult{Repaint: true} + } + canvas := !layout.ids.Canvas.IsZero() && event.Target == layout.ids.Canvas + slider := layout.zoomEnabled() && event.Target == layout.ids.Zoom + if !canvas && !slider { + return state, gfx.EventResult{} + } + switch event.Kind { + case gfx.PointerDown: + state = layout.geometry.normalize(state) + if slider { + state.gesture = avatarEditorGestureZoom + state = layout.zoomAtX(state, event.X) + } else { + state.gesture = avatarEditorGestureCanvas + state.dragX, state.dragY = event.X, event.Y + } + case gfx.PointerMove: + if !event.Captured { + return state, gfx.EventResult{} + } + switch { + case canvas && state.gesture == avatarEditorGestureCanvas: + state = layout.pan(state, state.dragX-event.X, state.dragY-event.Y) + state.dragX, state.dragY = event.X, event.Y + case slider && state.gesture == avatarEditorGestureZoom: + state = layout.zoomAtX(state, event.X) + default: + return state, gfx.EventResult{} + } + case gfx.PointerUp: + if !(canvas && state.gesture == avatarEditorGestureCanvas || slider && state.gesture == avatarEditorGestureZoom) { + return state, gfx.EventResult{} + } + state.gesture = avatarEditorGestureNone + default: + return state, gfx.EventResult{} + } + return state, gfx.EventResult{Handled: true, Repaint: true} +} + +// Scroll zooms around the pointer. At a zoom limit, a scroll that would go +// farther is left for the containing page to handle. +func (layout AvatarEditorLayout) Scroll(event gfx.ScrollEvent, state AvatarEditorState) (AvatarEditorState, gfx.EventResult) { + if !layout.Ready || layout.ids.Canvas.IsZero() || event.Target != layout.ids.Canvas || event.DeltaY == 0 { + return state, gfx.EventResult{} + } + view := layout.geometry.normalize(state) + delta := min(float32(8), max(float32(-8), event.StepY(1))) + target := view.Zoom * float32(math.Pow(1.15, -float64(delta))) + stage := layout.Stage + focusX := min(1, max(0, (event.X-stage.X)/stage.Width)) + focusY := min(1, max(0, (event.Y-stage.Y)/stage.Height)) + next := layout.geometry.zoom(view, target, focusX, focusY) + if next.Zoom == view.Zoom { + return state, gfx.EventResult{} + } + return next, gfx.EventResult{Handled: true, Repaint: true} +} + +// Key handles unmodified editing keys (and Shift for larger moves). Canvas +// arrows pan, +/- and Page Up/Down zoom, and Home resets the view. The zoom +// slider follows standard slider keys. Enter and app shortcuts pass through. +func (layout AvatarEditorLayout) Key(event gfx.KeyEvent, state AvatarEditorState) (AvatarEditorState, gfx.EventResult) { + if !layout.Ready || event.Release || event.Modifiers&(gfx.ModifierControl|gfx.ModifierMeta|gfx.ModifierAlt) != 0 || + event.Target.IsZero() { + return state, gfx.EventResult{} + } + view := layout.geometry.normalize(state) + result := gfx.EventResult{Handled: true, Repaint: true} + if event.Target == layout.ids.Zoom && layout.zoomEnabled() { + g := layout.geometry + value, handled := SliderKeyDownLarge(view.Zoom, g.minZoom, g.maxZoom, avatarEditorZoomStep, 1, LTR, event.Key, event.Modifiers) + if !handled { + return state, gfx.EventResult{} + } + // Home and End select the exact endpoints, including custom bounds that + // aren't an integer number of steps apart. + if event.Key == gfx.KeyEnd { + value = g.maxZoom + } + return g.zoom(view, value, .5, .5), result + } + if event.Target != layout.ids.Canvas { + return state, gfx.EventResult{} + } + step := float32(8) + if event.Modifiers&gfx.ModifierShift != 0 { + step = 24 + } + switch event.Key { + case gfx.KeyLeft: + view = layout.pan(view, -step, 0) + case gfx.KeyRight: + view = layout.pan(view, step, 0) + case gfx.KeyUp: + view = layout.pan(view, 0, -step) + case gfx.KeyDown: + view = layout.pan(view, 0, step) + case gfx.KeyPageUp: + view = layout.geometry.zoom(view, view.Zoom*1.15, .5, .5) + case gfx.KeyPageDown: + view = layout.geometry.zoom(view, view.Zoom/1.15, .5, .5) + case gfx.KeyHome: + view = layout.geometry.normalize(AvatarEditorState{}) + default: + switch event.Text { + case "+", "=": + view = layout.geometry.zoom(view, view.Zoom*1.15, .5, .5) + case "-": + view = layout.geometry.zoom(view, view.Zoom/1.15, .5, .5) + default: + return state, gfx.EventResult{} + } + } + return view, result +} + +func normalizedAvatarEditorLabels(labels AvatarEditorLabels) AvatarEditorLabels { + if labels.Hint == "" { + labels.Hint = "Drag to reposition. Scroll, use the slider, or use the zoom buttons." + } + if labels.Canvas == "" { + labels.Canvas = "Image crop" + } + if labels.Zoom == "" { + labels.Zoom = "Zoom" + } + if labels.ZoomOut == "" { + labels.ZoomOut = "Zoom out" + } + if labels.ZoomIn == "" { + labels.ZoomIn = "Zoom in" + } + if labels.Reset == "" { + labels.Reset = "Reset" + } + if labels.Loading == "" { + labels.Loading = "Loading image…" + } + if labels.Unavailable == "" { + labels.Unavailable = "This image could not be displayed." + } + return labels +} + +func finiteAvatarValue(value float32) bool { + return value >= -math.MaxFloat32 && value <= math.MaxFloat32 +} + +func avatarEditorLimits(o AvatarEditorOptions) (aspect, minZoom, maxZoom float32) { + aspect = o.AspectRatio + if !finiteAvatarValue(aspect) || aspect <= 0 { + aspect = 1 + } + minZoom = o.MinZoom + if !finiteAvatarValue(minZoom) || minZoom < 1 { + minZoom = 1 + } + maxZoom = o.MaxZoom + if !finiteAvatarValue(maxZoom) || maxZoom < minZoom { + maxZoom = max(8, minZoom) + } + return aspect, minZoom, maxZoom +} + +func avatarBitmapReady(bitmap gfx.Bitmap) bool { + if bitmap.Width <= 0 || bitmap.Height <= 0 || bitmap.Width > len(bitmap.Pix)/4 || bitmap.Stride < bitmap.Width*4 { + return false + } + return (len(bitmap.Pix)-bitmap.Width*4)/bitmap.Stride >= bitmap.Height-1 +} + +type avatarCropGeometry struct { + image, base gfx.Size + minZoom, maxZoom float32 +} + +func newAvatarCropGeometry(bitmap gfx.Bitmap, aspect, minZoom, maxZoom float32) avatarCropGeometry { + image := gfx.Size{Width: float32(bitmap.Width), Height: float32(bitmap.Height)} + base := image + if image.Width/image.Height > aspect { + base.Width = image.Height * aspect + } else { + base.Height = image.Width / aspect + } + return avatarCropGeometry{image: image, base: base, minZoom: minZoom, maxZoom: maxZoom} +} + +func (g avatarCropGeometry) normalize(state AvatarEditorState) AvatarEditorState { + if !finiteAvatarValue(state.Zoom) || state.Zoom <= 0 { + state.Zoom, state.CenterX, state.CenterY = 1, .5, .5 + } + state.Zoom = min(g.maxZoom, max(g.minZoom, state.Zoom)) + if !finiteAvatarValue(state.CenterX) { + state.CenterX = .5 + } + if !finiteAvatarValue(state.CenterY) { + state.CenterY = .5 + } + width, height := g.base.Width/state.Zoom, g.base.Height/state.Zoom + halfWidth, halfHeight := width/g.image.Width/2, height/g.image.Height/2 + state.CenterX = min(1-halfWidth, max(halfWidth, state.CenterX)) + state.CenterY = min(1-halfHeight, max(halfHeight, state.CenterY)) + return state +} + +func (g avatarCropGeometry) crop(state AvatarEditorState) gfx.Rect { + width, height := g.base.Width/state.Zoom, g.base.Height/state.Zoom + return gfx.Rect{ + X: min(g.image.Width-width, max(0, state.CenterX*g.image.Width-width/2)), + Y: min(g.image.Height-height, max(0, state.CenterY*g.image.Height-height/2)), + Width: width, Height: height, + } +} + +func (g avatarCropGeometry) zoom(state AvatarEditorState, target, focusX, focusY float32) AvatarEditorState { + if math.IsNaN(float64(target)) { + return state + } + target = min(g.maxZoom, max(g.minZoom, target)) + if state.Zoom == target { + return state + } + before := g.crop(state) + state.Zoom = target + state.CenterX = (before.X + focusX*before.Width + (.5-focusX)*g.base.Width/target) / g.image.Width + state.CenterY = (before.Y + focusY*before.Height + (.5-focusY)*g.base.Height/target) / g.image.Height + return g.normalize(state) +} + +func (layout AvatarEditorLayout) pan(state AvatarEditorState, dx, dy float32) AvatarEditorState { + g := layout.geometry + state = g.normalize(state) + // Use the latest draft zoom even if the caller has not painted again yet. + state.CenterX += dx * (g.base.Width / state.Zoom / g.image.Width) / layout.Stage.Width + state.CenterY += dy * (g.base.Height / state.Zoom / g.image.Height) / layout.Stage.Height + return g.normalize(state) +} + +func (layout AvatarEditorLayout) zoomEnabled() bool { + return layout.zoomBounds.Width > 0 && layout.geometry.maxZoom > layout.geometry.minZoom +} + +const ( + avatarEditorZoomThumb = 14 + avatarEditorZoomStep = .1 +) + +func (layout AvatarEditorLayout) zoomAtX(state AvatarEditorState, x float32) AvatarEditorState { + track := layout.zoomBounds + fraction := min(1, max(0, (x-track.X-avatarEditorZoomThumb/2)/(track.Width-avatarEditorZoomThumb))) + g := layout.geometry + return g.zoom(g.normalize(state), g.minZoom+fraction*(g.maxZoom-g.minZoom), .5, .5) +} + +func avatarEditorPaintGuides(c *gfx.Canvas, theme gfx.Theme, stage gfx.Rect) { + color := theme.Foreground + color.Alpha = .22 + for _, fraction := range [...]float32{1.0 / 3, 2.0 / 3} { + c.Fill(gfx.Rect{X: stage.X + stage.Width*fraction, Y: stage.Y, Width: 1, Height: stage.Height}, color) + c.Fill(gfx.Rect{X: stage.X, Y: stage.Y + stage.Height*fraction, Width: stage.Width, Height: 1}, color) + } +} + +func avatarEditorPaintZoom(c *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx.Rect, zoom, minZoom, maxZoom float32, ready bool, label string) { + centerY := bounds.Y + bounds.Height/2 + track := gfx.Rect{X: bounds.X + avatarEditorZoomThumb/2, Y: centerY - 2, Width: bounds.Width - avatarEditorZoomThumb, Height: 4} + c.Rounded(track, 2, theme.Muted) + fraction := float32(0) + if ready && maxZoom > minZoom { + fraction = min(1, max(0, (zoom-minZoom)/(maxZoom-minZoom))) + c.Rounded(gfx.Rect{X: track.X, Y: track.Y, Width: track.Width * fraction, Height: track.Height}, 2, theme.Primary) + } + if ready { + thumbX := track.X + track.Width*fraction + thumb := gfx.Rect{X: thumbX - avatarEditorZoomThumb/2, Y: centerY - avatarEditorZoomThumb/2, Width: avatarEditorZoomThumb, Height: avatarEditorZoomThumb} + if c.FocusVisible() == id { + c.Rounded(expand(thumb, 3), avatarEditorZoomThumb/2+3, theme.Ring) + } + c.Rounded(thumb, avatarEditorZoomThumb/2, theme.Background) + c.RoundedBorder(thumb, avatarEditorZoomThumb/2, 1.5, theme.Primary, gfx.Color{}) + } else { + zoom = minZoom + } + c.HitWithOptions(id, bounds, label, gfx.HitOptions{ + Role: gfx.RoleSlider, + Range: gfx.ValueRange{Min: float64(minZoom), Max: float64(maxZoom), Now: float64(zoom), Step: avatarEditorZoomStep, Set: true}, + Disabled: !ready || maxZoom == minZoom, Cursor: gfx.PointerCursorHand, + }) +} + +// avatarEditorBorderWidth is the stage border's thickness in logical pixels. It +// is constant across stage sizes for both the rectangular and circular stage. +const avatarEditorBorderWidth float32 = 1.5 + +var ( + avatarEditorCirclePathsOnce sync.Once + avatarEditorCircleMask gfx.Path + avatarEditorCircleFill gfx.Path +) + +func avatarEditorCircleMaskPath() gfx.Path { + avatarEditorCirclePathsOnce.Do(initAvatarEditorCirclePaths) + return avatarEditorCircleMask +} + +func avatarEditorCircleFillPath() gfx.Path { + avatarEditorCirclePathsOnce.Do(initAvatarEditorCirclePaths) + return avatarEditorCircleFill +} + +func initAvatarEditorCirclePaths() { + avatarEditorCircleMask = gfx.NewPath(100, 100, + // Keep the square edge away from the circle's four tangent points. + // Otherwise even-odd tessellation leaves a seam across the bottom of + // the stage where the circle contour touches the outer contour. + gfx.MoveTo(-2, -2), gfx.LineTo(102, -2), gfx.LineTo(102, 102), gfx.LineTo(-2, 102), gfx.ClosePath(), + gfx.MoveTo(50, 0), + gfx.CubicTo(77.614, 0, 100, 22.386, 100, 50), + gfx.CubicTo(100, 77.614, 77.614, 100, 50, 100), + gfx.CubicTo(22.386, 100, 0, 77.614, 0, 50), + gfx.CubicTo(0, 22.386, 22.386, 0, 50, 0), + gfx.ClosePath(), + ) + avatarEditorCircleFill = gfx.NewPath(100, 100, + gfx.MoveTo(50, 0), + gfx.CubicTo(77.614, 0, 100, 22.386, 100, 50), + gfx.CubicTo(100, 77.614, 77.614, 100, 50, 100), + gfx.CubicTo(22.386, 100, 0, 77.614, 0, 50), + gfx.CubicTo(0, 22.386, 22.386, 0, 50, 0), + gfx.ClosePath(), + ) +} + +var avatarEditorZoomOutIcon = gfx.Icon{ + ViewBox: 24, Stroke: 1.8, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{ + gfx.MoveTo(10.5, 4), + gfx.CubicTo(14.09, 4, 17, 6.91, 17, 10.5), + gfx.CubicTo(17, 14.09, 14.09, 17, 10.5, 17), + gfx.CubicTo(6.91, 17, 4, 14.09, 4, 10.5), + gfx.CubicTo(4, 6.91, 6.91, 4, 10.5, 4), + gfx.ClosePath(), + gfx.MoveTo(15.2, 15.2), gfx.LineTo(20, 20), + gfx.MoveTo(7.2, 10.5), gfx.LineTo(13.8, 10.5), + }, +} + +var avatarEditorZoomInIcon = gfx.Icon{ + ViewBox: 24, Stroke: 1.8, Cap: gfx.CapRound, Join: gfx.JoinRound, + Commands: []gfx.PathCommand{ + gfx.MoveTo(10.5, 4), + gfx.CubicTo(14.09, 4, 17, 6.91, 17, 10.5), + gfx.CubicTo(17, 14.09, 14.09, 17, 10.5, 17), + gfx.CubicTo(6.91, 17, 4, 14.09, 4, 10.5), + gfx.CubicTo(4, 6.91, 6.91, 4, 10.5, 4), + gfx.ClosePath(), + gfx.MoveTo(15.2, 15.2), gfx.LineTo(20, 20), + gfx.MoveTo(7.2, 10.5), gfx.LineTo(13.8, 10.5), + gfx.MoveTo(10.5, 7.2), gfx.LineTo(10.5, 13.8), + }, +} diff --git a/components/avatar_editor_driver_test.go b/components/avatar_editor_driver_test.go new file mode 100644 index 000000000..e08f765f1 --- /dev/null +++ b/components/avatar_editor_driver_test.go @@ -0,0 +1,117 @@ +package components_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +type avatarEditorDriverModel struct { + options components.AvatarEditorOptions + layout components.AvatarEditorLayout +} + +func (model *avatarEditorDriverModel) page(c ui.C) { + ui.Slot(c).Fill().Draw(func(d *ui.DrawContext) { + model.layout = components.BeginAvatarEditor(d.Canvas, *d.Theme, d.Rect, model.options).Paint() + model.options.State = model.layout.State + }) +} + +func TestAvatarEditorDriverInteraction(t *testing.T) { + state := components.AvatarEditorState{Zoom: 2, CenterX: .5, CenterY: .5} + ids := components.AvatarEditorIDs{ + Canvas: gfx.Item(4), Zoom: gfx.Item(5), ZoomOut: gfx.Item(6), ZoomIn: gfx.Item(7), + Reset: gfx.Item(8), + } + pixels := make([]byte, 160*100*4) + model := &avatarEditorDriverModel{options: components.AvatarEditorOptions{ + IDs: ids, State: state, AspectRatio: 1, Circular: true, + Bitmap: gfx.Bitmap{Pix: pixels, Width: 160, Height: 100, Stride: 160 * 4, ID: 1, Version: 1}, + Labels: components.AvatarEditorLabels{ + Hint: "Drag and zoom", Canvas: "Avatar crop", + Zoom: "Zoom", ZoomOut: "Zoom out", ZoomIn: "Zoom in", Reset: "Reset", + }, + }} + page := ui.NewPage(ui.PageConfig{View: model.page, Theme: themePointer(gfx.LightTheme())}) + driver, err := app.NewDriver(page.Config(app.Config{ + Width: 900, Height: 680, + OnPointer: func(event gfx.PointerEvent) gfx.EventResult { + state, result := model.layout.Pointer(event, model.options.State) + model.options.State = state + return result + }, + OnScroll: func(event gfx.ScrollEvent) gfx.EventResult { + state, result := model.layout.Scroll(event, model.options.State) + model.options.State = state + return result + }, + OnKey: func(event gfx.KeyEvent) gfx.EventResult { + state, result := model.layout.Key(event, model.options.State) + model.options.State = state + return result + }, + }), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(driver.Close) + + canvasHit := driverAvatarHit(t, driver, ids.Canvas) + x := canvasHit.Bounds.X + canvasHit.Bounds.Width/2 + y := canvasHit.Bounds.Y + canvasHit.Bounds.Height/2 + if err := driver.Press(x-60, y+25, gfx.PointerButtonPrimary); err != nil { + t.Fatal(err) + } + if err := driver.Move(x+35, y-45); err != nil { + t.Fatal(err) + } + if err := driver.Release(x+35, y-45, gfx.PointerButtonPrimary); err != nil { + t.Fatal(err) + } + if model.options.State.CenterX == .5 || model.options.State.CenterY == .5 { + t.Fatalf("driver drag did not update the crop: %+v", model.options.State) + } + + beforeZoom := model.options.State.Zoom + if err := driver.Scroll(gfx.ScrollEvent{X: x, Y: y, DeltaY: -1}); err != nil { + t.Fatal(err) + } + if model.options.State.Zoom <= beforeZoom { + t.Fatalf("driver scroll did not zoom in: %+v", model.options.State) + } + + if err := driver.Key(gfx.KeyHome, 0); err != nil { + t.Fatal(err) + } + if model.options.State.Zoom != 1 || model.options.State.CenterX != .5 || model.options.State.CenterY != .5 { + t.Fatalf("driver key did not reset: %+v", model.options.State) + } + + zoomIn := driverAvatarHit(t, driver, ids.ZoomIn) + if err := driver.Click(zoomIn.Bounds.X+zoomIn.Bounds.Width/2, zoomIn.Bounds.Y+zoomIn.Bounds.Height/2); err != nil { + t.Fatal(err) + } + if model.options.State.Zoom <= 1 { + t.Fatalf("zoom button did not update state: %+v", model.options.State) + } + if model.layout.Crop.Width >= float32(model.options.Bitmap.Height) { + t.Fatalf("zoom button returned an unzoomed crop: %+v", model.layout.Crop) + } +} + +func themePointer(theme gfx.Theme) *gfx.Theme { return &theme } + +func driverAvatarHit(t *testing.T, driver *app.Driver, id gfx.ID) gfx.Hit { + t.Helper() + for _, hit := range driver.Snapshot().Hits { + if hit.ID == id { + return hit + } + } + t.Fatalf("missing avatar editor hit %v", id) + return gfx.Hit{} +} diff --git a/components/avatar_editor_test.go b/components/avatar_editor_test.go new file mode 100644 index 000000000..c09f05173 --- /dev/null +++ b/components/avatar_editor_test.go @@ -0,0 +1,355 @@ +package components + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" +) + +func avatarEditorTestBitmap(width, height int) gfx.Bitmap { + pixels := make([]byte, width*height*4) + for i := range pixels { + pixels[i] = byte(i*31 + 17) + } + return gfx.Bitmap{Pix: pixels, Width: width, Height: height, Stride: width * 4, ID: 91, Version: 2} +} + +func avatarEditorTestOptions() AvatarEditorOptions { + ids := AvatarEditorIDs{ + Canvas: gfx.Item(4), Zoom: gfx.Item(5), ZoomOut: gfx.Item(6), ZoomIn: gfx.Item(7), + Reset: gfx.Item(8), + } + return AvatarEditorOptions{ + IDs: ids, + Labels: AvatarEditorLabels{Hint: "Drag and zoom", Canvas: "Avatar crop"}, + Bitmap: avatarEditorTestBitmap(120, 80), + AspectRatio: 1, + Circular: true, + } +} + +func avatarEditorTestBounds() gfx.Rect { + return gfx.Rect{X: 24, Y: 20, Width: 456, Height: 500} +} + +func TestAvatarEditorCropMath(t *testing.T) { + bitmap := avatarEditorTestBitmap(120, 80) + geometry := newAvatarCropGeometry(bitmap, 1, 1, 8) + state := geometry.normalize(AvatarEditorState{}) + crop := geometry.crop(state) + if !avatarEditorRectNear(crop, gfx.Rect{X: 20, Y: 0, Width: 80, Height: 80}) { + t.Fatalf("initial square crop = %+v", crop) + } + + state.Zoom = 2 + crop = geometry.crop(state) + if !avatarEditorRectNear(crop, gfx.Rect{X: 40, Y: 20, Width: 40, Height: 40}) { + t.Fatalf("zoomed square crop = %+v", crop) + } + + state.Zoom, state.CenterX, state.CenterY = 1, .99, -.5 + crop = geometry.crop(geometry.normalize(state)) + if !avatarEditorRectNear(crop, gfx.Rect{X: 40, Y: 0, Width: 80, Height: 80}) { + t.Fatalf("clamped crop = %+v", crop) + } + + geometry = newAvatarCropGeometry(bitmap, 16.0/9.0, 1, 8) + crop = geometry.crop(geometry.normalize(AvatarEditorState{})) + if math.Abs(float64(crop.Width/crop.Height-16.0/9.0)) > 0.0001 || + crop.X < 0 || crop.Y < 0 || crop.X+crop.Width > 120.001 || crop.Y+crop.Height > 80.001 { + t.Fatalf("widescreen crop = %+v", crop) + } +} + +func TestAvatarEditorPaintAndInput(t *testing.T) { + for _, theme := range []gfx.Theme{gfx.LightTheme(), gfx.DarkTheme()} { + for _, scale := range []float32{1, 1.25, 1.5, 2} { + var canvas gfx.Canvas + canvas.SetPixelScale(scale) + options := avatarEditorTestOptions() + options.IDs.Reset = gfx.ID{} + options.State = AvatarEditorState{Zoom: 2, CenterX: .5, CenterY: .5} + options.Backdrop = gfx.Color{Red: .12, Green: .23, Blue: .34, Alpha: 1} + bounds := avatarEditorTestBounds() + layout := BeginAvatarEditor(&canvas, theme, bounds, options).Paint() + if !layout.Ready || layout.Stage.Width <= 0 || layout.Stage.Height <= 0 || layout.Crop.Width != layout.Crop.Height { + t.Fatalf("scale %v: incomplete layout %+v", scale, layout) + } + if layout.Stage.X < bounds.X || layout.Stage.X+layout.Stage.Width > bounds.X+bounds.Width { + t.Fatalf("scale %v: crop surface escaped its bounds: %+v", scale, layout) + } + if !canvas.TrappedFocusScope().IsZero() || !canvas.EscapeTarget().IsZero() { + t.Fatal("crop surface installed dialog routing") + } + if texts := canvas.Texts(); len(texts) != 0 { + t.Fatalf("scale %v: crop surface painted dialog chrome text: %+v", scale, texts) + } + backdropFound := false + for _, triangle := range canvas.Triangles() { + backdropFound = backdropFound || triangle.Color == options.Backdrop + } + if !backdropFound { + t.Fatalf("scale %v: circular mask did not use the caller's backdrop", scale) + } + if images := canvas.Images(); len(images) != 1 { + t.Fatalf("scale %v: circular preview used %d bitmap draws, want 1", scale, len(images)) + } + canvasHits, zoomHits := 0, 0 + for _, hit := range canvas.Hits() { + switch hit.ID { + case options.IDs.Canvas: + canvasHits++ + if hit.Cursor != gfx.PointerCursorHand { + t.Fatalf("crop cursor = %v", hit.Cursor) + } + case options.IDs.Zoom: + zoomHits++ + if hit.Role != gfx.RoleSlider || !hit.Range.Set { + t.Fatalf("zoom hit = %+v", hit) + } + } + } + if canvasHits != 1 || zoomHits != 1 { + t.Fatalf("scale %v: crop hits %d, zoom hits %d", scale, canvasHits, zoomHits) + } + + state := layout.State + startX := layout.Stage.X + layout.Stage.Width/2 + startY := layout.Stage.Y + layout.Stage.Height/2 + state, result := layout.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, + Target: options.IDs.Canvas, X: startX, Y: startY, + }, state) + if !result.Handled { + t.Fatal("crop drag did not begin") + } + state, result = layout.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerMove, Button: gfx.PointerButtonPrimary, Captured: true, + Target: options.IDs.Canvas, X: startX - 80, Y: startY + 30, + }, state) + if !result.Handled || state.CenterX <= .5 || state.CenterY >= .5 { + t.Fatalf("crop drag state = %+v", state) + } + state, result = layout.Pointer(gfx.PointerEvent{ + Kind: gfx.PointerUp, Button: gfx.PointerButtonPrimary, + Target: options.IDs.Canvas, X: startX - 80, Y: startY + 30, + }, state) + if !result.Handled || state.gesture != avatarEditorGestureNone { + t.Fatal("crop drag did not end") + } + + beforeZoom := state.Zoom + state, result = layout.Scroll(gfx.ScrollEvent{ + Target: options.IDs.Canvas, X: startX + 40, Y: startY - 20, DeltaY: -1, + }, state) + if !result.Handled || state.Zoom <= beforeZoom { + t.Fatalf("wheel zoom = %+v, %+v", state, result) + } + + beforeX := state.CenterX + state, result = layout.Key(gfx.KeyEvent{Target: options.IDs.Canvas, Key: gfx.KeyLeft}, state) + if !result.Handled || state.CenterX >= beforeX { + t.Fatalf("keyboard pan = %+v, %+v", state, result) + } + state, result = layout.Key(gfx.KeyEvent{Target: options.IDs.Canvas, Key: gfx.KeyHome}, state) + if !result.Handled || state.Zoom != 1 || state.CenterX != .5 || state.CenterY != .5 { + t.Fatalf("keyboard reset = %+v", state) + } + if _, result = layout.Key(gfx.KeyEvent{Target: options.IDs.Canvas, Key: gfx.KeyEnter}, state); result.Handled { + t.Fatal("crop input claimed the application's submit key") + } + if _, result = layout.Key(gfx.KeyEvent{Target: options.IDs.Canvas, Key: gfx.KeyLeft, Modifiers: gfx.ModifierControl}, state); result.Handled { + t.Fatal("crop input claimed the application's keyboard shortcut") + } + } + } +} + +func TestAvatarEditorLoadingAndAllocations(t *testing.T) { + options := avatarEditorTestOptions() + options.Loading = true + var canvas gfx.Canvas + paint := func() { + canvas.Reset() + BeginAvatarEditor(&canvas, gfx.LightTheme(), avatarEditorTestBounds(), options).Paint() + } + paint() + for _, hit := range canvas.Hits() { + if hit.ID == options.IDs.Canvas && !hit.Disabled || hit.ID == options.IDs.Zoom && !hit.Disabled { + t.Fatalf("loading editor enabled %+v", hit) + } + } + if allocations := testing.AllocsPerRun(100, paint); allocations != 0 { + t.Fatalf("editor paint allocations = %v", allocations) + } + + options = avatarEditorTestOptions() + paint = func() { + canvas.Reset() + BeginAvatarEditor(&canvas, gfx.LightTheme(), avatarEditorTestBounds(), options).Paint() + } + paint() + if allocations := testing.AllocsPerRun(100, paint); allocations != 0 { + t.Fatalf("ready editor paint allocations = %v", allocations) + } +} + +func TestAvatarEditorFitsConstrainedBounds(t *testing.T) { + options := avatarEditorTestOptions() + options.MaxStageSize = 100 + var canvas gfx.Canvas + for _, bounds := range []gfx.Rect{ + {X: 7, Y: 11, Width: 120, Height: 180}, + {X: 7, Y: 11, Width: 60, Height: 100}, + {X: 7, Y: 11, Width: 12, Height: 32}, + {X: 7, Y: 11, Width: 120, Height: 6}, + } { + canvas.Reset() + layout := BeginAvatarEditor(&canvas, gfx.LightTheme(), bounds, options).Paint() + if !layout.Ready || layout.Stage.Width > 100 || layout.Stage.Height > 100 { + t.Fatalf("bounds %+v: invalid crop layout %+v", bounds, layout) + } + slider := false + for _, hit := range canvas.Hits() { + if hit.Bounds.X < bounds.X || hit.Bounds.X+hit.Bounds.Width > bounds.X+bounds.Width || + hit.Bounds.Y < bounds.Y || hit.Bounds.Y+hit.Bounds.Height > bounds.Y+bounds.Height { + t.Fatalf("bounds %+v: hit escaped its container: %+v", bounds, hit) + } + slider = slider || hit.ID == options.IDs.Zoom + } + if slider != (bounds.Width >= 60 && bounds.Height >= 100) { + t.Fatalf("bounds %+v: slider present = %v", bounds, slider) + } + } +} + +func TestAvatarEditorZoomLimitsAndStatus(t *testing.T) { + options := avatarEditorTestOptions() + options.IDs.Reset = gfx.ID{} + options.MinZoom = .5 + options.MaxZoom = float32(math.Inf(1)) + options.AspectRatio = float32(math.NaN()) + var canvas gfx.Canvas + paint := func() AvatarEditorLayout { + canvas.Reset() + return BeginAvatarEditor(&canvas, gfx.LightTheme(), avatarEditorTestBounds(), options).Paint() + } + layout := paint() + if !layout.Ready || layout.State.Zoom != 1 || !avatarEditorRectNear(layout.Crop, gfx.Rect{X: 20, Width: 80, Height: 80}) { + t.Fatalf("invalid limits must fall back to a crop inside the source: %+v", layout) + } + options.MinZoom, options.MaxZoom = 2, 2 + layout = paint() + if !layout.Ready || layout.State.Zoom != 2 || layout.Crop.Width != 40 { + t.Fatalf("fixed zoom = %+v", layout) + } + for _, hit := range canvas.Hits() { + if hit.ID == options.IDs.Zoom && !hit.Disabled { + t.Fatal("fixed zoom slider can receive focus or input") + } + } + _, result := layout.Scroll(gfx.ScrollEvent{Target: options.IDs.Canvas, DeltaY: -1}, layout.State) + if result.Handled { + t.Fatal("fixed zoom stole the containing page's wheel input") + } + options.Error = "Cannot open the new image" + options.Loading = true + layout = paint() + if layout.Ready || layout.Crop != (gfx.Rect{}) || len(canvas.Images()) != 0 { + t.Fatal("the loading or error state offered the previous image as a crop") + } + if texts := canvas.Texts(); len(texts) != 1 || texts[0].Value != options.Error { + t.Fatalf("error must be shown before the loading message: %+v", texts) + } +} + +func TestAvatarEditorPaintsTheCropReturnedAfterZoomClick(t *testing.T) { + var canvas gfx.Canvas + options := avatarEditorTestOptions() + canvas.BeginEventPass(options.IDs.ZoomIn, gfx.ClickInfo{}) + defer canvas.EndEventPass() + layout := BeginAvatarEditor(&canvas, gfx.LightTheme(), avatarEditorTestBounds(), options).Paint() + images := canvas.Images() + if !layout.Ready || layout.State.Zoom <= 1 || len(images) != 1 || !avatarEditorRectNear(images[0].Source, layout.Crop) { + t.Fatalf("preview and returned source crop disagree after a click: %+v", layout) + } +} + +func BenchmarkAvatarEditor(b *testing.B) { + for _, circular := range []bool{false, true} { + name := "square" + if circular { + name = "circular" + } + b.Run(name, func(b *testing.B) { + options := avatarEditorTestOptions() + options.Circular = circular + var canvas gfx.Canvas + paint := func() { + canvas.Reset() + BeginAvatarEditor(&canvas, gfx.LightTheme(), avatarEditorTestBounds(), options).Paint() + } + paint() + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + paint() + } + }) + } +} + +func avatarEditorRectNear(a, b gfx.Rect) bool { + const epsilon = .0001 + return math.Abs(float64(a.X-b.X)) < epsilon && + math.Abs(float64(a.Y-b.Y)) < epsilon && + math.Abs(float64(a.Width-b.Width)) < epsilon && + math.Abs(float64(a.Height-b.Height)) < epsilon +} + +// The circular stage's border must keep the same logical thickness at every +// stage size; a thickness that scales with the stage is nearly invisible when +// the stage is small. +func TestAvatarEditorCircleBorderKeepsItsWidthAcrossStageSizes(t *testing.T) { + theme := gfx.LightTheme() + var widths []float32 + for _, maxStage := range []float32{100, 320} { + options := avatarEditorTestOptions() + options.MaxStageSize = maxStage + var canvas gfx.Canvas + layout := BeginAvatarEditor(&canvas, theme, avatarEditorTestBounds(), options).Paint() + stage := layout.Stage + if !layout.Ready || stage.Width <= 0 || stage.Width != stage.Height { + t.Fatalf("max stage %v: no square crop stage: %+v", maxStage, layout) + } + const tolerance = 0.01 + centre := gfx.Point{X: stage.X + stage.Width/2, Y: stage.Y + stage.Height/2} + inner, outer := float32(math.Inf(1)), float32(0) + for _, triangle := range canvas.Triangles() { + if triangle.Color != theme.Border { + continue + } + for _, point := range triangle.Points { + if point.X < stage.X-tolerance || point.X > stage.X+stage.Width+tolerance || + point.Y < stage.Y-tolerance || point.Y > stage.Y+stage.Height+tolerance { + continue + } + radius := float32(math.Hypot(float64(point.X-centre.X), float64(point.Y-centre.Y))) + inner = min(inner, radius) + outer = max(outer, radius) + } + } + if outer == 0 { + t.Fatalf("max stage %v: circular stage drew no border", maxStage) + } + width := outer - inner + if math.Abs(float64(width-avatarEditorBorderWidth)) > 0.05 { + t.Fatalf("max stage %v (stage %v): border width %v, want %v", maxStage, stage.Width, width, avatarEditorBorderWidth) + } + widths = append(widths, stage.Width) + } + if len(widths) != 2 || widths[0] == widths[1] { + t.Fatalf("stage sizes did not differ, test proves nothing: %v", widths) + } +} diff --git a/components/doc.go b/components/doc.go index 3a227108e..d1d2bf99f 100644 --- a/components/doc.go +++ b/components/doc.go @@ -60,6 +60,15 @@ // its Query editor to the application's text-input provider. // // Actions: +// - Avatar editor: `BeginAvatarEditor` paints a crop surface inside +// caller-provided bounds. It owns drag-to-position, pointer-centered wheel +// zoom, a zoom slider and buttons, keyboard controls, an optional circular +// preview, and a caller-configurable aspect ratio. Titles, modal chrome, +// and confirm/cancel actions remain with the surrounding application. +// Start with a zero AvatarEditorState, keep the state returned from Paint +// and from the layout's Pointer, Scroll and Key handlers, and read Crop in +// source bitmap pixels only when Ready. Reset the state when the source +// changes. // - Button: `BeginButton` paints a labeled control with Default, Secondary, // Outline, and Ghost variants; hover, press, and focus states, metrics- // scaled geometry, and the hit declaration are built in. diff --git a/internal/componentdemo/avatar_editor.go b/internal/componentdemo/avatar_editor.go new file mode 100644 index 000000000..6c0eca9cc --- /dev/null +++ b/internal/componentdemo/avatar_editor.go @@ -0,0 +1,120 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/components" + "github.com/vivaui/viva/gfx" +) + +var avatarEditorComponent = Component{ + ID: "avatar-editor", Title: "Avatar Editor", Category: "Media", + Summary: "嵌入任意容器的头像裁切表面,支持拖动、缩放、圆形预览和任意宽高比。", + paint: (*State).paintAvatarEditor, pointer: (*State).pointerAvatarEditor, + key: (*State).keyAvatarEditor, scroll: (*State).scrollAvatarEditor, + initialize: func(state *State) { + const width, height = 360, 240 + pixels := make([]byte, width*height*4) + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + offset := (y*width + x) * 4 + pixels[offset] = byte(42 + x*170/width) + pixels[offset+1] = byte(35 + y*190/height) + pixels[offset+2] = byte(70 + (x+y)*80/(width+height)) + pixels[offset+3] = 255 + } + } + state.avatarEditor = &avatarEditorDemoState{ + bitmap: gfx.Bitmap{Pix: pixels, Width: width, Height: height, Stride: width * 4, ID: 0xa7e1, Version: 1}, + } + }, + Examples: []Example{ + { + ID: "avatar", Title: "嵌入圆形裁切表面", Height: 560, + Description: "组件只绘制预览与缩放控件;标题、弹窗和确认操作由调用方安排。", + Snippet: `layout := components.BeginAvatarEditor(canvas, theme, bounds, components.AvatarEditorOptions{ + IDs: ids, Bitmap: bitmap, State: draft, + AspectRatio: 1, Circular: true, MaxStageSize: 320, + Labels: labels, +}).Paint() +draft = layout.State +// The caller owns the surrounding dialog or panel and uses layout.Crop when layout.Ready.`, + }, + { + ID: "cover", Title: "自定义宽高比", Height: 520, + Description: "同一个组件可裁剪 16:9 封面;Crop 始终是源图片中的目标比例区域。", + Snippet: `options.AspectRatio = 16.0 / 9.0 +options.Circular = false +layout := components.BeginAvatarEditor(canvas, theme, bounds, options).Paint() +sourceRegion := layout.Crop`, + }, + }, +} + +var avatarEditorDemoIDs = components.AvatarEditorIDs{ + Canvas: tree.ID(tree.Feature("avatar-editor"), "canvas"), + Zoom: tree.ID(tree.Feature("avatar-editor"), "zoom"), + ZoomOut: tree.ID(tree.Feature("avatar-editor"), "zoom-out"), + ZoomIn: tree.ID(tree.Feature("avatar-editor"), "zoom-in"), + Reset: tree.ID(tree.Feature("avatar-editor"), "reset"), +} + +type avatarEditorDemoState struct { + bitmap gfx.Bitmap + state components.AvatarEditorState + layout components.AvatarEditorLayout +} + +func (state *State) paintAvatarEditor(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := state.avatarEditor + aspect := float32(1) + circular := true + if state.exampleID == "cover" { + aspect, circular = 16.0/9.0, false + } + stageSize := min(float32(320), max(float32(1), size.Width-48)) + control := max(float32(32), theme.Metrics.ControlHeight) + bounds := gfx.Rect{ + X: 24, Y: 24, + Width: min(float32(440), max(float32(1), size.Width-48)), + Height: min(max(float32(1), size.Height-48), stageSize+control+12), + } + options := components.AvatarEditorOptions{ + IDs: avatarEditorDemoIDs, Bitmap: demo.bitmap, State: demo.state, + AspectRatio: aspect, Circular: circular, MaxStageSize: stageSize, + Labels: components.AvatarEditorLabels{ + Hint: state.Text("拖动图片调整位置,滚轮、滑杆或按钮缩放。", "Drag to reposition. Scroll, use the slider, or use the buttons to zoom."), + Canvas: state.Text("头像裁切区域", "Image crop"), Zoom: state.Text("缩放", "Zoom"), + ZoomOut: state.Text("缩小", "Zoom out"), ZoomIn: state.Text("放大", "Zoom in"), + Reset: state.Text("重置", "Reset"), Loading: state.Text("正在读取图片…", "Loading image…"), + Unavailable: state.Text("无法读取这张图片", "This image could not be displayed."), + }, + } + demo.layout = components.BeginAvatarEditor(canvas, theme, bounds, options).Paint() + demo.state = demo.layout.State +} + +func (state *State) pointerAvatarEditor(event gfx.PointerEvent) gfx.EventResult { + if state.avatarEditor == nil { + return gfx.EventResult{} + } + var result gfx.EventResult + state.avatarEditor.state, result = state.avatarEditor.layout.Pointer(event, state.avatarEditor.state) + return result +} + +func (state *State) scrollAvatarEditor(event gfx.ScrollEvent) gfx.EventResult { + if state.avatarEditor == nil { + return gfx.EventResult{} + } + var result gfx.EventResult + state.avatarEditor.state, result = state.avatarEditor.layout.Scroll(event, state.avatarEditor.state) + return result +} + +func (state *State) keyAvatarEditor(event gfx.KeyEvent) gfx.EventResult { + if state.avatarEditor == nil { + return gfx.EventResult{} + } + var result gfx.EventResult + state.avatarEditor.state, result = state.avatarEditor.layout.Key(event, state.avatarEditor.state) + return result +} diff --git a/internal/componentdemo/catalog_a.go b/internal/componentdemo/catalog_a.go index 13d563cf5..8ddadaeb2 100644 --- a/internal/componentdemo/catalog_a.go +++ b/internal/componentdemo/catalog_a.go @@ -7,6 +7,7 @@ var groupAComponents = []Component{ aspectRatioComponent, attachmentComponent, avatarComponent, + avatarEditorComponent, breadcrumbComponent, bubbleComponent, buttonGroupComponent, diff --git a/internal/componentdemo/catalog_a_test.go b/internal/componentdemo/catalog_a_test.go index accacf44f..6a9124e72 100644 --- a/internal/componentdemo/catalog_a_test.go +++ b/internal/componentdemo/catalog_a_test.go @@ -45,7 +45,7 @@ func snapshotGroupAPaint(canvas *gfx.Canvas) groupAPaintSnapshot { func TestGroupACatalogOrder(t *testing.T) { want := []string{ "accordion", "alert", "alert-dialog", "aspect-ratio", "attachment", - "avatar", "breadcrumb", "bubble", "button-group", "calendar", "card", + "avatar", "avatar-editor", "breadcrumb", "bubble", "button-group", "calendar", "card", "carousel", "chart", "chart-area", "chart-bar", "chart-downsample", "collapsible", "combobox", } if len(groupAComponents) != len(want) { diff --git a/internal/componentdemo/state.go b/internal/componentdemo/state.go index f8685598e..21eee578f 100644 --- a/internal/componentdemo/state.go +++ b/internal/componentdemo/state.go @@ -103,16 +103,17 @@ type State struct { fieldID gfx.ID editing bool // textarea keeps the rows and scroll of the Textarea example. - textarea *components.TextareaLayout - codeEditor *components.CodeEditor - codeDiff *codeDiffDemoState - codeMerge *codeMergeDemoState - reorder *reorderDemoState - reorderGrid *reorderGridDemoState - imageBitmap *gfx.Bitmap - dialog dialogState - slider sliderDemoState - picker *colorPickerDemoState + textarea *components.TextareaLayout + codeEditor *components.CodeEditor + codeDiff *codeDiffDemoState + codeMerge *codeMergeDemoState + reorder *reorderDemoState + reorderGrid *reorderGridDemoState + imageBitmap *gfx.Bitmap + avatarEditor *avatarEditorDemoState + dialog dialogState + slider sliderDemoState + picker *colorPickerDemoState // chart keeps the hover and label caches of the chart examples. chart *chartDemoState // list is the page-layer List example: its rows, choice and page. From b4ee5fdeaa55e306c619f07af745e96d43712e58 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Tue, 17 Nov 2026 23:40:15 +0800 Subject: [PATCH 05/23] fix(ui): keep ContextMenu rows apart from target parts --- ui/control_parts_test.go | 52 ++++++++++++++++++++++++++++++++++++++++ ui/menu.go | 7 ++++++ ui/page.go | 2 ++ 3 files changed, 61 insertions(+) diff --git a/ui/control_parts_test.go b/ui/control_parts_test.go index 4e6e02972..d6f8ed260 100644 --- a/ui/control_parts_test.go +++ b/ui/control_parts_test.go @@ -154,3 +154,55 @@ func TestControlPartsRepaintAllocates(t *testing.T) { t.Fatalf("%v allocations a repaint", allocs) } } + +// A ContextMenu on a control with parts keeps its rows and its backdrop apart from +// the parts: a click on any row chooses it, and the click that dismisses the menu +// presses no part, rather than either reaching the control as a press on a part. +func TestControlContextMenuIsNotItsParts(t *testing.T) { + s := newStars() + var chosen []string + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Gap(8).Children(func() { + rating := ui.Control(c, "Rating", &s.handlers).Size(240, 32).Draw(s.drawFn) + ui.ContextMenu(c, rating, func(menu *ui.MenuItems) { + for _, label := range [...]string{"Clear", "Half", "Full"} { + if menu.Item(label).Clicked() { + chosen = append(chosen, label) + } + } + }) + }) + }) + // The control's own area, right of the stars, opens the menu. + rating := d.hit("Rating").Bounds + x, y := rating.X+rating.Width-10, rating.Y+rating.Height/2 + openMenu := func() { + t.Helper() + if err := d.driver.ClickButton(x, y, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + if !d.has("Clear") { + t.Fatal("a secondary press on the control did not open its menu") + } + } + for _, label := range [...]string{"Clear", "Half", "Full"} { + openMenu() + d.click(label) + if n := len(chosen); n == 0 || chosen[n-1] != label || d.has("Clear") { + t.Fatalf("a click on %s chose %q, menu shown %v", label, chosen, d.has("Clear")) + } + } + openMenu() + if allocs := testing.AllocsPerRun(100, d.repaint); allocs != 0 { + t.Fatalf("%v allocations a repaint with the menu open", allocs) + } + if err := d.driver.Click(rating.X+rating.Width/2, rating.Y+200); err != nil { + t.Fatal(err) + } + if d.has("Clear") { + t.Fatal("a click outside the menu left it open") + } + if len(s.pressed) != 0 || s.value != 0 { + t.Fatalf("the menu pressed the parts %v, value %d", s.pressed, s.value) + } +} diff --git a/ui/menu.go b/ui/menu.go index 03864a30c..862b88ad0 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -122,6 +122,13 @@ func contextMenu(c C, target Box, bound gfx.Scope, opened *menuOrigin, body func // pointer opened it, and the chosen row (or a dismissal) closes it. open = &menu.shown } + if bound.IsZero() { + // The target's scope holds the identities inside it: the parts of a + // Control (Handlers.Parts) and the children of a container. The rows and + // the backdrop of the menu take a place of their own under it, or a press + // on a row would reach the control as a press on one of its parts. + scope = p.tree.Sub(scope, p.menuName) + } p.declareMenu(c, menu, scope, open, -1, opened, body) } } diff --git a/ui/page.go b/ui/page.go index 74cad6922..433f85c07 100644 --- a/ui/page.go +++ b/ui/page.go @@ -252,6 +252,7 @@ type Page struct { freshAt gfx.Scope kindName [pkKinds]gfx.Name keyName gfx.Name + menuName gfx.Name // the place of a ContextMenu inside its target (contextMenu) held [2]armedButton states map[protoStateKey]protoState fields []fieldEntry @@ -423,6 +424,7 @@ func (p *Page) init(tree *gfx.Tree) { p.kindName[kind] = p.tree.Name(fmt.Sprintf("~k%d", kind)) } p.keyName = p.tree.Name("~key") + p.menuName = p.tree.Name("~menu") p.freshAt = p.tree.Sub(p.root, p.tree.Name("~new")) p.keys = map[keyKey]keyEntry{} p.intKeys = map[intKey]keyEntry{} From a6f2bbeca3cb023d69c0da5f0691e32a70abba82 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 23:35:52 +0800 Subject: [PATCH 06/23] docs(ui): list every part the ContextMenu scope holds The menu scope holds the focus trap and the scroll bar as well as the rows and the backdrop, and those two were the actual collisions behind the bug, so the comment now names all four. Refs: #341 --- ui/menu.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ui/menu.go b/ui/menu.go index 862b88ad0..6dcbdf99c 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -124,9 +124,10 @@ func contextMenu(c C, target Box, bound gfx.Scope, opened *menuOrigin, body func } if bound.IsZero() { // The target's scope holds the identities inside it: the parts of a - // Control (Handlers.Parts) and the children of a container. The rows and - // the backdrop of the menu take a place of their own under it, or a press - // on a row would reach the control as a press on one of its parts. + // Control (Handlers.Parts) and the children of a container. The rows, the + // backdrop, the scroll bar and the focus trap of the menu take a place of + // their own under it, or a press on a row would reach the control as a + // press on one of its parts. scope = p.tree.Sub(scope, p.menuName) } p.declareMenu(c, menu, scope, open, -1, opened, body) From 45b87aee2e5c30819e028cbdea6ceacd6ecf5470 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Tue, 17 Nov 2026 23:42:27 +0800 Subject: [PATCH 07/23] fix(ui): let a context menu take the arrows from the focused control --- ui/menu.go | 4 +++- ui/menu_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/ui/menu.go b/ui/menu.go index 6dcbdf99c..9c9e7fd5c 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -740,7 +740,9 @@ func (p *Page) menuKey(event gfx.KeyEvent) (gfx.EventResult, bool) { trigger = m.f.nodes[m.anchor].id } _, inside := event.Target.In(m.scope) - last := i == len(p.menus)-1 && event.Target.IsZero() + // A context menu is modal: its arrows move through it from wherever the focus is, + // as a menu opened at a point of the window has no control of its own to be on. + last := i == len(p.menus)-1 && (event.Target.IsZero() || m.context) if !inside && !last && (event.Target != trigger || trigger.IsZero()) { continue } diff --git a/ui/menu_test.go b/ui/menu_test.go index df0e8e548..14fbdade0 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -555,3 +555,29 @@ func TestMenuTallerThanTheWindowScrollsToItsLastItem(t *testing.T) { t.Fatalf("chosen %q, open %v", m.chosen, m.open) } } + +// A context menu opened at a point is modal: the arrows move through it while the +// focus is still on the control that was focused when it opened. +func TestContextMenuAtTakesTheArrowsFromTheFocusedControl(t *testing.T) { + m := &contextModel{hosts: []string{"alpha"}} + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.Button(c, "Anchor") + ui.ContextMenuAt(c, ui.Button(c, "Header"), &m.open, gfx.Point{X: 100, Y: 100}, func(items *ui.MenuItems) { + items.Item("One") + if items.Item("Two").Clicked() { + m.connected = "two" + } + }) + }) + }) + d.click("Anchor") + m.open = true + d.repaint() + d.key(gfx.KeyDown) + d.key(gfx.KeyDown) + d.key(gfx.KeyEnter) + if m.connected != "two" || m.open { + t.Fatalf("connected %q, open %v: the arrows did not reach the menu", m.connected, m.open) + } +} From 21d5d36ac68e61428d3095771070a26358a4d0f2 Mon Sep 17 00:00:00 2001 From: Dean Cen Date: Tue, 17 Nov 2026 23:59:23 +0800 Subject: [PATCH 08/23] fix(windows): keep live resizing responsive without stretching content --- .github/workflows/ci.yml | 2 +- internal/platform/windows/api_windows_test.go | 3 +- .../composition_events_windows_test.go | 2 +- internal/platform/windows/device_windows.go | 10 +- .../windows/redraw_queue_windows_test.go | 13 +- internal/platform/windows/renderer_windows.go | 21 +- .../windows/window_resize_windows_test.go | 592 +++++++++++++++++- internal/platform/windows/window_windows.go | 310 +++++++-- 8 files changed, 866 insertions(+), 87 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d7cb217bf..9c8762500 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -293,7 +293,7 @@ jobs: # native structure ABI tests are here for the same reason: they build only # on Windows. - name: Material contracts and controls (WARP) - run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI)' -count=1 -v + run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame)' -count=1 -v - name: Terminal keyboard routing run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v - name: Native Windows global shortcut diff --git a/internal/platform/windows/api_windows_test.go b/internal/platform/windows/api_windows_test.go index 9a574c27d..6e2f58b1a 100644 --- a/internal/platform/windows/api_windows_test.go +++ b/internal/platform/windows/api_windows_test.go @@ -50,12 +50,13 @@ func TestNativeStructureABI(t *testing.T) { {"DWRITE_TEXT_METRICS", unsafe.Sizeof(textMetrics{}), 36}, {"rectangle shader instance", unsafe.Sizeof(rectangleInstance{}), rectangleInstanceBytes}, {"frame shader constants", unsafe.Sizeof(frameConstants{}), 64}, + {"DEVMODEW", unsafe.Sizeof(displayMode{}), 220}, } { if layout.size != layout.want { t.Errorf("%s: size %d, want %d", layout.name, layout.size, layout.want) } } - if unsafe.Offsetof(swapChainDesc1{}.Scaling) != 32 || unsafe.Offsetof(windowClass{}.Name) != 64 || unsafe.Offsetof(message{}.First) != 16 || unsafe.Offsetof(resourceData{}.Pitch) != 8 || unsafe.Offsetof(notifyIconData{}.Info) != 304 || unsafe.Offsetof(notifyIconData{}.BalloonIcon) != 968 { + if unsafe.Offsetof(swapChainDesc1{}.Scaling) != 32 || unsafe.Offsetof(windowClass{}.Name) != 64 || unsafe.Offsetof(message{}.First) != 16 || unsafe.Offsetof(resourceData{}.Pitch) != 8 || unsafe.Offsetof(displayMode{}.Frequency) != 184 || unsafe.Offsetof(notifyIconData{}.Info) != 304 || unsafe.Offsetof(notifyIconData{}.BalloonIcon) != 968 { t.Fatal("native member alignment mismatch") } wantTextureIID := guid{0x6f15aaf2, 0xd208, 0x4e89, [8]byte{0x9a, 0xb4, 0x48, 0x95, 0x35, 0xd3, 0x4f, 0x9c}} diff --git a/internal/platform/windows/composition_events_windows_test.go b/internal/platform/windows/composition_events_windows_test.go index 267ab762a..05e3d5aa9 100644 --- a/internal/platform/windows/composition_events_windows_test.go +++ b/internal/platform/windows/composition_events_windows_test.go @@ -433,7 +433,7 @@ func TestCompositionSupersededFrameDoesNotPublishOldNativeViews(t *testing.T) { } }) if err != nil || state.err != nil || state.textState != latest.State || - len(state.web.rects) != 1 || state.web.rects[0].ID != latestView.ID || presented == 0 || state.textRectangles[0] != base { + len(state.web.rects) != 1 || state.web.rects[0].ID != latestView.ID || presented != 0 || state.textRectangles[0] != base { t.Fatalf("superseded frame published: state=%+v views=%+v rectangle=%+v presented=%d err=%v", state.textState, state.web.rects, state.textRectangles[0], presented, err) } } diff --git a/internal/platform/windows/device_windows.go b/internal/platform/windows/device_windows.go index 816fdb545..7ba75b62a 100644 --- a/internal/platform/windows/device_windows.go +++ b/internal/platform/windows/device_windows.go @@ -74,10 +74,11 @@ func (state *windowState) present(width, height int) error { return state.presentWithSync(width, height, 1) } -// presentImmediate draws the window without waiting for the display refresh. A -// resize uses it so the frame drawn for the new client size reaches the swap -// chain before the window manager returns; the swap chain itself does not scale -// stale frames (see createWindowSwapChain). +// presentImmediate draws the window without waiting for the display refresh. +// Synchronous size changes must present before returning to the window manager, +// and the timer-paced modal resize path uses it too, since the timer already +// paces those frames. The swap chain itself does not scale stale frames (see +// createWindowSwapChain). func (state *windowState) presentImmediate(width, height int) error { return state.presentWithSync(width, height, 0) } @@ -104,6 +105,7 @@ func (state *windowState) presentWithSync(width, height int, sync uintptr) error // presented, or there was nothing to present. Its present-paced frame clock // asks for the next frame only after this. func (state *windowState) framePresented() { + state.paintPending = false if state.config.FramePresented != nil { state.config.FramePresented() } diff --git a/internal/platform/windows/redraw_queue_windows_test.go b/internal/platform/windows/redraw_queue_windows_test.go index 76ef66055..a1a25850f 100644 --- a/internal/platform/windows/redraw_queue_windows_test.go +++ b/internal/platform/windows/redraw_queue_windows_test.go @@ -1,7 +1,6 @@ package windows import ( - "errors" "sync" "sync/atomic" "testing" @@ -78,7 +77,7 @@ func TestRedrawQueueRetriesConcurrentWakeAfterNativePostFails(t *testing.T) { } } -func TestNativeRedrawMessageRearmsBeforeCallingThePainter(t *testing.T) { +func TestNativeRedrawMessageKeepsRequestsCoalescedUntilPaint(t *testing.T) { // Exercise the message dispatch without creating an OS window or renderer. state := &windowState{} handle := ^uintptr(0) @@ -88,14 +87,14 @@ func TestNativeRedrawMessageRearmsBeforeCallingThePainter(t *testing.T) { posts := 0 post := func() bool { posts++; return true } state.redraws.post(post) - stop := errors.New("stop before native rendering") state.config.OnRedraw = func() (platform.Frame, error) { - state.redraws.post(post) // a worker updates the state during painting - return platform.Frame{}, stop + t.Fatal("posted redraw must yield to hardware input before painting") + return platform.Frame{}, nil } windowProc(handle, wmRedraw, 0, 0) - if posts != 2 || state.err != stop { - t.Fatalf("posts=%d err=%v", posts, state.err) + state.redraws.post(post) + if posts != 1 || !state.redrawRequested { + t.Fatalf("posts=%d requested=%v", posts, state.redrawRequested) } } diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index f9ed52c9c..1ed348261 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -266,12 +266,8 @@ func (renderer *renderer) createDeviceAndResources(software bool) error { return fmt.Errorf("create D3D11 device and swap chain, hardware and software (WARP) both failed: %w: %w", platform.ErrNoGraphics, failure) } -// createWindowSwapChain makes the swap chain the window presents through. The -// scale mode is DXGI_SCALING_NONE: when the window changes size before the frame -// for the new size is presented, the desktop keeps the previous back buffer at -// its own size in the top-left corner instead of stretching it over the new -// client area. DXGI_SCALING_STRETCH (the default of the older -// D3D11CreateDeviceAndSwapChain path) is what made a live resize wobble. +// createWindowSwapChain keeps the previous frame at its native size between +// live resize ticks. DXGI fills newly exposed pixels with the renderer background. func (renderer *renderer) createWindowSwapChain() error { var factory uintptr status, _, _ := createDXGIFactory.Call(uintptr(unsafe.Pointer(&factory2IID)), uintptr(unsafe.Pointer(&factory))) @@ -288,6 +284,12 @@ func (renderer *renderer) createWindowSwapChain() error { if err := hresult(status); err != nil { return fmt.Errorf("create swap chain for window: %w", err) } + // IDXGISwapChain1::SetBackgroundColor is slot 25 (GetDesc1 is 18, GetHwnd 20, + // Present1 22, IsTemporaryMonoSupported 23, GetRestrictToOutput 24). The color + // only fills pixels a resize exposes, so its HRESULT is ignored: a failure must + // not fail device creation for hardware and WARP alike. + background := [4]float32{float32(renderer.color.Red), float32(renderer.color.Green), float32(renderer.color.Blue), float32(renderer.color.Alpha)} + comCall(renderer.swap, 25, uintptr(unsafe.Pointer(&background))) return nil } @@ -543,10 +545,9 @@ func (renderer *renderer) present(width, height int, scale float32) error { return renderer.presentWithSync(width, height, scale, 1) } -// presentWithSync presents with a DXGI sync interval. A live resize presents -// immediately (0) so the frame drawn for the new size reaches the swap chain -// before WM_SIZE returns; the swap chain itself uses DXGI_SCALING_NONE, so an -// older frame is shown at its own size instead of stretched over the window. +// presentWithSync presents with a DXGI sync interval. Modal resize ticks use 0 +// because the timer already paces them. HWND chains use DXGI_SCALING_NONE; +// composition chains retain the DXGI-required STRETCH mode without a visual scale. func (renderer *renderer) presentWithSync(width, height int, scale float32, sync uintptr) error { if width <= 0 || height <= 0 { return nil diff --git a/internal/platform/windows/window_resize_windows_test.go b/internal/platform/windows/window_resize_windows_test.go index 005cbc3dc..3123761cb 100644 --- a/internal/platform/windows/window_resize_windows_test.go +++ b/internal/platform/windows/window_resize_windows_test.go @@ -1,6 +1,7 @@ package windows import ( + "fmt" "runtime" "testing" "unsafe" @@ -9,11 +10,9 @@ import ( "github.com/vivaui/viva/internal/render" ) -// A live resize reaches the window as a stream of WM_SIZE messages. The swap -// chain is created with DXGI_SCALING_NONE, so a frame that has not been drawn -// for the new size is shown at its own size instead of stretched over the new -// client area. The frame for a new size must also reach the swap chain before -// WM_SIZE returns, or the desktop has only the previous one to show. +// A programmatic resize reaches the window as WM_SIZE outside a drag loop. The +// frame for the new size must reach the swap chain before WM_SIZE returns, or +// the desktop has only the previous one to show. func TestResizePresentsTheNewSizeBeforeReturning(t *testing.T) { runtime.LockOSThread() defer runtime.UnlockOSThread() @@ -46,18 +45,15 @@ func TestResizePresentsTheNewSizeBeforeReturning(t *testing.T) { } } -// The window's swap chain must not scale its contents: DXGI_SCALING_STRETCH is -// what let the desktop stretch the previous frame over the new client area -// during a live resize. A frame that is late then shows at its own size in the -// top-left corner instead. -func TestWindowSwapChainDoesNotScale(t *testing.T) { +// Old pixels keep their native size; newly exposed pixels use the clear color. +func TestWindowSwapChainDoesNotStretchStaleFrames(t *testing.T) { runtime.LockOSThread() defer runtime.UnlockOSThread() err := RunApplication(func(application platform.Application) error { opened, err := application.OpenWindow(platform.Config{ Title: "Viva swap chain scaling test", Width: 320, Height: 200, WindowMode: platform.WindowCustomTitlebar, TitlebarHeight: 32, - ClearColor: platform.Color{Alpha: 1}, + ClearColor: platform.Color{Red: .2, Green: .4, Blue: .6, Alpha: 1}, }) if err != nil { return err @@ -72,6 +68,15 @@ func TestWindowSwapChainDoesNotScale(t *testing.T) { if description.Scaling != 1 { // DXGI_SCALING_NONE t.Fatalf("swap chain scaling = %d, want DXGI_SCALING_NONE (1)", description.Scaling) } + var background [4]float32 + // IDXGISwapChain1::GetBackgroundColor follows SetBackgroundColor. + if err := hresult(comCall(state.renderer.swap, 26, uintptr(unsafe.Pointer(&background)))); err != nil { + return err + } + color := state.renderer.color + if background != [4]float32{float32(color.Red), float32(color.Green), float32(color.Blue), float32(color.Alpha)} { + t.Fatalf("swap chain background = %v, want renderer clear color", background) + } if description.SwapEffect != 3 { // DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL t.Fatalf("swap chain effect = %d, want DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL (3)", description.SwapEffect) } @@ -85,6 +90,567 @@ func TestWindowSwapChainDoesNotScale(t *testing.T) { } } +// A burst of native sizes is laid out once at the next modal timer tick. +func TestLiveResizeCoalescesLayoutBeforeExit(t *testing.T) { + for _, software := range []string{"0", "1"} { + t.Run("software="+software, func(t *testing.T) { + t.Setenv("VIVA_SOFTWARE_RENDERING", software) + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + resizes := 0 + var laidOut platform.Size + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva live resize test", Width: 640, Height: 400, + WindowMode: platform.WindowCustomTitlebar, TitlebarHeight: 32, + ClearColor: platform.Color{Alpha: 1}, + OnResize: func(size platform.Size) (platform.Frame, error) { + laidOut = size + resizes++ + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + }, + }) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + if err := state.renderer.present(640, 400, 1); err != nil { + return err + } + windowProc(state.window, 0x0231, 0, 0) // WM_ENTERSIZEMOVE + if !state.sizingMove || state.resizeTimerInterval < 10 { + return fmt.Errorf("modal entry did not arm the resize timer") + } + before := resizes + for step := range 12 { + width, height := uintptr(700+step*11), uintptr(450+step*7) + if ok, _, err := setWindowPosition.Call(state.window, 0, 0, 0, width, height, 0x16); ok == 0 { + return err + } + if resizes != before { + return fmt.Errorf("drag step %d rendered: OnResize ran %d times during the drag", step, resizes-before) + } + if state.renderer.width != 640 || state.renderer.height != 400 { + return fmt.Errorf("drag step %d resized the swap chain to %dx%d", step, state.renderer.width, state.renderer.height) + } + } + presents := resizeTestPresentCount(t, state) + windowProc(state.window, wmTimer, resizeTimerID, 0) + if resizes != before+1 || resizeTestPresentCount(t, state) != presents+1 { + return fmt.Errorf("timer must lay out and present once before exit") + } + windowProc(state.window, wmTimer, resizeTimerID, 0) + windowProc(state.window, wmExitSizeMove, 0, 0) + if state.sizingMove || state.resizeTimerInterval != 0 { + return fmt.Errorf("modal exit retained resize timer state") + } + if resizeTestPresentCount(t, state) != presents+1 { + return fmt.Errorf("clean tick or exit presented again") + } + var client rect + getClientRect.Call(state.window, uintptr(unsafe.Pointer(&client))) + if state.renderer.width != int(client.Right) || state.renderer.height != int(client.Bottom) { + return fmt.Errorf("after the drag the swap chain is %dx%d, client is %dx%d", state.renderer.width, state.renderer.height, client.Right, client.Bottom) + } + if resizes != before+1 || laidOut != state.logicalSize(int(client.Right), int(client.Bottom)) { + return fmt.Errorf("timer did not lay out the latest client size exactly once") + } + windowProc(state.window, wmEnterSizeMove, 0, 0) + if ok, _, err := setWindowPosition.Call(state.window, 0, 0, 0, 900, 600, 0x16); ok == 0 { + return err + } + windowProc(state.window, wmExitSizeMove, 0, 0) + getClientRect.Call(state.window, uintptr(unsafe.Pointer(&client))) + if resizes != before+2 || resizeTestPresentCount(t, state) != presents+2 || laidOut != state.logicalSize(int(client.Right), int(client.Bottom)) { + return fmt.Errorf("exit failed to flush geometry pending before the next tick") + } + return nil + }) + if err != nil { + t.Fatal(err) + } + }) + } +} + +func TestFlipWindowResizeAndRecoveryWithoutBackdrop(t *testing.T) { + for _, software := range []string{"0", "1"} { + t.Run("software="+software, func(t *testing.T) { + t.Setenv("VIVA_SOFTWARE_RENDERING", software) + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + var resized platform.Size + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva flip resize test", Width: 640, Height: 400, + WindowMode: platform.WindowCustomTitlebar, TitlebarHeight: 32, + ClearColor: platform.Color{Red: .2, Green: .4, Blue: .6, Alpha: 1}, + OnResize: func(size platform.Size) (platform.Frame, error) { + resized = size + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + }, + }) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + check := func() error { + style, _, _ := readCompositionWindowStyle.Call(state.window, ^uintptr(19)) + if style&wsExNoRedirectionBitmap != 0 { + return fmt.Errorf("window without a backdrop must keep the baseline redirection style") + } + var client rect + getClientRect.Call(state.window, uintptr(unsafe.Pointer(&client))) + if state.renderer.width != int(client.Right) || state.renderer.height != int(client.Bottom) { + return fmt.Errorf("presented %dx%d, client is %dx%d", state.renderer.width, state.renderer.height, client.Right, client.Bottom) + } + if resized != state.logicalSize(int(client.Right), int(client.Bottom)) { + return fmt.Errorf("layout size %+v does not match client", resized) + } + return nil + } + for _, scale := range []float32{1, 1.25, 1.5, 2} { + state.scale = scale + for step := range 12 { + width, height := uintptr(640+step*13), uintptr(400+step*7) + if step%2 == 1 { + width, height = 800-width/4, 600-height/4 + } + ok, _, err := setWindowPosition.Call(state.window, 0, 0, 0, width, height, 0x16) + if ok == 0 { + return err + } + if err := check(); err != nil { + return err + } + } + } + if err := state.renderer.recover(software == "1"); err != nil { + return err + } + setWindowPosition.Call(state.window, 0, 0, 0, 720, 480, 0x16) + if err := check(); err != nil { + return err + } + showWindow.Call(state.window, swMinimize) + showWindow.Call(state.window, swRestore) + return check() + }) + if err != nil { + t.Fatal(err) + } + }) + } +} + +// Redraw notifications must yield to input until WM_PAINT. Use a counted post +// callback so delivery is deterministic without pumping unrelated native messages. +func TestRedrawWaitsForPaintAndRetainsInvalidations(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva deferred redraw test", Width: 320, Height: 200, + WindowMode: platform.WindowCustomTitlebar, TitlebarHeight: 32, + ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + windowProc(state.window, wmPaint, 0, 0) + posts, redraws, moves := 0, 0, 0 + post := func() bool { posts++; return true } + invalidate := func() { + for range 20 { + state.redraws.post(post) + } + } + state.config.OnRedraw = func() (platform.Frame, error) { + redraws++ + if redraws == 1 { + invalidate() // Changes arriving while this frame is being built. + } + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + } + state.config.OnPointer = func(event platform.PointerEvent) (platform.Frame, error) { + if event.Kind == platform.PointerMove { + moves++ + } + return platform.Frame{}, nil + } + invalidate() + windowProc(state.window, wmRedraw, 0, 0) + invalidate() // Still coalesced after delivery, until painting begins. + windowProc(state.window, wmMouseMove, 0, uintptr(40|60<<16)) + if posts != 1 || redraws != 0 || moves != 1 { + return fmt.Errorf("before paint: posts=%d redraws=%d mouse moves=%d, want 1, 0, 1", posts, redraws, moves) + } + windowProc(state.window, wmPaint, 0, 0) + if redraws != 1 || posts != 2 { + return fmt.Errorf("first paint: redraws=%d posts=%d, want 1, 2 (one retained redraw)", redraws, posts) + } + windowProc(state.window, wmRedraw, 0, 0) + invalidate() + windowProc(state.window, wmMouseMove, 0, uintptr(41|61<<16)) + if redraws != 1 || posts != 2 || moves != 2 { + return fmt.Errorf("between paints: redraws=%d posts=%d mouse moves=%d, want 1, 2, 2", redraws, posts, moves) + } + windowProc(state.window, wmPaint, 0, 0) + presented := resizeTestPresentCount(t, state) + windowProc(state.window, wmPaint, 0, 0) + if resizeTestPresentCount(t, state) != presented { + return fmt.Errorf("redraw left a dirty region after paint: an empty paint presented again") + } + if redraws != 2 || posts != 2 { + return fmt.Errorf("after paints: redraws=%d posts=%d, want 2, 2", redraws, posts) + } + return state.err + }) + if err != nil { + t.Fatal(err) + } +} + +func TestContinuousRedrawRequestsYieldToNativePaint(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + redraws, presents := 0, 0 + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva redraw fairness test", Width: 320, Height: 200, + ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + state := opened.(*nativeWindow).state + request := func() { + state.redraws.post(func() bool { + posted, _, _ := postMessage.Call(state.window, wmRedraw, 0, 0) + return posted != 0 + }) + } + state.config.OnRedraw = func() (platform.Frame, error) { + redraws++ + if redraws >= 64 { + opened.Close() + } else { + request() + } + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + } + state.config.FramePresented = func() { + if redraws > 0 { + presents++ + opened.Close() + } + } + request() + return nil + }) + if err != nil { + t.Fatal(err) + } + if presents == 0 || redraws >= 64 { + t.Fatalf("continuous redraw requests starved native paint: redraws=%d presents=%d", redraws, presents) + } +} + +func TestNoOpFrameDoesNotAcknowledgePendingPaint(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva pending paint test", Width: 320, Height: 200, + WindowMode: platform.WindowCustomTitlebar, TitlebarHeight: 32, + ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + windowProc(state.window, wmPaint, 0, 0) + acknowledged := 0 + state.config.FramePresented = func() { acknowledged++ } + state.frame(platform.Frame{}, nil) + if acknowledged != 1 { + return fmt.Errorf("idle no-op acknowledged %d frames, want 1", acknowledged) + } + before := resizeTestPresentCount(t, state) + state.frame(platform.Frame{Update: render.Update{Rebuild: true}}, nil) + for range 3 { + state.frame(platform.Frame{}, nil) + } + if acknowledged != 1 || resizeTestPresentCount(t, state) != before { + return fmt.Errorf("dirty frame was acknowledged or presented before WM_PAINT: acknowledgements=%d, want 1", acknowledged) + } + windowProc(state.window, wmPaint, 0, 0) + if acknowledged != 2 || resizeTestPresentCount(t, state) != before+1 { + return fmt.Errorf("paint must present and acknowledge the pending frame exactly once: acknowledgements=%d, want 2", acknowledged) + } + state.frame(platform.Frame{}, nil) + if acknowledged != 3 { + return fmt.Errorf("no-op after paint: acknowledgements=%d, want 3", acknowledged) + } + return state.err + }) + if err != nil { + t.Fatal(err) + } +} + +// A move-only drag can consume dirty paints without changing the client size. +// The exit must still present them, then forget the deferred work. +func TestSameSizeDragExitPresentsPendingUpdates(t *testing.T) { + for _, software := range []string{"0", "1"} { + t.Run("software="+software, func(t *testing.T) { + t.Setenv("VIVA_SOFTWARE_RENDERING", software) + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva same-size drag test", Width: 320, Height: 200, + WindowMode: platform.WindowCustomTitlebar, TitlebarHeight: 32, + ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + var client rect + getClientRect.Call(state.window, uintptr(unsafe.Pointer(&client))) + state.presentClientSize(int(client.Right), int(client.Bottom)) + if state.err != nil { + return state.err + } + before := resizeTestPresentCount(t, state) + acknowledged, resizes := 0, 0 + state.config.FramePresented = func() { acknowledged++ } + state.config.OnResize = func(platform.Size) (platform.Frame, error) { + resizes++ + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + } + windowProc(state.window, wmEnterSizeMove, 0, 0) + for range 3 { + state.frame(platform.Frame{Update: render.Update{Rebuild: true}}, nil) + windowProc(state.window, wmPaint, 0, 0) + } + if acknowledged != 0 || resizes != 0 || resizeTestPresentCount(t, state) != before { + return fmt.Errorf("during drag: acknowledgements=%d resizes=%d; want 0, 0 and no native presents", acknowledged, resizes) + } + windowProc(state.window, wmExitSizeMove, 0, 0) + if resizes != 0 || acknowledged != 1 || resizeTestPresentCount(t, state) != before+1 { + return fmt.Errorf("same-size exit: resizes=%d acknowledgements=%d; want 0, 1 and one native present", resizes, acknowledged) + } + // No new updates: another move-only drag should do no rendering. + windowProc(state.window, wmEnterSizeMove, 0, 0) + windowProc(state.window, wmExitSizeMove, 0, 0) + if resizes != 0 || acknowledged != 1 || resizeTestPresentCount(t, state) != before+1 { + return fmt.Errorf("clean move-only exit rendered or acknowledged an extra frame") + } + return state.err + }) + if err != nil { + t.Fatal(err) + } + }) + } +} + +func TestResizeTimerRetainsCallbackUpdates(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva resize callback test", Width: 320, Height: 200, + ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + windowProc(state.window, wmPaint, 0, 0) + before := resizeTestPresentCount(t, state) + redraws, acknowledgements := 0, 0 + state.config.OnRedraw = func() (platform.Frame, error) { + redraws++ + // A nested timer must not enter layout/render again. A new redraw + // delivered inside this callback belongs to the following tick. + windowProc(state.window, wmTimer, resizeTimerID, 0) + if redraws == 1 { + windowProc(state.window, wmRedraw, 0, 0) + } + return platform.Frame{Update: render.Update{Rebuild: true}}, nil + } + state.config.FramePresented = func() { + acknowledgements++ + if acknowledgements == 1 { + state.frame(platform.Frame{Update: render.Update{Rebuild: true}}, nil) + } + } + windowProc(state.window, wmEnterSizeMove, 0, 0) + for range 10 { + windowProc(state.window, wmRedraw, 0, 0) + windowProc(state.window, wmPaint, 0, 0) + } + if redraws != 0 || acknowledgements != 0 || !state.redrawRequested { + return fmt.Errorf("paint bypassed modal cadence or consumed pending redraw") + } + windowProc(state.window, wmTimer, resizeTimerID, 0) + if redraws != 1 || acknowledgements != 1 || !state.redrawRequested || !state.paintPending { + return fmt.Errorf("first tick lost callback updates: redraws=%d acknowledgements=%d", redraws, acknowledgements) + } + windowProc(state.window, wmExitSizeMove, 0, 0) + if redraws != 2 || acknowledgements != 2 || resizeTestPresentCount(t, state) != before+2 { + return fmt.Errorf("exit did not flush callback updates once") + } + windowProc(state.window, wmTimer, resizeTimerID, 0) + if resizeTestPresentCount(t, state) != before+2 { + return fmt.Errorf("stale modal timer presented after exit") + } + return state.err + }) + if err != nil { + t.Fatal(err) + } +} + +func TestZeroSizeFrameAcknowledgesAndRestoresPendingPaint(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{ + Title: "Viva zero-size acknowledgement test", Width: 320, Height: 200, + ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + windowProc(state.window, wmPaint, 0, 0) + var client rect + getClientRect.Call(state.window, uintptr(unsafe.Pointer(&client))) + acknowledged := 0 + callbackSawPending := false + queueNext := false + state.config.FramePresented = func() { + acknowledged++ + callbackSawPending = callbackSawPending || state.paintPending + if queueNext { + state.frame(platform.Frame{Update: render.Update{Rebuild: true}}, nil) + } + } + for _, size := range [][2]int{{0, 200}, {320, 0}, {0, 0}} { + before := resizeTestPresentCount(t, state) + acks := acknowledged + state.presentClientSize(size[0], size[1]) + if state.err != nil { + return state.err + } + if acknowledged != acks+1 || state.paintPending || callbackSawPending || resizeTestPresentCount(t, state) != before { + return fmt.Errorf("empty size %v did not acknowledge and clear the pending frame without presenting", size) + } + queueNext = true + state.presentClientSize(size[0], size[1]) + queueNext = false + if acknowledged != acks+2 || !state.paintPending || callbackSawPending || resizeTestPresentCount(t, state) != before { + return fmt.Errorf("empty size %v lost the acknowledgement callback's pending frame", size) + } + state.presentClientSize(int(client.Right), int(client.Bottom)) + if state.err != nil { + return state.err + } + if acknowledged != acks+3 || state.paintPending || resizeTestPresentCount(t, state) != before+1 { + return fmt.Errorf("positive-size restoration did not present and acknowledge the pending frame once") + } + } + return state.err + }) + if err != nil { + t.Fatal(err) + } +} + +func TestResizeTimerRearmsOnlyWhenIntervalChanges(t *testing.T) { + state := windowState{} + var intervals []uintptr + armErr := fmt.Errorf("SetTimer failed") + fail := false + arm := func(interval uintptr) error { + intervals = append(intervals, interval) + if fail { + return armErr + } + return nil + } + check := func(interval, cached uintptr, calls int, wantErr error) { + t.Helper() + if err := state.rearmResizeTimer(interval, arm); err != wantErr { + t.Fatalf("rearm(%d) error = %v, want %v", interval, err, wantErr) + } + if state.resizeTimerInterval != cached || len(intervals) != calls { + t.Fatalf("rearm(%d): cached=%d calls=%v, want cache %d and %d calls", interval, state.resizeTimerInterval, intervals, cached, calls) + } + if calls > 0 && intervals[calls-1] < 10 { + t.Fatalf("timer interval below Win32 minimum: %v", intervals) + } + } + check(17, 0, 0, nil) // No modal timer outside a drag. + state.sizingMove = true + check(17, 17, 1, nil) + for range 10 { + check(17, 17, 1, nil) // Moves on the same refresh cadence must not defer the tick. + } + check(7, 10, 2, nil) // Move to a faster monitor, clamped to 10 ms. + check(9, 10, 2, nil) + check(34, 34, 3, nil) // Display mode changed while still dragging. + fail = true + check(17, 34, 4, armErr) // A failed rearm must not cache the requested interval. + fail = false + check(17, 17, 5, nil) + state.sizingMove = false + state.resizeTimerInterval = 0 + check(34, 0, 5, nil) + state.sizingMove = true + check(17, 17, 6, nil) // A new drag must arm even at the previous cadence. +} + +// A drag whose timer cannot start keeps the window open and presents each size +// change synchronously; the next drag arms the timer again. +func TestResizeTimerFailureDegradesToSynchronousResize(t *testing.T) { + state := windowState{sizingMove: true} + state.paceResize(17, func(uintptr) error { return fmt.Errorf("SetTimer failed") }) + if state.err != nil || state.sizingMove || state.resizeTimerInterval != 0 { + t.Fatalf("failed timer: err=%v sizingMove=%v cached=%d, want an open window and synchronous resizing", state.err, state.sizingMove, state.resizeTimerInterval) + } + var armed uintptr + state.sizingMove = true // WM_ENTERSIZEMOVE of the next drag + state.paceResize(17, func(interval uintptr) error { armed = interval; return nil }) + if armed != 17 || state.resizeTimerInterval != 17 || state.err != nil { + t.Fatalf("next drag armed %d, cached %d, err=%v", armed, state.resizeTimerInterval, state.err) + } +} + +// Query actual swap-chain presents: dimensions and frame acknowledgements alone +// cannot distinguish a suppressed paint from a successful same-size present. +func resizeTestPresentCount(t *testing.T, state *windowState) uint32 { + t.Helper() + var count uint32 + // IDXGISwapChain::GetLastPresentCount. + if err := hresult(comCall(state.renderer.swap, 17, uintptr(unsafe.Pointer(&count)))); err != nil { + t.Fatal(err) + } + return count +} + // BenchmarkResizePresent measures what one live-resize step costs on the window // thread: apply a frame and present it at a new client size, including // ResizeBuffers. A drag is one such step per pointer move. @@ -109,7 +675,9 @@ func BenchmarkResizePresent(b *testing.B) { for i := 0; i < b.N; i++ { width := 640 + i%320 height := 400 + i%240 - windowProc(state.window, wmSize, 0, uintptr(uint32(width)|uint32(height)<<16)) + if ok, _, err := setWindowPosition.Call(state.window, 0, 0, 0, uintptr(width), uintptr(height), 0x16); ok == 0 { + return err + } } b.StopTimer() return nil diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 03dcc92d6..29c2cb6ba 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -56,6 +56,8 @@ const ( wmWheel = 522 wmHorizontalWheel = 526 wmCaptureChanged = 533 + wmEnterSizeMove = 0x0231 + wmExitSizeMove = 0x0232 wmSettingChange = 26 wmFontChange = 29 wmMouseLeave = 675 @@ -82,14 +84,17 @@ type windowState struct { fullscreenStyle uint32 fullscreenPlacement windowPlacement backdropState - application *windowsApplication - config platform.Config - renderer renderer - window uintptr - ready, tracking, sizing bool - minimized bool - trimArmed bool // the idle timer that trims driver memory is running - lastPresent time.Time // when the window last presented a frame + application *windowsApplication + config platform.Config + renderer renderer + window uintptr + ready, tracking, sizing, sizingMove bool + redrawRequested, paintPending, resizePending bool + resizeTimerInterval uintptr + resizeMonitor, resizeMonitorInterval uintptr // the monitor resizeMonitorInterval was queried for + minimized bool + trimArmed bool // the idle timer that trims driver memory is running + lastPresent time.Time // when the window last presented a frame // hiddenByShow is set while ShowWindow has the window hidden; shownVisible is the last // visibility reported to OnVisibility, with ok set once one has been. hiddenByShow, shownVisible, shownKnown bool @@ -493,6 +498,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } } case wmDisplayChange: + // A mode change can alter the refresh rate of the monitor already cached. + state.resizeMonitorInterval = 0 + state.refreshResizeTimer() if state.fullscreen.Load() { state.fitFullscreenMonitor() return 0 @@ -544,11 +552,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } return 0 case wmRedraw: - state.redraws.begin() - if state.config.OnRedraw != nil { - frame, redrawErr := state.config.OnRedraw() - state.frame(frame, redrawErr) - } + // Keep posted redraws coalesced until WM_PAINT lets hardware input run first. + state.redrawRequested = true + invalidateRect.Call(window, 0, 0) return 0 case wmGetObject: if result, handled := state.accessibility.returnRawProvider(window, first, second); handled { @@ -653,11 +659,39 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { return 0 } case wmPaint: + if !state.sizingMove && !state.sizing && state.resizePending && !state.iconic() { + state.serviceResize() + return 0 + } + if state.sizingMove || state.sizing { + var paint paintStruct + beginPaint.Call(window, uintptr(unsafe.Pointer(&paint))) + if paint.Bounds.Right > paint.Bounds.Left && paint.Bounds.Bottom > paint.Bounds.Top { + state.paintPending = true + } + endPaint.Call(window, uintptr(unsafe.Pointer(&paint))) + return 0 + } + state.sizing = true + defer func() { + state.sizing = false + state.invalidatePendingFrame() + }() + if state.redrawRequested { + state.redrawRequested = false + state.redraws.begin() + if state.config.OnRedraw != nil { + frame, redrawErr := state.config.OnRedraw() + if err := state.frameWithText(frame, redrawErr, false); err != nil || state.window == 0 { + return 0 + } + } + } var paint paintStruct beginPaint.Call(window, uintptr(unsafe.Pointer(&paint))) // An empty update region has nothing left to draw. Presenting again would // block on the next vblank for no change. - if paint.Bounds.Right <= paint.Bounds.Left || paint.Bounds.Bottom <= paint.Bounds.Top { + if (paint.Bounds.Right <= paint.Bounds.Left || paint.Bounds.Bottom <= paint.Bounds.Top) && !state.paintPending { endPaint.Call(window, uintptr(unsafe.Pointer(&paint))) state.framePresented() return 0 @@ -684,6 +718,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } return 0 case wmMove: + state.refreshResizeTimer() state.reportFrame() if state.web != nil { state.web.moved() @@ -722,41 +757,21 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { state.config.OnMaximize(zoomed) } } - if state.sizing { - return 0 - } - state.sizing = true - defer func() { state.sizing = false }() - if state.config.OnResize != nil { - state.resizeEvents++ - frame, err := state.config.OnResize(state.logicalSize(int(uint16(second)), int(uint16(second>>16)))) - if err := state.frameWithText(frame, err, false); err != nil { - return 0 - } - } - state.reportFrame() - if state.web != nil { - state.web.layoutAll(true) - } - if state.ready { - // Draw the new size before returning to the window manager. The swap - // chain is scaled with DXGI_SCALING_NONE, so a frame that has not - // arrived yet is shown at its own size instead of stretched over the - // new client area. Maximize, restore and DPI changes take this path - // too; it is the same paint the queued WM_PAINT would have done, just - // earlier. - if err := state.presentImmediate(int(uint16(second)), int(uint16(second>>16))); err != nil { - state.fail(err) - } else { - state.scheduleTrim() - // presentImmediate drew the whole client area, so the invalidate - // PrepareFrame queued has nothing left to paint. ValidateRect - // removes it rather than drawing the same frame twice. - validateRect.Call(window, 0) - } + if state.sizingMove || state.sizing { + state.resizePending = true return 0 } - invalidateRect.Call(window, 0, 0) + state.presentClientSize(int(uint16(second)), int(uint16(second>>16))) + return 0 + case wmEnterSizeMove: + state.sizingMove = true + state.refreshResizeTimer() + return 0 + case wmExitSizeMove: + killTimer.Call(window, resizeTimerID) + state.sizingMove = false + state.resizeTimerInterval = 0 + state.serviceResize() return 0 case wmDPIChanged: if !state.scaleFixed { @@ -771,6 +786,10 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } else { setWindowPosition.Call(window, 0, uintptr(bounds.Left), uintptr(bounds.Top), uintptr(bounds.Right-bounds.Left), uintptr(bounds.Bottom-bounds.Top), 0x14) } + if state.sizingMove || state.sizing { + state.resizePending = true + return 0 + } state.reportFrame() if state.resizeEvents == resizes && state.config.OnResize != nil && state.ready { // The window kept its pixel size, so no WM_SIZE told the application the scale @@ -933,6 +952,12 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { return 0 } case wmTimer: + if first == resizeTimerID { + if state.sizingMove { + state.serviceResize() + } + return 0 + } if first == trimTimerID { state.handleTrimTimer() return 0 @@ -955,6 +980,187 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { return result } +const resizeTimerID = 3 + +// Refresh on monitor moves and mode changes without postponing ticks on every move. +func (state *windowState) refreshResizeTimer() { + if !state.sizingMove { + return + } + state.paceResize(state.resizeInterval(), func(interval uintptr) error { + if timer, _, err := setTimer.Call(state.window, resizeTimerID, interval, 0); timer == 0 { + return fmt.Errorf("windows: start resize timer: %w", err) + } + return nil + }) +} + +// paceResize keeps a drag paced at interval. If the timer cannot start, the drag +// falls back to synchronous presents: WM_SIZE and WM_PAINT present each size +// change themselves, as they do outside a drag. The window stays open, and the +// next drag arms the timer again. +func (state *windowState) paceResize(interval uintptr, arm func(uintptr) error) { + if err := state.rearmResizeTimer(interval, arm); err == nil { + return + } + killTimer.Call(state.window, resizeTimerID) + state.sizingMove = false + state.resizeTimerInterval = 0 + state.invalidatePendingFrame() +} + +func (state *windowState) rearmResizeTimer(interval uintptr, arm func(uintptr) error) error { + interval = max(10, interval) + if !state.sizingMove || state.resizeTimerInterval == interval { + return nil + } + if err := arm(interval); err != nil { + return err + } + state.resizeTimerInterval = interval + return nil +} + +var enumDisplaySettings = user.NewProc("EnumDisplaySettingsW") + +// displayMode is DEVMODEW, including the 16-byte printer/display union. +type displayMode struct { + DeviceName [32]uint16 + SpecVersion, DriverVersion, Size, DriverExtra uint16 + Fields uint32 + Display [4]uint32 + Color, Duplex, YResolution, TTOption, Collate int16 + FormName [32]uint16 + LogPixels uint16 + BitsPerPixel, Width, Height, Flags, Frequency uint32 + ICMMethod, ICMIntent, MediaType, DitherType, Reserved1, Reserved2 uint32 + PanningWidth, PanningHeight uint32 +} + +// resizeInterval is the drag timer interval for the monitor this window is on. +// The display mode is queried only when the window moves to another monitor, or +// after WM_DISPLAYCHANGE clears resizeMonitorInterval. +func (state *windowState) resizeInterval() uintptr { + monitor, _, _ := monitorFromWindow.Call(state.window, 2) + if monitor != state.resizeMonitor || state.resizeMonitorInterval == 0 { + state.resizeMonitor = monitor + state.resizeMonitorInterval = monitorResizeInterval(monitor) + } + return state.resizeMonitorInterval +} + +// monitorResizeInterval queries the current mode of monitor, not the primary +// display. SetTimer has a 10 ms minimum; unavailable display information falls +// back to 60 Hz. +func monitorResizeInterval(monitor uintptr) uintptr { + var info struct { + monitorInfo + Device [32]uint16 + } + info.Size = uint32(unsafe.Sizeof(info)) + mode := displayMode{Size: uint16(unsafe.Sizeof(displayMode{}))} + frequency := uint32(60) + if ok, _, _ := getMonitorInfo.Call(monitor, uintptr(unsafe.Pointer(&info))); ok != 0 { + if ok, _, _ := enumDisplaySettings.Call(uintptr(unsafe.Pointer(&info.Device[0])), uintptr(^uint32(0)), uintptr(unsafe.Pointer(&mode))); ok != 0 && mode.Frequency > 1 { + frequency = mode.Frequency + } + } + return uintptr(max(10, (1000+frequency-1)/frequency)) +} + +func (state *windowState) invalidatePendingFrame() { + if state.window != 0 && !state.sizingMove && (state.redrawRequested || state.paintPending || state.resizePending) && !state.iconic() { + invalidateRect.Call(state.window, 0, 0) + } +} + +// serviceResize consumes one batch. Clear requests before callbacks so updates +// delivered reentrantly survive for the next tick (or paint after modal exit). +func (state *windowState) serviceResize() { + if state.sizing || !state.ready || state.window == 0 || state.iconic() { + return + } + var bounds rect + if ok, _, _ := getClientRect.Call(state.window, uintptr(unsafe.Pointer(&bounds))); ok == 0 || bounds.Right <= 0 || bounds.Bottom <= 0 { + return + } + width, height := int(bounds.Right), int(bounds.Bottom) + layout := state.resizePending || state.renderer.width != width || state.renderer.height != height + if !layout && !state.redrawRequested && !state.paintPending { + return + } + state.sizing = true + defer func() { + state.sizing = false + state.invalidatePendingFrame() + }() + redraw := state.redrawRequested + state.redrawRequested, state.resizePending = false, false + state.paintPending = true + if redraw { + state.redraws.begin() + if state.config.OnRedraw != nil { + frame, err := state.config.OnRedraw() + if state.frameWithText(frame, err, false) != nil || state.window == 0 { + return + } + } + } + if layout && !state.layoutClientSize(width, height) { + return + } + if state.window == 0 || !state.ready { + return + } + // Validate before Present/FramePresented: callbacks may invalidate another frame. + validateRect.Call(state.window, 0) + if err := state.presentImmediate(width, height); err != nil { + state.fail(err) + } else { + state.scheduleTrim() + } +} + +// presentClientSize handles synchronous, non-modal size changes. +func (state *windowState) presentClientSize(width, height int) { + if state.sizing { + return + } + state.sizing = true + defer func() { + state.sizing = false + state.invalidatePendingFrame() + }() + state.resizePending = false + state.paintPending = true + if !state.layoutClientSize(width, height) { + return + } + if state.ready && state.window != 0 { + validateRect.Call(state.window, 0) + if err := state.presentImmediate(width, height); err != nil { + state.fail(err) + } else { + state.scheduleTrim() + } + } +} + +func (state *windowState) layoutClientSize(width, height int) bool { + if state.config.OnResize != nil { + state.resizeEvents++ + frame, err := state.config.OnResize(state.logicalSize(width, height)) + if err := state.frameWithText(frame, err, false); err != nil || state.window == 0 { + return false + } + } + state.reportFrame() + if state.web != nil { + state.web.layoutAll(true) + } + return state.window != 0 +} + // logicalSize is a client size of width by height device pixels in logical pixels, with // the display scale it was divided by. func (state *windowState) logicalSize(width, height int) platform.Size { @@ -994,7 +1200,7 @@ func (state *windowState) frameWithTextAndCancel(frame platform.Frame, err error var dirty bool frame, dirty, err = state.prepareFrameWithCancel(frame, nativeVisualChanged, cancelNative) if err == errSupersededTextFrame { - if state.window != 0 { + if state.window != 0 && !state.paintPending && !state.sizing && !state.resizePending { state.framePresented() } return nil @@ -1009,10 +1215,9 @@ func (state *windowState) frameWithTextAndCancel(frame platform.Frame, err error } if err == nil { if dirty { + state.paintPending = true invalidateRect.Call(state.window, 0, 0) - } else { - // Nothing reached the screen, so no WM_PAINT will report this - // frame as presented; the runtime can still ask for the next one. + } else if !state.paintPending && !state.sizing && !state.resizePending { state.framePresented() } } @@ -1037,6 +1242,9 @@ func (state *windowState) frameWithTextAndCancel(frame platform.Frame, err error func (state *windowState) destroyed(window uintptr) { // Native teardown can reenter the dispatcher; retire text callbacks first. state.ready = false + killTimer.Call(window, resizeTimerID) + state.sizingMove = false + state.resizeTimerInterval = 0 state.closeText() forgetClipboardListener(window) released := false From 04b5b5c5c292d9644c888971c5d48551ef9aef70 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 00:29:49 +0800 Subject: [PATCH 09/23] feat(ui): add TextAreaID for a text area the application names --- ui/elements.go | 20 ++++++++++++++++++++ ui/page_test.go | 22 ++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/ui/elements.go b/ui/elements.go index c66e4fa9e..3d43de938 100644 --- a/ui/elements.go +++ b/ui/elements.go @@ -333,6 +333,26 @@ func TextArea[T TextValue](c C, value T, label, placeholder string) Box { return b } +// TextAreaID is TextArea for a field the application already names, as TextFieldID is +// for TextField: id is the field's identity in the page's Tree, so an initial focus, +// a window's own routing or a test can address it. Field.Bind gives it an editor the +// application keeps and reads itself. +// +// ui.TextAreaID(c, m.commandID, &m.commandField, "Command", "").Height(120) +func TextAreaID(c C, id gfx.ID, field *Field, label, placeholder string) Box { + if field == nil { + panic("ui: TextAreaID needs a Field") + } + p := c.page + b := c.f.FieldArea(field, id, label, placeholder) + c.f.bindField(b, field) + if p.areaKey == nil { + p.keyRoute, p.areaKey = (*Page).routeKey, (*Field).Key // Up and Down by row + } + p.fields = append(p.fields, fieldEntry{id: id, field: field}) + return b +} + // Popover shows the panel body declares, hanging off anchor, while *open: a press // outside it or Escape sets *open to false (and the press goes on to what is under // the pointer), and a press on the anchor only closes it, so the anchor that toggles diff --git a/ui/page_test.go b/ui/page_test.go index b593f9e7d..2c40df96e 100644 --- a/ui/page_test.go +++ b/ui/page_test.go @@ -588,3 +588,25 @@ func TestSelectIconChoosesAnOption(t *testing.T) { t.Fatalf("chose %+v, want %+v", chosen, locales[2]) } } + +// A TextAreaID is addressed by the identity the application gave it, and edits its +// Field in rows like a TextArea. +func TestPageTextAreaID(t *testing.T) { + var notes ui.Field + id := gfx.Item(41) + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.TextAreaID(c, id, ¬es, "Notes", "").Width(300).Height(120) + }) + }) + d.click("Notes") + d.typeText("one") + d.key(gfx.KeyEnter) + d.typeText("two") + if notes.Text() != "one\ntwo" { + t.Fatalf("text %q", notes.Text()) + } + if d.driver.Snapshot().Focused != id { + t.Fatalf("focused %v, want the identity the application gave it", d.driver.Snapshot().Focused) + } +} From 38f43566d3a986addbcdf01b4039b1ef6ba9208a Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 00:31:15 +0800 Subject: [PATCH 10/23] test(ui): cover a context menu named by a zero-size slot --- ui/menu_test.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/ui/menu_test.go b/ui/menu_test.go index 14fbdade0..72aa8bb18 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -581,3 +581,26 @@ func TestContextMenuAtTakesTheArrowsFromTheFocusedControl(t *testing.T) { t.Fatalf("connected %q, open %v: the arrows did not reach the menu", m.connected, m.open) } } + +func TestContextMenuAtNamedByAZeroSizeSlotTakesTheArrows(t *testing.T) { + m := &contextModel{hosts: []string{"alpha"}} + d := openPage(t, func(c ui.C) { + ui.PopupLayer(c, 600) + anchor := ui.Slot(c).Absolute().Left(100).Top(100).Size(0, 0).HitWith(ui.ID(c), "", gfx.HitOptions{SkipFocus: true, SkipTab: true}) + ui.ContextMenuAt(c, anchor, &m.open, gfx.Point{X: 100, Y: 100}, func(items *ui.MenuItems) { + items.RowHeight(24) + items.Item("One") + if items.Item("Two").Clicked() { + m.connected = "two" + } + }) + }) + m.open = true + d.repaint() + d.key(gfx.KeyDown) + d.key(gfx.KeyDown) + d.key(gfx.KeyEnter) + if m.connected != "two" || m.open { + t.Fatalf("connected %q, open %v: the arrows did not reach the menu", m.connected, m.open) + } +} From 46d6eefcab0d06c6765bb0c3281075330e88f3fe Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 00:39:45 +0800 Subject: [PATCH 11/23] feat(ui): add Checkbox.Mixed for a select-all over some chosen rows --- ui/caption.go | 15 +++++++++++++++ ui/checkbox_test.go | 33 +++++++++++++++++++++++++++++++++ ui/frame.go | 1 + ui/paint.go | 3 +++ 4 files changed, 52 insertions(+) create mode 100644 ui/checkbox_test.go diff --git a/ui/caption.go b/ui/caption.go index 0f1aa1a9a..e31782d9a 100644 --- a/ui/caption.go +++ b/ui/caption.go @@ -12,6 +12,21 @@ import ( // elements it does nothing. // // f.Checkbox(syncID, m.sync).Caption("Sync over SSH") +// Mixed paints a Checkbox as neither on nor off, a dash in a filled box: the select-all of a +// list of which only some rows are chosen. Declare it from the rows' state each paint; a +// press still flips the bound value, so the application decides what the next state is. +// It has no effect on any other element. +func (b Box) Mixed(mixed bool) Box { + if n := b.n(); n.kind == kindCheckbox { + if mixed { + n.flags |= flagMixed + } else { + n.flags &^= flagMixed + } + } + return b +} + func (b Box) Caption(text string) Box { n := b.n() if n.kind != kindCheckbox && n.kind != kindSwitch { diff --git a/ui/checkbox_test.go b/ui/checkbox_test.go new file mode 100644 index 000000000..7152bee33 --- /dev/null +++ b/ui/checkbox_test.go @@ -0,0 +1,33 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +// A mixed Checkbox paints the dash of components.Checkbox.Indeterminate: its fill is the +// checked fill, not the unchecked one, and a press still reaches the application. +func TestCheckboxMixedPaintsTheDash(t *testing.T) { + fill := func(mixed bool) (primitives int) { + on := false + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + ui.Checkbox(c, &on, "All").Mixed(mixed) + }) + }) + for _, p := range d.driver.Snapshot().Primitives { + if p.Kind == app.RectanglePrimitive && p.Color == pageTheme.Primary { + primitives++ + } + } + return primitives + } + if fill(false) != 0 { + t.Fatal("an unchecked box has a primary fill") + } + if fill(true) == 0 { + t.Fatal("a mixed box shows no primary fill") + } +} diff --git a/ui/frame.go b/ui/frame.go index 4172ac5c5..2d5374ea4 100644 --- a/ui/frame.go +++ b/ui/frame.go @@ -104,6 +104,7 @@ const ( flagPopover // a Popover's root: painted with components.Popover's dismiss, focus scope and Escape around its children flagDrawer // a Drawer's root: painted by components.Drawer around its children flagLabelFor // the element is a label of the control its identity names (LabelFor) + flagMixed // a Checkbox that is neither on nor off: some of what it stands for is chosen ) // node is one element of the page. Fields are plain values so a node is reused diff --git a/ui/paint.go b/ui/paint.go index 1d5aeac67..4b62c68f7 100644 --- a/ui/paint.go +++ b/ui/paint.go @@ -184,6 +184,9 @@ func (f *frame) paintControl(n *node, r Rect) { f.captionFn(f, n, bounds) } checkbox := components.BeginCheckbox(canvas, f.theme, n.id, bounds, n.flags&flagChecked != 0) + if n.flags&flagMixed != 0 { + checkbox = checkbox.Indeterminate() + } if f.styles != nil && f.styles.Checkbox != nil { checkbox = checkbox.Recipe(f.styles.Checkbox) } From 117aef5e973f35331b47199ed6f66bde4cc94941 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:41:37 +0800 Subject: [PATCH 12/23] linux: keep Wayland keyboard and IME after content clicks --- .github/workflows/text-input.yml | 14 +- internal/ibus/testdata/native-fcitx-daemon.sh | 10 + internal/ibus/testdata/wayland-seat.py | 259 ++++++++ internal/platform/linux/gtk_app_linux.go | 18 +- internal/platform/linux/gtk_input_linux.go | 78 ++- internal/platform/linux/gtk_library_linux.go | 138 ++-- .../gtk_native_widget_focus_linux_test.go | 527 +++++++++++++++ ...ayland_attach_failure_native_linux_test.go | 90 +++ .../linux/gtk_wayland_attr_linux_test.go | 39 ++ .../gtk_wayland_keyboard_native_linux_test.go | 613 ++++++++++++++++++ internal/platform/linux/gtk_wayland_linux.go | 77 ++- .../gtk_wayland_regions_native_linux_test.go | 508 +++++++++++++++ internal/platform/linux/gtk_window_linux.go | 50 +- 13 files changed, 2344 insertions(+), 77 deletions(-) create mode 100644 internal/ibus/testdata/wayland-seat.py create mode 100644 internal/platform/linux/gtk_native_widget_focus_linux_test.go create mode 100644 internal/platform/linux/gtk_wayland_attach_failure_native_linux_test.go create mode 100644 internal/platform/linux/gtk_wayland_attr_linux_test.go create mode 100644 internal/platform/linux/gtk_wayland_keyboard_native_linux_test.go create mode 100644 internal/platform/linux/gtk_wayland_regions_native_linux_test.go diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 80ce917ed..55face264 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -133,8 +133,8 @@ jobs: if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y --no-install-recommends libgtk-3-0t64 xvfb xauth dbus-x11 ibus ibus-libpinyin ibus-hangul python3-gi gir1.2-ibus-1.0 gir1.2-gtk-3.0 libglib2.0-bin dconf-cli fcitx5 fcitx5-pinyin fcitx5-hangul fcitx5-frontend-gtk3 weston - dpkg-query -W libgtk-3-0t64 xvfb xauth dbus-x11 ibus ibus-libpinyin ibus-hangul python3-gi gir1.2-ibus-1.0 gir1.2-gtk-3.0 libglib2.0-bin dconf-cli fcitx5 fcitx5-pinyin fcitx5-hangul fcitx5-frontend-gtk3 weston + sudo apt-get install -y --no-install-recommends libgtk-3-0t64 xvfb xauth dbus-x11 ibus ibus-libpinyin ibus-hangul python3-gi gir1.2-ibus-1.0 gir1.2-gtk-3.0 libglib2.0-bin dconf-cli fcitx5 fcitx5-pinyin fcitx5-hangul fcitx5-frontend-gtk3 weston libxtst6 at-spi2-core + dpkg-query -W libgtk-3-0t64 xvfb xauth dbus-x11 ibus ibus-libpinyin ibus-hangul python3-gi gir1.2-ibus-1.0 gir1.2-gtk-3.0 libglib2.0-bin dconf-cli fcitx5 fcitx5-pinyin fcitx5-hangul fcitx5-frontend-gtk3 weston libxtst6 at-spi2-core - name: IBus native engine lifecycle if: runner.os == 'Linux' run: | @@ -161,6 +161,16 @@ jobs: xvfb-run -a env VIVA_FCITX_ENGINE="$engine" VIVA_FCITX_REFERENCE=1 VIVA_FCITX_GTK_REFERENCE=1 VIVA_GTK_IME_NATIVE=1 G_DEBUG=fatal-criticals VIVA_FCITX_TEST_BINARY="$RUNNER_TEMP/viva-ibus-frontend.test" VIVA_IBUS_TEST_RUN='^Test(NativeIBus(Frontend|OwnerReactivation|FactoryDeclinedShortcut|UnsupportedModeRetirement)|GTKNativeFcitx(Composition|WindowClose))$' sh internal/ibus/testdata/native-fcitx-service.sh "$backend" done done + - name: GTK real seat keyboard and Fcitx composition + if: runner.os == 'Linux' + run: | + for backend in x11 wayland; do + tests='^TestGTKNativeSeatKeyboardAfterContentClick$' + if [ "$backend" = wayland ]; then + tests='^Test(GTKNative(SeatKeyboardAfterContentClick|WaylandSeatHideShow|WaylandWidgetExternalFocus|WaylandAttachFailure|WaylandInputRegions)|GTKWaylandWindowAttrLP64Layout)$' + fi + xvfb-run -a -s '-screen 0 800x600x24' env VIVA_GTK_SEAT_NATIVE=1 VIVA_GTK_SEAT_REMAP=1 VIVA_GTK_NATIVE_WIDGET_FOCUS=1 VIVA_GTK_ATTACH_NATIVE=1 VIVA_GTK_REGION_NATIVE=1 VIVA_GTK_IME_NATIVE=1 VIVA_FCITX_ENGINE=pinyin G_DEBUG=fatal-criticals VIVA_FCITX_TEST_BINARY="$RUNNER_TEMP/viva-ibus-frontend.test" VIVA_IBUS_TEST_RUN="$tests" sh internal/ibus/testdata/native-fcitx-service.sh "$backend" + done - name: Linux text callback ordering if: runner.os == 'Linux' run: go test -race ./internal/platform/linux -run '^TestLinuxTextCallback' -count=1 -timeout=90s diff --git a/internal/ibus/testdata/native-fcitx-daemon.sh b/internal/ibus/testdata/native-fcitx-daemon.sh index a951abe53..e7b2c797f 100644 --- a/internal/ibus/testdata/native-fcitx-daemon.sh +++ b/internal/ibus/testdata/native-fcitx-daemon.sh @@ -34,6 +34,16 @@ if [ "$VIVA_FCITX_BACKEND" = wayland ]; then else export GDK_BACKEND=x11 fi +if [ "${VIVA_GTK_SEAT_NATIVE:-0}" = 1 ]; then + VIVA_GTK_SEAT_DRIVER="$fixture_dir/wayland-seat.py" + export VIVA_GTK_SEAT_DRIVER VIVA_ACCESSIBILITY=1 + if [ "$VIVA_FCITX_BACKEND" = wayland ]; then + WESTON_X11_WINDOW_ID=$(awk '/x11 output .* window id / { print $NF; exit }' "$task_dir/weston.log") + case "$WESTON_X11_WINDOW_ID" in ''|*[!0-9]*) echo 'Weston X11 output window missing' >&2; exit 1 ;; esac + export WESTON_X11_WINDOW_ID + fi + /usr/bin/python3 "$fixture_dir/reference-client.py" --activation-environment +fi export IBUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS export IBUS_ADDRESS_FILE=$task_dir/ibus-address # This fixture uses GTK/IBus over D-Bus, not Weston's privileged IM binding. diff --git a/internal/ibus/testdata/wayland-seat.py b/internal/ibus/testdata/wayland-seat.py new file mode 100644 index 000000000..1cfbb907b --- /dev/null +++ b/internal/ibus/testdata/wayland-seat.py @@ -0,0 +1,259 @@ +#!/usr/bin/python3 +"""Drive a native GTK test through XTest and its real X11/Wayland seat.""" + +import ctypes +import ctypes.util +import json +import os +import sys +import time +import traceback + +import gi + +gi.require_version("Gio", "2.0") +gi.require_version("GLib", "2.0") +from gi.repository import Gio, GLib + + +ACCESSIBLE = "org.a11y.atspi.Accessible" +COMPONENT = "org.a11y.atspi.Component" +PROPERTIES = "org.freedesktop.DBus.Properties" +ROOT = "/org/a11y/atspi/accessible/root" + + +def call(bus, destination, path, interface, member, arguments=None): + return bus.call_sync(destination, path, interface, member, arguments, None, + Gio.DBusCallFlags.NONE, 1500, None).unpack() + + +class Seat: + def __init__(self): + self.xlib = ctypes.CDLL(ctypes.util.find_library("X11")) + self.xtst = ctypes.CDLL(ctypes.util.find_library("Xtst")) + x = self.xlib + x.XOpenDisplay.argtypes = [ctypes.c_char_p] + x.XOpenDisplay.restype = ctypes.c_void_p + x.XDefaultRootWindow.argtypes = [ctypes.c_void_p] + x.XDefaultRootWindow.restype = ctypes.c_ulong + x.XQueryTree.argtypes = [ctypes.c_void_p, ctypes.c_ulong, + ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_ulong), + ctypes.POINTER(ctypes.POINTER(ctypes.c_ulong)), ctypes.POINTER(ctypes.c_uint)] + x.XFetchName.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_void_p)] + x.XFree.argtypes = [ctypes.c_void_p] + x.XSetInputFocus.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong] + x.XGetInputFocus.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_int)] + x.XStringToKeysym.argtypes = [ctypes.c_char_p] + x.XStringToKeysym.restype = ctypes.c_ulong + x.XKeysymToKeycode.argtypes = [ctypes.c_void_p, ctypes.c_ulong] + x.XKeysymToKeycode.restype = ctypes.c_ubyte + x.XSync.argtypes = [ctypes.c_void_p, ctypes.c_int] + x.XCloseDisplay.argtypes = [ctypes.c_void_p] + self.xtst.XTestQueryExtension.argtypes = [ctypes.c_void_p, *([ctypes.POINTER(ctypes.c_int)] * 4)] + self.xtst.XTestFakeMotionEvent.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_ulong] + self.xtst.XTestFakeButtonEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong] + self.xtst.XTestFakeKeyEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_ulong] + self.display = x.XOpenDisplay(None) + if not self.display: + raise RuntimeError("XTest cannot open the private Xvfb display") + extension = [ctypes.c_int() for _ in range(4)] + if not self.xtst.XTestQueryExtension(self.display, *(ctypes.byref(item) for item in extension)): + raise RuntimeError("XTest extension is missing") + self.session = Gio.bus_get_sync(Gio.BusType.SESSION, None) + address = call(self.session, "org.a11y.Bus", "/org/a11y/bus", "org.a11y.Bus", "GetAddress")[0] + flags = Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION + self.accessible = Gio.DBusConnection.new_for_address_sync(address, flags, None, None) + self.editor = None + self.window = None + + def children(self, reference): + return call(self.accessible, reference[0], reference[1], ACCESSIBLE, "GetChildren")[0] + + def name(self, reference): + value = call(self.accessible, reference[0], reference[1], PROPERTIES, "Get", + GLib.Variant("(ss)", (ACCESSIBLE, "Name")))[0] + return value.unpack() if isinstance(value, GLib.Variant) else value + + def find_node(self, pid, label): + refs = self.children(("org.a11y.atspi.Registry", ROOT)) + applications = [] + for reference in refs: + try: + owner = call(self.accessible, "org.freedesktop.DBus", "/org/freedesktop/DBus", + "org.freedesktop.DBus", "GetConnectionUnixProcessID", + GLib.Variant("(s)", (reference[0],)))[0] + if owner == pid: + applications.append(tuple(reference)) + except GLib.Error: + continue + if len(applications) != 1: + return None + queue, seen, nodes = applications, set(), [] + while queue: + reference = tuple(queue.pop(0)) + if reference in seen or reference[1].endswith("/null"): + continue + seen.add(reference) + if len(seen) > 100: + raise RuntimeError("AT-SPI tree exceeds the native probe bound") + if self.name(reference) == label: + nodes.append(reference) + queue.extend(self.children(reference)) + if len(nodes) > 1: + raise RuntimeError("multiple %s nodes for the test PID" % label) + return nodes[0] if nodes else None + + def x11_windows(self): + x = self.xlib + root, parent = ctypes.c_ulong(), ctypes.c_ulong() + children, count = ctypes.POINTER(ctypes.c_ulong)(), ctypes.c_uint() + if not x.XQueryTree(self.display, x.XDefaultRootWindow(self.display), + ctypes.byref(root), ctypes.byref(parent), + ctypes.byref(children), ctypes.byref(count)): + raise RuntimeError("XQueryTree failed") + names = [] + try: + for index in range(count.value): + title = ctypes.c_void_p() + value = "" + if x.XFetchName(self.display, children[index], ctypes.byref(title)) and title.value: + value = ctypes.string_at(title.value).decode("utf-8", "replace") + x.XFree(title) + names.append((children[index], value)) + finally: + if children: + x.XFree(children) + return names + + def bind(self, pid, backend): + deadline = time.monotonic() + 8 + while time.monotonic() < deadline: + try: + editor = self.find_node(pid, "Seat editor") + windows = self.x11_windows() + if backend == "wayland": + target = int(os.environ["WESTON_X11_WINDOW_ID"]) + matches = [wid for wid, _ in windows if wid == target] + else: + matches = [wid for wid, name in windows if name == "Viva seat keyboard probe"] + if editor is not None and len(matches) == 1: + rect = call(self.accessible, editor[0], editor[1], COMPONENT, "GetExtents", + GLib.Variant("(u)", (0,)))[0] + x, y, width, height = rect + if width <= 0 or height <= 0 or x < 0 or y < 0 or x + width > 800 or y + height > 600: + raise RuntimeError("editor is outside the private 800x600 Xvfb viewport: %r" % (rect,)) + self.editor, self.window = editor, matches[0] + return {"window": self.window, "editor": list(rect)} + if len(matches) > 1: + raise RuntimeError("multiple X11 windows match the native probe") + except GLib.Error: + pass + time.sleep(0.025) + raise RuntimeError("native editor or matching X11/Weston window did not appear") + + def focus(self): + x = self.xlib + x.XSetInputFocus(self.display, self.window, 1, 0) + x.XSync(self.display, False) + focused, revert = ctypes.c_ulong(), ctypes.c_int() + if not x.XGetInputFocus(self.display, ctypes.byref(focused), ctypes.byref(revert)) or focused.value != self.window: + raise RuntimeError("outer X11 window did not acquire input focus") + return {"window": focused.value} + + def grab(self): + accepted = call(self.accessible, self.editor[0], self.editor[1], COMPONENT, "GrabFocus")[0] + if not accepted: + raise RuntimeError("AT-SPI editor rejected GrabFocus") + return {"accepted": True} + + def click(self, reference=None): + reference = reference or self.editor + x, y, width, height = call(self.accessible, reference[0], reference[1], COMPONENT, + "GetExtents", GLib.Variant("(u)", (0,)))[0] + if width <= 0 or height <= 0 or x < 0 or y < 0 or x + width > 800 or y + height > 600: + raise RuntimeError("native click target is outside the private viewport") + return self.click_at(x + width // 2, y + height // 2) + + def move(self, x, y): + if not 0 <= x < 800 or not 0 <= y < 600: + raise RuntimeError("pointer position is outside the private viewport") + if not self.xtst.XTestFakeMotionEvent(self.display, -1, x, y, 0): + raise RuntimeError("XTest pointer motion failed") + self.xlib.XSync(self.display, False) + return {"point": [x, y]} + + def click_at(self, x, y): + self.move(x, y) + for pressed in (True, False): + if not self.xtst.XTestFakeButtonEvent(self.display, 1, pressed, 0): + raise RuntimeError("XTest pointer button failed") + self.xlib.XSync(self.display, False) + return {"point": [x, y]} + + def probe_switch(self, pid): + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + try: + target = self.find_node(pid, "Switch window") + if target is not None: + rect = call(self.accessible, target[0], target[1], COMPONENT, "GetExtents", + GLib.Variant("(u)", (0,)))[0] + if rect[2] > 0 and rect[3] > 0: + return {"node": "Switch window", "extent": list(rect)} + except GLib.Error: + pass + time.sleep(0.025) + raise RuntimeError("Switch window AT-SPI node did not become visible") + + def key(self, symbol, down): + keysym = self.xlib.XStringToKeysym(symbol.encode("ascii")) + code = self.xlib.XKeysymToKeycode(self.display, keysym) + if not keysym or not code or not self.xtst.XTestFakeKeyEvent(self.display, code, down, 0): + raise RuntimeError("XTest key failed: %r" % symbol) + self.xlib.XSync(self.display, False) + return {"code": code} + + def close(self): + self.accessible.close_sync(None) + self.xlib.XCloseDisplay(self.display) + + +def main(): + seat = Seat() + try: + for line in sys.stdin: + command = json.loads(line) + operation = command["op"] + if operation == "bind": + result = seat.bind(int(command["pid"]), command["backend"]) + elif operation == "focus": + result = seat.focus() + elif operation == "grab": + result = seat.grab() + elif operation == "click": + result = seat.click() + elif operation == "probe-switch": + result = seat.probe_switch(int(command["pid"])) + elif operation == "move": + result = seat.move(int(command["x"]), int(command["y"])) + elif operation == "click-at": + result = seat.click_at(int(command["x"]), int(command["y"])) + elif operation in ("down", "up"): + result = seat.key(command["key"], operation == "down") + elif operation == "quit": + print(json.dumps({"ok": True}), flush=True) + return + else: + raise RuntimeError("unknown seat command: %r" % operation) + print(json.dumps({"ok": True, **result}), flush=True) + finally: + seat.close() + + +if __name__ == "__main__": + try: + main() + except Exception as error: + traceback.print_exc(file=sys.stderr) + print(json.dumps({"ok": False, "error": str(error)}), flush=True) + sys.exit(1) diff --git a/internal/platform/linux/gtk_app_linux.go b/internal/platform/linux/gtk_app_linux.go index 4e663e97a..80bdc4572 100644 --- a/internal/platform/linux/gtk_app_linux.go +++ b/internal/platform/linux/gtk_app_linux.go @@ -36,6 +36,8 @@ type gtkApplication struct { wayland bool started bool stopping bool + + mainRunning bool // mainThread is the thread that runs the loop, which is where GTK may be called. mainThread int // active is the window the keyboard or the pointer was last in. @@ -113,8 +115,10 @@ func RunGTKApplication(start platform.ApplicationStart) error { application.destroyAll() return err } - if len(application.windows) > 0 { + if len(application.windows) > 0 && !application.stopping { + application.mainRunning = true g.main() + application.mainRunning = false } application.destroyAll() return application.firstErr @@ -195,7 +199,9 @@ func (a *gtkApplication) fail(err error) { func (a *gtkApplication) stop() { if !a.stopping { a.stopping = true - a.g.mainQuit() + if a.mainRunning { + a.g.mainQuit() + } } } @@ -312,7 +318,7 @@ func typeNameOf(g *gtkLibrary, object uintptr) string { // frees a callback and allows a fixed number, so a window must not make its own. The window a call // is for travels in the data pointer, as its id. type gtkCallbacks struct { - task, descriptor, settings, dragMotion, dragLeave, dragDrop, dragData, event, draw, allocate, destroy, deleteEvent, mapped, unmapped, commit, preeditStart, preedit, preeditEnd, surrounding, deleteSurrounding, retireIME, releaseIME, redraw, webMessage, webLoad, webScheme, webDecide, webCreate, webDownload, webDestination uintptr + task, descriptor, settings, dragMotion, dragLeave, dragDrop, dragData, event, capturePress, draw, allocate, destroy, deleteEvent, mapped, unmapped, commit, preeditStart, preedit, preeditEnd, surrounding, deleteSurrounding, retireIME, releaseIME, redraw, webMessage, webLoad, webScheme, webDecide, webCreate, webDownload, webDestination uintptr } var ( @@ -386,6 +392,12 @@ func callbacks() *gtkCallbacks { } return 0 }), + capturePress: purego.NewCallback(func(gesture, sequence, id uintptr) uintptr { + if w := gtkWindowByID(id); w != nil && w.wl != nil && w.wl.s.focus == w.wl { + w.g.gestureSetState(gesture, 1) // GTK_EVENT_SEQUENCE_CLAIMED + } + return 0 + }), draw: purego.NewCallback(func(widget, cr, id uintptr) uintptr { if w := gtkWindowByID(id); w != nil { w.draw(widget, cr) diff --git a/internal/platform/linux/gtk_input_linux.go b/internal/platform/linux/gtk_input_linux.go index 57c1b6062..b34630c7a 100644 --- a/internal/platform/linux/gtk_input_linux.go +++ b/internal/platform/linux/gtk_input_linux.go @@ -45,6 +45,12 @@ func (w *gtkWindow) handleEvent(widget, event uintptr) uintptr { if w.closed { return 0 } + if w.wl != nil && w.wl.gdkWindow != 0 && *(*uintptr)(unsafe.Add(unsafePointer(event), 8)) == w.wl.gdkWindow { + switch eventType(event) { + case gdkMotionNotify, gdkEnterNotify, gdkLeaveNotify, gdkButtonPress, gdkButtonRelease, gdk2ButtonPress, gdk3ButtonPress, gdkScroll: + return 1 // Viva's wl_pointer delivers this surface's pointer events. + } + } switch eventType(event) { case gdkMotionNotify: e := (*gdkEventMotion)(unsafePointer(event)) @@ -76,10 +82,25 @@ func (w *gtkWindow) handleEvent(widget, event uintptr) uintptr { return w.keyEvent(event) case gdkFocusChange: in := (*gdkEventFocus)(unsafePointer(event)).In != 0 + if widget == w.area { + // The drawing area gets focus events only on Wayland, where it is the content subsurface. + // It is never a page, so the event must not fall through to the web view branch below. + if w.wl != nil && w.wl.gdkWindow != 0 { + w.waylandFocusChanged(in) + } + return 1 + } if widget != w.toplevel { + if in { + w.focusSerial++ // a native view has taken focus within this window + } w.webFocusChanged(widget, in) return 0 } + if w.wl != nil && w.wl.gdkWindow != 0 { + w.waylandFocusChanged(in) + return 0 + } w.focusChanged(in) case gdkWindowState: w.stateChanged((*gdkEventWindowState)(unsafePointer(event))) @@ -89,6 +110,22 @@ func (w *gtkWindow) handleEvent(widget, event uintptr) uintptr { return 0 } +// GDK sends a focus-out for the parent before the focus-in for its subsurface. +// Defer losing the window's logical focus until that transfer has completed. +func (w *gtkWindow) waylandFocusChanged(in bool) { + w.focusSerial++ + serial := w.focusSerial + if in { + w.focusChanged(true) + return + } + w.app.enqueue(func() { + if !w.closed && serial == w.focusSerial && w.webFocus == 0 { + w.focusChanged(false) + } + }) +} + // logical converts a position in widget units to logical pixels. func (w *gtkWindow) logical(x, y float64) (float32, float32) { return float32(x) / w.ratio, float32(y) / w.ratio @@ -152,7 +189,14 @@ func (w *gtkWindow) buttonAt(x, y, screenX, screenY float32, gdkButton uint32, d if button == gfx.PointerButtonNone { return } + reclaimingNative := false if down { + reclaimingNative = w.wl != nil && (w.nativeKeys || w.webFocus != 0) + if w.wl != nil && w.g.windowGetFocus(w.toplevel) != 0 { + // GTK can keep a native widget as the window's stored focus after the + // window loses compositor focus, even after its focus-out signal ran. + w.g.windowSetFocus(w.toplevel, 0) + } w.takeKeys() w.pointer.clicks.Interval, w.pointer.clicks.Distance = clickTimingGTK(w) w.pointer.clicks.Press(time.Duration(eventTime)*time.Millisecond, uint8(gdkButton), x, y) @@ -162,6 +206,22 @@ func (w *gtkWindow) buttonAt(x, y, screenX, screenY float32, gdkButton uint32, d kind = platform.PointerDown } w.deliverPointer(platform.PointerEvent{Kind: kind, Button: button, Modifiers: modifiers, X: x, Y: y, ScreenX: screenX, ScreenY: screenY, ClickCount: w.pointer.clicks.Current()}) + if reclaimingNative && !w.closed && w.ime != nil { + ime, context := w.ime, w.ime.ctx + w.reclaimIME(ime, context) + } +} + +func (w *gtkWindow) reclaimIME(ime *gtkIME, context uintptr) { + ready := func() bool { + return !w.closed && w.wl != nil && w.wl.s.focus == w.wl && !w.nativeKeys && w.focused && w.ime == ime && ime.ctx == context + } + if ready() && !ime.composing() { + ime.setFocused(false) + if ready() && !ime.composing() { + ime.setFocused(true) + } + } } // deliverPointer gives an event to the application, then to the text field under it. @@ -326,6 +386,19 @@ func (w *gtkWindow) focusChanged(focused bool) { if w.focused == focused { return } + w.setKeyboard(focused) + if !focused && w.config.WindowMode == platform.WindowPanel && w.g.widgetIsVisible(w.toplevel) != 0 { + // A panel is a transient popup: losing the focus while it is on screen dismisses it. The focus + // that goes when Hide unmaps it is not the user leaving, and Show must bring the panel back. + panelDismissedAt.Store(monotonicNow()) + w.destroy() + } +} + +// setKeyboard records the keyboard going to the window or away from it, and tells what follows from +// it. Losing the keyboard is not always the user leaving: Hide takes it away too, and a panel that +// is hidden must survive until Show. +func (w *gtkWindow) setKeyboard(focused bool) { w.focused = focused w.app.atspiActive(w, focused) if focused { @@ -346,11 +419,6 @@ func (w *gtkWindow) focusChanged(focused bool) { frame, err := w.config.OnFocusLost() w.present(frame, err) } - if w.config.WindowMode == platform.WindowPanel { - // A panel is a transient popup: losing the focus dismisses it. - panelDismissedAt.Store(monotonicNow()) - w.destroy() - } } // stateChanged follows the window being minimized and maximized. diff --git a/internal/platform/linux/gtk_library_linux.go b/internal/platform/linux/gtk_library_linux.go index afae981c0..5872ba19b 100644 --- a/internal/platform/linux/gtk_library_linux.go +++ b/internal/platform/linux/gtk_library_linux.go @@ -40,55 +40,63 @@ type gtkLibrary struct { unixFDAdd func(fd int32, condition uint32, function, data uintptr) uint32 // GTK: application and windows. - initCheck func(argc *int32, argv uintptr) int32 - main func() - mainQuit func() - windowNew func(kind int32) uintptr - windowSetTitle func(window uintptr, title *byte) - windowSetDefault func(window uintptr, width, height int32) - windowResize func(window uintptr, width, height int32) - windowMove func(window uintptr, x, y int32) - windowSetDecorated func(window uintptr, decorated int32) - windowSetGeometry func(window, widget uintptr, geometry *gdkGeometry, mask uint32) - windowSetTypeHint func(window uintptr, hint int32) - windowSkipTaskbar func(window uintptr, skip int32) - windowKeepAbove func(window uintptr, keep int32) - windowAcceptFocus func(window uintptr, accept int32) - windowSetWMClass func(window uintptr, name, class *byte) - windowSetIconList func(window, list uintptr) - windowIconify func(window uintptr) - windowDeiconify func(window uintptr) - windowMaximize func(window uintptr) - windowUnmaximize func(window uintptr) - windowIsMaximized func(window uintptr) int32 - windowFullscreen func(window uintptr) - windowUnfullscreen func(window uintptr) - windowPresent func(window uintptr) - windowGetPosition func(window uintptr, x, y *int32) - windowGetSize func(window uintptr, width, height *int32) - windowBeginMove func(window uintptr, button, rootX, rootY int32, timestamp uint32) - windowBeginResize func(window uintptr, edge, button, rootX, rootY int32, timestamp uint32) - windowSetFocus func(window, widget uintptr) - windowSetHasFrame func(window uintptr, frame int32) - windowSetTransient func(window, parent uintptr) - windowSetAppPaint func(widget uintptr, paintable int32) - windowSetVisual func(widget, visual uintptr) - windowSetIcon func(window, pixbuf uintptr) - windowSetTitlebar func(window, titlebar uintptr) - windowGetModalHint func(window uintptr) int32 - widgetShow func(widget uintptr) - widgetShowAll func(widget uintptr) - widgetHide func(widget uintptr) - widgetDestroy func(widget uintptr) - widgetRealize func(widget uintptr) - widgetQueueDraw func(widget uintptr) - widgetQueueDrawArea func(widget uintptr, x, y, width, height int32) - widgetGetWindow func(widget uintptr) uintptr - widgetAddEvents func(widget uintptr, events int32) - widgetSetEvents func(widget uintptr, events int32) - widgetSetSize func(widget uintptr, width, height int32) - widgetSetCanFocus func(widget uintptr, can int32) - widgetGrabFocus func(widget uintptr) + initCheck func(argc *int32, argv uintptr) int32 + main func() + mainQuit func() + windowNew func(kind int32) uintptr + windowSetTitle func(window uintptr, title *byte) + windowSetDefault func(window uintptr, width, height int32) + windowResize func(window uintptr, width, height int32) + windowMove func(window uintptr, x, y int32) + windowSetDecorated func(window uintptr, decorated int32) + windowSetGeometry func(window, widget uintptr, geometry *gdkGeometry, mask uint32) + windowSetTypeHint func(window uintptr, hint int32) + windowSkipTaskbar func(window uintptr, skip int32) + windowKeepAbove func(window uintptr, keep int32) + windowAcceptFocus func(window uintptr, accept int32) + windowSetWMClass func(window uintptr, name, class *byte) + windowSetIconList func(window, list uintptr) + windowIconify func(window uintptr) + windowDeiconify func(window uintptr) + windowMaximize func(window uintptr) + windowUnmaximize func(window uintptr) + windowIsMaximized func(window uintptr) int32 + windowFullscreen func(window uintptr) + windowUnfullscreen func(window uintptr) + windowPresent func(window uintptr) + windowGetPosition func(window uintptr, x, y *int32) + windowGetSize func(window uintptr, width, height *int32) + windowBeginMove func(window uintptr, button, rootX, rootY int32, timestamp uint32) + windowBeginResize func(window uintptr, edge, button, rootX, rootY int32, timestamp uint32) + windowSetFocus func(window, widget uintptr) + windowGetFocus func(window uintptr) uintptr + windowSetHasFrame func(window uintptr, frame int32) + windowSetTransient func(window, parent uintptr) + windowSetAppPaint func(widget uintptr, paintable int32) + windowSetVisual func(widget, visual uintptr) + windowSetIcon func(window, pixbuf uintptr) + windowSetTitlebar func(window, titlebar uintptr) + windowGetModalHint func(window uintptr) int32 + widgetShow func(widget uintptr) + widgetShowAll func(widget uintptr) + widgetHide func(widget uintptr) + widgetDestroy func(widget uintptr) + widgetRealize func(widget uintptr) + widgetQueueDraw func(widget uintptr) + widgetQueueDrawArea func(widget uintptr, x, y, width, height int32) + widgetGetWindow func(widget uintptr) uintptr + widgetAddEvents func(widget uintptr, events int32) + widgetSetEvents func(widget uintptr, events int32) + widgetSetSize func(widget uintptr, width, height int32) + widgetSetCanFocus func(widget uintptr, can int32) + widgetGrabFocus func(widget uintptr) + gestureMultiPressNew func(widget uintptr) uintptr + controllerSetPhase func(controller uintptr, phase int32) + gestureSetState func(gesture uintptr, state int32) int32 + + widgetRegisterWindow func(widget, window uintptr) + widgetUnregisterWindow func(widget, window uintptr) + widgetAllocW func(widget uintptr) int32 widgetAllocH func(widget uintptr) int32 widgetGetScale func(widget uintptr) int32 @@ -153,6 +161,11 @@ type gtkLibrary struct { gdkDisplayMonitorAt func(display, window uintptr) uintptr gdkMonitorGeometry func(monitor uintptr, rect *[4]int32) gdkWindowSetCursor func(window, cursor uintptr) + gdkWindowNew func(parent uintptr, attrs *gdkWindowAttr, mask int32) uintptr + gdkWindowShow func(window uintptr) + gdkWindowDestroy func(window uintptr) + gdkWindowMoveResize func(window uintptr, x, y, width, height int32) + gdkWindowTransient func(window, parent uintptr) gdkCursorFromName func(display uintptr, name *byte) uintptr gdkCursorFromPixbuf func(display, pixbuf uintptr, x, y int32) uintptr gdkCursorFromSurface func(display, surface uintptr, x, y float64) uintptr @@ -230,6 +243,22 @@ type gdkGeometry struct { _ [4]byte } +// GDK window attributes on LP64 Linux, shared by GTK 3 on amd64 and arm64. +type gdkWindowAttr struct { + Title uintptr + EventMask int32 + X, Y int32 + Width, Height int32 + Class int32 + Visual uintptr + WindowType int32 + Cursor uintptr + WMClassName uintptr + WMClassClass uintptr + OverrideRedirect int32 + TypeHint int32 +} + const ( gdkHintMinSize = 1 << 1 gdkHintPos = 1 << 0 @@ -342,6 +371,7 @@ func (g *gtkLibrary) bindAll() { b(&g.windowBeginMove, "gtk_window_begin_move_drag") b(&g.windowBeginResize, "gtk_window_begin_resize_drag") b(&g.windowSetFocus, "gtk_window_set_focus") + b(&g.windowGetFocus, "gtk_window_get_focus") b(&g.windowSetTransient, "gtk_window_set_transient_for") b(&g.windowSetAppPaint, "gtk_widget_set_app_paintable") b(&g.windowSetVisual, "gtk_widget_set_visual") @@ -359,6 +389,11 @@ func (g *gtkLibrary) bindAll() { b(&g.widgetSetSize, "gtk_widget_set_size_request") b(&g.widgetSetCanFocus, "gtk_widget_set_can_focus") b(&g.widgetGrabFocus, "gtk_widget_grab_focus") + b(&g.gestureMultiPressNew, "gtk_gesture_multi_press_new") + b(&g.controllerSetPhase, "gtk_event_controller_set_propagation_phase") + b(&g.gestureSetState, "gtk_gesture_set_state") + b(&g.widgetRegisterWindow, "gtk_widget_register_window") + b(&g.widgetUnregisterWindow, "gtk_widget_unregister_window") b(&g.widgetAllocW, "gtk_widget_get_allocated_width") b(&g.widgetAllocH, "gtk_widget_get_allocated_height") b(&g.widgetGetScale, "gtk_widget_get_scale_factor") @@ -421,6 +456,11 @@ func (g *gtkLibrary) bindAll() { b(&g.gdkDisplayMonitorAt, "gdk_display_get_monitor_at_window") b(&g.gdkMonitorGeometry, "gdk_monitor_get_geometry") b(&g.gdkWindowSetCursor, "gdk_window_set_cursor") + b(&g.gdkWindowNew, "gdk_window_new") + b(&g.gdkWindowShow, "gdk_window_show") + b(&g.gdkWindowDestroy, "gdk_window_destroy") + b(&g.gdkWindowMoveResize, "gdk_window_move_resize") + b(&g.gdkWindowTransient, "gdk_window_set_transient_for") b(&g.gdkCursorFromName, "gdk_cursor_new_from_name") b(&g.gdkCursorFromPixbuf, "gdk_cursor_new_from_pixbuf") b(&g.gdkCursorFromSurface, "gdk_cursor_new_from_surface") diff --git a/internal/platform/linux/gtk_native_widget_focus_linux_test.go b/internal/platform/linux/gtk_native_widget_focus_linux_test.go new file mode 100644 index 000000000..08ee91750 --- /dev/null +++ b/internal/platform/linux/gtk_native_widget_focus_linux_test.go @@ -0,0 +1,527 @@ +//go:build linux && vivagtk + +package linux + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/dbus" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +type gtkNativeWidgetFocusState struct { + windowFocused, otherFocused, nativeKeys, imeActive bool + windowFocusedAtOtherClick bool + pointerOnOther bool + webFocus, windowFocus, afterTakeKeys uintptr + focusLost, focusLostAtOtherClick, focusLostAtReturnClick int + otherClicks, editorClicks, entryIn, entryOut int + eventOrder []string +} + +type gtkNativeWidgetTrace struct { + entryIn, entryOut int + focusLostAtOtherClick int + windowFocusedAtOtherClick bool + focusLostAtReturnClick int + afterTakeKeys uintptr + getFocus func(uintptr) uintptr + events []string +} + +var gtkNativeWidgetTraceActive *gtkNativeWidgetTrace + +func (trace *gtkNativeWidgetTrace) note(event string) { + if len(trace.events) == 32 { + copy(trace.events, trace.events[1:]) + trace.events = trace.events[:31] + } + trace.events = append(trace.events, event) +} + +func gtkNativeWidgetState(ctx context.Context, app *gtkApplication, editor, other *gtkWindow, lost, otherClicks, editorClicks *int) (gtkNativeWidgetFocusState, error) { + answer := make(chan gtkNativeWidgetFocusState, 1) + app.enqueue(func() { + state := gtkNativeWidgetFocusState{ + windowFocused: editor.focused, otherFocused: other.focused, + nativeKeys: editor.nativeKeys, webFocus: editor.webFocus, + imeActive: editor.ime != nil && editor.ime.active, + pointerOnOther: other.wl != nil && other.wl.s.focus == other.wl, + focusLost: *lost, otherClicks: *otherClicks, editorClicks: *editorClicks, + } + if trace := gtkNativeWidgetTraceActive; trace != nil { + state.windowFocus = trace.getFocus(editor.toplevel) + state.afterTakeKeys = trace.afterTakeKeys + state.entryIn, state.entryOut = trace.entryIn, trace.entryOut + state.focusLostAtOtherClick = trace.focusLostAtOtherClick + state.windowFocusedAtOtherClick = trace.windowFocusedAtOtherClick + state.focusLostAtReturnClick = trace.focusLostAtReturnClick + state.eventOrder = append([]string(nil), trace.events...) + } + answer <- state + }) + select { + case state := <-answer: + return state, nil + case <-ctx.Done(): + return gtkNativeWidgetFocusState{}, ctx.Err() + } +} + +func gtkNativeWidgetWait(ctx context.Context, app *gtkApplication, editor, other *gtkWindow, lost, otherClicks, editorClicks *int, label string, check func(gtkNativeWidgetFocusState) bool) error { + deadline := time.NewTimer(2 * time.Second) + defer deadline.Stop() + var last gtkNativeWidgetFocusState + for { + state, err := gtkNativeWidgetState(ctx, app, editor, other, lost, otherClicks, editorClicks) + if err != nil { + return fmt.Errorf("%s: %w", label, err) + } + last = state + if check(state) { + return nil + } + select { + case <-deadline.C: + return fmt.Errorf("%s: deadline; A.focused=%t B.focused=%t B.pointer=%t nativeKeys=%t webFocus=%#x gtkFocus=%#x afterTakeKeys=%#x entryIn/out=%d/%d IME=%t OnFocusLost=%d B.pointerDown=%d A.pointerDown=%d events=%q", + label, last.windowFocused, last.otherFocused, last.pointerOnOther, last.nativeKeys, last.webFocus, + last.windowFocus, last.afterTakeKeys, last.entryIn, last.entryOut, + last.imeActive, last.focusLost, last.otherClicks, last.editorClicks, last.eventOrder) + case <-ctx.Done(): + return fmt.Errorf("%s: %w", label, ctx.Err()) + case <-time.After(10 * time.Millisecond): + } + } +} + +func gtkNativeWidgetFocusRun(ctx context.Context, t *testing.T, app *gtkApplication, p *gtkTentativeProbe, other *gtkWindow, entry uintptr, lost, otherClicks, editorClicks *int, path string) (failures []string) { + driver, err := newGTKSeatDriver(ctx, path) + if err != nil { + return []string{fmt.Sprintf("start GTK native-widget seat driver: %v", err)} + } + defer func() { + if err := driver.close(); err != nil { + failures = append(failures, err.Error()) + } + }() + logState := func(stage string) { + if os.Getenv("VIVA_GTK_SEAT_TRACE") != "1" { + return + } + state, err := gtkNativeWidgetState(ctx, app, p.w, other, lost, otherClicks, editorClicks) + if err != nil { + failures = append(failures, fmt.Sprintf("%s: %v", stage, err)) + return + } + t.Logf("native-widget %s: A.focused=%t B.focused=%t nativeKeys=%t webFocus=%#x gtkFocus=%#x afterTakeKeys=%#x entryIn/out=%d/%d IME=%t lost=%d clicks(A/B)=%d/%d order=%q", + stage, state.windowFocused, state.otherFocused, state.nativeKeys, state.webFocus, + state.windowFocus, state.afterTakeKeys, state.entryIn, state.entryOut, + state.imeActive, state.focusLost, state.editorClicks, state.otherClicks, state.eventOrder) + } + pointer := >kSeatPointer{} + if err := gtkSeatWait(ctx, app, p, pointer, "A mapped editor", func(s gtkSeatSnapshot) bool { return s.mapped && s.imeActive }); err != nil { + return []string{err.Error()} + } + for _, op := range []string{"bind", "focus", "grab"} { + if _, err := driver.command(op, "", "wayland"); err != nil { + return []string{err.Error()} + } + } + if err := gtkNativeWidgetWait(ctx, app, p.w, other, lost, otherClicks, editorClicks, "A initial focus", func(s gtkNativeWidgetFocusState) bool { + return s.windowFocused && s.imeActive + }); err != nil { + return []string{err.Error()} + } + beforeEntry, err := gtkNativeWidgetState(ctx, app, p.w, other, lost, otherClicks, editorClicks) + if err != nil { + return []string{err.Error()} + } + grabbing := make(chan struct{}, 1) + app.enqueue(func() { + p.w.g.widgetGrabFocus(entry) + grabbing <- struct{}{} + }) + select { + case <-grabbing: + case <-ctx.Done(): + return []string{ctx.Err().Error()} + } + if err := gtkNativeWidgetWait(ctx, app, p.w, other, lost, otherClicks, editorClicks, "real GtkEntry focus", func(s gtkNativeWidgetFocusState) bool { + return s.windowFocused && s.nativeKeys && s.webFocus == entry && !s.imeActive && s.focusLost == beforeEntry.focusLost+1 + }); err != nil { + return []string{err.Error()} + } + baseline, err := gtkNativeWidgetState(ctx, app, p.w, other, lost, otherClicks, editorClicks) + if err != nil { + return []string{err.Error()} + } + shown := make(chan struct{}, 1) + app.enqueue(func() { + other.g.widgetShowAll(other.toplevel) + shown <- struct{}{} + }) + select { + case <-shown: + case <-ctx.Done(): + return []string{ctx.Err().Error()} + } + if _, err := driver.command("probe-switch", "", ""); err != nil { + return []string{err.Error()} + } + clickX, clickY := -1, -1 + for _, y := range []int{300, 220, 380, 140, 460, 60, 540} { + for x := 40; x < 800; x += 80 { + if _, err := driver.commandAt("move", x, y); err != nil { + return []string{err.Error()} + } + for attempt := 0; attempt < 6; attempt++ { + state, err := gtkNativeWidgetState(ctx, app, p.w, other, lost, otherClicks, editorClicks) + if err != nil { + return []string{err.Error()} + } + if state.pointerOnOther { + select { + case <-ctx.Done(): + return []string{ctx.Err().Error()} + case <-time.After(10 * time.Millisecond): + } + state, err = gtkNativeWidgetState(ctx, app, p.w, other, lost, otherClicks, editorClicks) + if err != nil { + return []string{err.Error()} + } + if state.pointerOnOther { + clickX, clickY = x, y + break + } + } + select { + case <-ctx.Done(): + return []string{ctx.Err().Error()} + case <-time.After(10 * time.Millisecond): + } + } + if clickX >= 0 { + break + } + } + if clickX >= 0 { + break + } + } + if clickX < 0 { + return []string{"real XTest pointer never entered B's Wayland content surface"} + } + if _, err := driver.commandAt("click-at", clickX, clickY); err != nil { + return []string{err.Error()} + } + if err := gtkNativeWidgetWait(ctx, app, p.w, other, lost, otherClicks, editorClicks, "real B pointer-down", func(s gtkNativeWidgetFocusState) bool { + return s.otherClicks == 1 + }); err != nil { + return []string{err.Error()} + } + logState("B clicked") + var afterSwitch gtkNativeWidgetFocusState + if err := gtkNativeWidgetWait(ctx, app, p.w, other, lost, otherClicks, editorClicks, "external A to B focus", func(s gtkNativeWidgetFocusState) bool { + afterSwitch = s + return !s.windowFocused && s.otherFocused && !s.imeActive && s.focusLost >= baseline.focusLost+1 + }); err != nil { + failures = append(failures, err.Error()) + } else { + // B's press may precede A's focus-out, which then accounts for one more loss. + want := afterSwitch.focusLostAtOtherClick + if afterSwitch.windowFocusedAtOtherClick { + want++ + } + if afterSwitch.focusLost != want { + failures = append(failures, fmt.Sprintf("A OnFocusLost after B.PointerDown=%d, at B.PointerDown=%d A.focused=%t, want %d; events=%q", + afterSwitch.focusLost, afterSwitch.focusLostAtOtherClick, afterSwitch.windowFocusedAtOtherClick, want, afterSwitch.eventOrder)) + } + } + logState("before B hide") + hidden := make(chan struct{}, 1) + app.enqueue(func() { + if trace := gtkNativeWidgetTraceActive; trace != nil { + trace.note("B.hide begin") + } + other.g.widgetHide(other.toplevel) + if trace := gtkNativeWidgetTraceActive; trace != nil { + trace.note("B.hide end") + } + hidden <- struct{}{} + }) + select { + case <-hidden: + case <-ctx.Done(): + return append(failures, ctx.Err().Error()) + } + logState("after B hide, before A click") + if _, err := driver.command("click", "", ""); err != nil { + return append(failures, err.Error()) + } + logState("after A click dispatch") + if err := gtkNativeWidgetWait(ctx, app, p.w, other, lost, otherClicks, editorClicks, "A editor return click", func(s gtkNativeWidgetFocusState) bool { + return s.editorClicks == 1 && s.windowFocused && !s.nativeKeys && s.webFocus == 0 && s.imeActive + }); err != nil { + logState("A return timeout") + return append(failures, err.Error()) + } + logState("A editor restored") + if state, err := gtkNativeWidgetState(ctx, app, p.w, other, lost, otherClicks, editorClicks); err != nil { + return append(failures, err.Error()) + } else if state.focusLost != state.focusLostAtReturnClick { + failures = append(failures, fmt.Sprintf("A OnFocusLost after return=%d, at A.PointerDown=%d; A.focused=%t B.focused=%t nativeKeys=%t webFocus=%#x gtkFocus=%#x afterTakeKeys=%#x entryIn/out=%d/%d IME=%t clicks(A/B)=%d/%d events=%q", + state.focusLost, state.focusLostAtReturnClick, state.windowFocused, state.otherFocused, state.nativeKeys, + state.webFocus, state.windowFocus, state.afterTakeKeys, state.entryIn, state.entryOut, + state.imeActive, state.editorClicks, state.otherClicks, state.eventOrder)) + } + deadline := time.NewTimer(3 * time.Second) + defer deadline.Stop() + for { + active, err := nativeFcitxCommand("--check", "-n") + if err != nil { + return append(failures, fmt.Sprintf("A Fcitx reactivation: %v", err)) + } + if active != "" { + break + } + select { + case <-deadline.C: + return append(failures, "A Fcitx did not reactivate") + case <-ctx.Done(): + return append(failures, ctx.Err().Error()) + case <-time.After(20 * time.Millisecond): + } + } + if err := selectNativeFcitxEngine("pinyin"); err != nil { + return append(failures, fmt.Sprintf("A select Fcitx pinyin: %v", err)) + } + for _, key := range []string{"n", "i"} { + before, err := gtkSeatState(ctx, app, p, pointer) + if err != nil { + return append(failures, err.Error()) + } + if _, err := driver.command("down", key, ""); err != nil { + return append(failures, err.Error()) + } + if _, err := driver.command("up", key, ""); err != nil { + return append(failures, err.Error()) + } + if err := gtkSeatWait(ctx, app, p, pointer, "A restored pinyin "+key, func(s gtkSeatSnapshot) bool { + return s.preeditSignals > before.preeditSignals && s.preeditEvents > before.preeditEvents + }); err != nil { + failures = append(failures, err.Error()) + } + } + beforeCancel, err := gtkSeatState(ctx, app, p, pointer) + if err != nil { + return append(failures, err.Error()) + } + for _, op := range []string{"down", "up"} { + if _, err := driver.command(op, "Escape", ""); err != nil { + return append(failures, err.Error()) + } + } + if err := gtkSeatWait(ctx, app, p, pointer, "A restored Escape", func(s gtkSeatSnapshot) bool { + return s.cancelEvents == beforeCancel.cancelEvents+1 && s.value == "abc" && !s.composing && !s.canUndo && s.pressedKeys == 0 + }); err != nil { + failures = append(failures, err.Error()) + } + return failures +} + +// GtkEntry exercises native GTK focus ownership without loading a WebKit page. +func TestGTKNativeWaylandWidgetExternalFocus(t *testing.T) { + if os.Getenv("VIVA_GTK_NATIVE_WIDGET_FOCUS") != "1" || os.Getenv("VIVA_FCITX_BACKEND") != "wayland" { + t.Skip("requires the private Wayland native-widget seat fixture") + } + path := os.Getenv("VIVA_GTK_SEAT_DRIVER") + if path == "" || os.Getenv("VIVA_GTK_SEAT_NATIVE") != "1" || os.Getenv("VIVA_GTK_IME_NATIVE") != "1" || os.Getenv("VIVA_ACCESSIBILITY") == "0" { + t.Fatal("native-widget focus fixture is missing its driver or GTK/accessibility settings") + } + if _, err := os.Stat(path); err != nil { + t.Fatal(err) + } + connection, err := dbus.DialSession() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { connection.Close() }) + restoreA11yStatus(t, connection, "IsEnabled") + var status dbus.Encoder + status.String(a11yStatus) + status.String("IsEnabled") + status.Variant("b") + status.Bool(true) + if _, err := connection.Call(a11yBusName, a11yBusPath, dbusProperties, "Set", "ssv", status.Bytes()); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) + defer cancel() + p := >kTentativeProbe{tentative: true} + gtkTentativeProbeActive = p + defer func() { gtkTentativeProbeActive = nil }() + trace := >kNativeWidgetTrace{} + gtkNativeWidgetTraceActive = trace + defer func() { gtkNativeWidgetTraceActive = nil }() + result := make(chan []string, 1) + focusLost, otherClicks, editorClicks := 0, 0, 0 + err = RunGTKApplication(func(application platform.Application) error { + app := application.(*gtkApplication) + host := &platform.WebHost{} + var aWindow *gtkWindow + first, err := application.OpenWindow(platform.Config{ + Title: "Viva seat keyboard probe", Width: 800, Height: 600, WindowMode: platform.WindowFrameless, + ClearColor: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Web: host, DynamicTextInput: true, + Accessibility: []platform.AccessibilityNode{{ + ID: gfx.Item(1), Role: platform.A11yRoleTextField, Label: "Seat editor", + X: 20, Y: 20, Width: 300, Height: 100, Focusable: true, + }}, + OnAccessibility: func(request platform.AccessibilityRequest, _ func(platform.Frame) error) (bool, error) { + return request.Node == gfx.Item(1) && request.Action == platform.AccessibilityFocus, nil + }, + OnFocusLost: func() (platform.Frame, error) { + focusLost++ + if aWindow != nil { + trace.note(fmt.Sprintf("A.OnFocusLost focused=%t nativeKeys=%t webFocus=%#x serial=%d", aWindow.focused, aWindow.nativeKeys, aWindow.webFocus, aWindow.focusSerial)) + } else { + trace.note("A.OnFocusLost") + } + return platform.Frame{}, nil + }, + OnPointer: func(event platform.PointerEvent) (platform.Frame, error) { + if event.Kind == platform.PointerDown { + editorClicks++ + trace.focusLostAtReturnClick = focusLost + if aWindow != nil && trace.getFocus != nil { + trace.afterTakeKeys = trace.getFocus(aWindow.toplevel) + trace.note(fmt.Sprintf("A.PointerDown after takeKeys gtkFocus=%#x nativeKeys=%t", trace.afterTakeKeys, aWindow.nativeKeys)) + } + } + return platform.Frame{}, nil + }, + OnRedraw: func() (platform.Frame, error) { return platform.Frame{}, nil }, + }) + if err != nil { + return err + } + aWindow = first.(*gtkWindow) + p.w = aWindow + if !aWindow.g.lookup(&trace.getFocus, "gtk_window_get_focus") { + aWindow.destroy() + return fmt.Errorf("GTK native-widget focus fixture lacks gtk_window_get_focus") + } + for _, signal := range []struct{ name, label string }{{"focus-in-event", "A.top.focus-in"}, {"focus-out-event", "A.top.focus-out"}} { + label := signal.label + aWindow.g.connect(aWindow.toplevel, signal.name, purego.NewCallback(func(_, _, _ uintptr) uintptr { + trace.note(label) + return 0 + }), 0) + } + // The production focus handler stops the specific signal; the generic event runs first. + aWindow.g.connect(aWindow.area, "event", purego.NewCallback(func(_, event, _ uintptr) uintptr { + if eventType(event) == gdkFocusChange { + if (*gdkEventFocus)(unsafePointer(event)).In != 0 { + trace.note("A.area.focus-in") + } else { + trace.note("A.area.focus-out") + } + } + return 0 + }), 0) + second, err := application.OpenWindow(platform.Config{ + Title: "Viva native focus switch", Width: 800, Height: 600, WindowMode: platform.WindowFrameless, + ClearColor: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Accessibility: []platform.AccessibilityNode{{ + ID: gfx.Item(2), Role: platform.A11yRoleButton, Label: "Switch window", + X: 100, Y: 300, Width: 600, Height: 200, + }}, + OnPointer: func(event platform.PointerEvent) (platform.Frame, error) { + if event.Kind == platform.PointerDown { + otherClicks++ + trace.focusLostAtOtherClick = focusLost + trace.windowFocusedAtOtherClick = aWindow.focused + trace.note(fmt.Sprintf("B.PointerDown A.focused=%t lost=%d", aWindow.focused, focusLost)) + } + return platform.Frame{}, nil + }, + OnRedraw: func() (platform.Frame, error) { return platform.Frame{}, nil }, + }) + if err != nil { + aWindow.destroy() + return err + } + bWindow := second.(*gtkWindow) + bWindow.g.widgetHide(bWindow.toplevel) + bWindow.g.windowSetTransient(bWindow.toplevel, aWindow.toplevel) + var entryNew func() uintptr + if aWindow.overlay == 0 || !aWindow.g.lookup(&entryNew, "gtk_entry_new") { + bWindow.destroy() + aWindow.destroy() + return fmt.Errorf("GTK native-widget focus fixture lacks GtkOverlay or GtkEntry") + } + entry := entryNew() + if entry == 0 { + bWindow.destroy() + aWindow.destroy() + return fmt.Errorf("GTK could not create native GtkEntry") + } + g := aWindow.g + g.widgetSetHAlign(entry, 1) + g.widgetSetVAlign(entry, 1) + g.widgetSetMarginX(entry, 500) + g.widgetSetMarginY(entry, 400) + g.widgetSetSize(entry, 100, 32) + g.overlayAdd(aWindow.overlay, entry) + g.connect(entry, "focus-in-event", callbacks().event, aWindow.id) + g.connect(entry, "focus-out-event", callbacks().event, aWindow.id) + g.connect(entry, "focus-in-event", purego.NewCallback(func(_, _, _ uintptr) uintptr { + trace.entryIn++ + trace.note("GtkEntry.focus-in") + return 0 + }), 0) + g.connect(entry, "focus-out-event", purego.NewCallback(func(_, _, _ uintptr) uintptr { + trace.entryOut++ + trace.note("GtkEntry.focus-out") + return 0 + }), 0) + g.widgetShow(entry) + app.enqueue(func() { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + result <- []string{"native-widget editor refused tentative composition"} + bWindow.destroy() + aWindow.destroy() + return + } + p.install(editor) + go func() { + failures := gtkNativeWidgetFocusRun(ctx, t, app, p, bWindow, entry, &focusLost, &otherClicks, &editorClicks, path) + result <- failures + app.enqueue(func() { + bWindow.destroy() + aWindow.destroy() + }) + }() + }) + return nil + }) + if err != nil { + t.Fatal(err) + } + select { + case failures := <-result: + for _, failure := range failures { + t.Error(failure) + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } +} diff --git a/internal/platform/linux/gtk_wayland_attach_failure_native_linux_test.go b/internal/platform/linux/gtk_wayland_attach_failure_native_linux_test.go new file mode 100644 index 000000000..00c64bccd --- /dev/null +++ b/internal/platform/linux/gtk_wayland_attach_failure_native_linux_test.go @@ -0,0 +1,90 @@ +//go:build linux && vivagtk + +package linux + +import ( + "context" + "fmt" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/vivaui/viva/internal/platform" +) + +const gtkAttachFaultMarker = "GDK content-window attach fault injected" + +func TestGTKNativeWaylandAttachFailure(t *testing.T) { + if os.Getenv("VIVA_GTK_ATTACH_NATIVE") != "1" || os.Getenv("VIVA_FCITX_BACKEND") != "wayland" { + t.Skip("requires the private Wayland GTK attach-failure fixture") + } + if os.Getenv("VIVA_GTK_ATTACH_CHILD") == "1" { + gtkAttachFailureChild(t) + return + } + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGTKNativeWaylandAttachFailure$", "-test.v", "-test.timeout=15s") + cmd.Env = append(os.Environ(), "VIVA_GTK_ATTACH_CHILD=1") + output, err := cmd.CombinedOutput() + if !strings.Contains(string(output), gtkAttachFaultMarker) { + t.Fatalf("native GDK content fault was not injected; child error=%v, output=%.1200s", err, output) + } + if ctx.Err() != nil { + t.Fatalf("OpenWindow/GTK loop hung after the injected content fault: %v; output=%.1200s", ctx.Err(), output) + } + if err != nil { + t.Fatalf("native content attach-failure contract: %v; output=%.1200s", err, output) + } +} + +func gtkAttachFailureChild(t *testing.T) { + var original func(uintptr, *gdkWindowAttr, int32) uintptr + var library *gtkLibrary + var openErr error + var window platform.Window + faults := 0 + runErr := RunGTKApplication(func(application platform.Application) error { + a := application.(*gtkApplication) + if err := a.initialize("Viva attach failure"); err != nil { + return err + } + if !a.wayland { + return fmt.Errorf("native attach-failure test needs GdkWaylandDisplay") + } + library, original = a.g, a.g.gdkWindowNew + a.g.gdkWindowNew = func(parent uintptr, attrs *gdkWindowAttr, mask int32) uintptr { + if attrs.WindowType == 6 { // GDK_WINDOW_SUBSURFACE + faults++ + if faults == 1 { + fmt.Fprintln(os.Stdout, gtkAttachFaultMarker) + } + return 0 + } + return original(parent, attrs, mask) + } + window, openErr = application.OpenWindow(platform.Config{ + Title: "Viva attach-failure probe", Width: 240, Height: 160, + ClearColor: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + OnRedraw: func() (platform.Frame, error) { return platform.Frame{}, nil }, + }) + return openErr + }) + if library != nil { + library.gdkWindowNew = original + } + if faults != 1 { + t.Errorf("content-window fault calls=%d, want 1", faults) + } + if window != nil || openErr == nil { + t.Errorf("OpenWindow returned window=%t error=%v after GDK content failure", window != nil, openErr) + } + if openErr != nil && !strings.Contains(openErr.Error(), "GDK Wayland content window") { + t.Errorf("OpenWindow error=%v, want a content-window creation error", openErr) + } + if runErr == nil || runErr != openErr { + t.Errorf("RunGTKApplication error=%v, want OpenWindow error=%v", runErr, openErr) + } +} diff --git a/internal/platform/linux/gtk_wayland_attr_linux_test.go b/internal/platform/linux/gtk_wayland_attr_linux_test.go new file mode 100644 index 000000000..9108c9f8b --- /dev/null +++ b/internal/platform/linux/gtk_wayland_attr_linux_test.go @@ -0,0 +1,39 @@ +//go:build linux && vivagtk + +package linux + +import ( + "testing" + "unsafe" +) + +func TestGTKWaylandWindowAttrLP64Layout(t *testing.T) { + var attr gdkWindowAttr + if size := unsafe.Sizeof(attr); size != 80 { + t.Fatalf("GDK window attributes size=%d, want 80", size) + } + for _, field := range []struct { + name string + got uintptr + want uintptr + }{ + {"Title", unsafe.Offsetof(attr.Title), 0}, + {"EventMask", unsafe.Offsetof(attr.EventMask), 8}, + {"X", unsafe.Offsetof(attr.X), 12}, + {"Y", unsafe.Offsetof(attr.Y), 16}, + {"Width", unsafe.Offsetof(attr.Width), 20}, + {"Height", unsafe.Offsetof(attr.Height), 24}, + {"Class", unsafe.Offsetof(attr.Class), 28}, + {"Visual", unsafe.Offsetof(attr.Visual), 32}, + {"WindowType", unsafe.Offsetof(attr.WindowType), 40}, + {"Cursor", unsafe.Offsetof(attr.Cursor), 48}, + {"WMClassName", unsafe.Offsetof(attr.WMClassName), 56}, + {"WMClassClass", unsafe.Offsetof(attr.WMClassClass), 64}, + {"OverrideRedirect", unsafe.Offsetof(attr.OverrideRedirect), 72}, + {"TypeHint", unsafe.Offsetof(attr.TypeHint), 76}, + } { + if field.got != field.want { + t.Errorf("GDK window attributes %s offset=%d, want %d", field.name, field.got, field.want) + } + } +} diff --git a/internal/platform/linux/gtk_wayland_keyboard_native_linux_test.go b/internal/platform/linux/gtk_wayland_keyboard_native_linux_test.go new file mode 100644 index 000000000..e2d025ef1 --- /dev/null +++ b/internal/platform/linux/gtk_wayland_keyboard_native_linux_test.go @@ -0,0 +1,613 @@ +//go:build linux && vivagtk + +package linux + +import ( + "context" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "strings" + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/dbus" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +type gtkSeatSnapshot struct { + mapped, focused, imeActive, composing, canUndo, canRedo bool + pointers, signalCount, eventCount int + preeditSignals, preeditEvents, cancelEvents, commits int + pressedKeys, clickCount int + value string + lastSignal string + lastEvent platform.TextEvent + lastEvents []string + selection, mirroredSelection, composition text.Range + compositionActive bool + editorIdentity, mirrorIdentity, imeIdentity text.CompositionIdentity +} + +type gtkSeatPointer struct { + downs, clickCount int +} + +type gtkSeatSurfaceState struct { + child uintptr + oldRegistered, registered bool + display uintptr + closed bool +} + +type gtkSeatDriver struct { + cmd *exec.Cmd + input io.WriteCloser + output *json.Decoder +} + +type gtkSeatReply struct { + OK bool `json:"ok"` + Error string `json:"error"` + Code uint16 `json:"code"` + Window uint64 `json:"window"` +} + +type gtkSeatRequest struct { + Op string `json:"op"` + Key string `json:"key,omitempty"` + Backend string `json:"backend,omitempty"` + PID int `json:"pid,omitempty"` + X int `json:"x,omitempty"` + Y int `json:"y,omitempty"` +} + +func newGTKSeatDriver(ctx context.Context, path string) (*gtkSeatDriver, error) { + cmd := exec.CommandContext(ctx, "/usr/bin/python3", path) + input, err := cmd.StdinPipe() + if err != nil { + return nil, err + } + output, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + driver := >kSeatDriver{cmd: cmd, input: input, output: json.NewDecoder(output)} + cmd.Stderr = os.Stderr + if err := cmd.Start(); err != nil { + return nil, err + } + return driver, nil +} + +func (d *gtkSeatDriver) command(op, key, backend string) (gtkSeatReply, error) { + return d.send(gtkSeatRequest{Op: op, Key: key, Backend: backend, PID: os.Getpid()}) +} + +func (d *gtkSeatDriver) commandAt(op string, x, y int) (gtkSeatReply, error) { + return d.send(gtkSeatRequest{Op: op, PID: os.Getpid(), X: x, Y: y}) +} + +func (d *gtkSeatDriver) send(request gtkSeatRequest) (gtkSeatReply, error) { + if err := json.NewEncoder(d.input).Encode(request); err != nil { + return gtkSeatReply{}, fmt.Errorf("seat %s command: %w", request.Op, err) + } + var response gtkSeatReply + if err := d.output.Decode(&response); err != nil { + return response, fmt.Errorf("seat %s response: %w (see driver stderr)", request.Op, err) + } + if !response.OK { + return response, fmt.Errorf("seat %s: %s", request.Op, response.Error) + } + return response, nil +} + +func (d *gtkSeatDriver) close() error { + _, _ = d.command("quit", "", "") + _ = d.input.Close() + if err := d.cmd.Wait(); err != nil { + return fmt.Errorf("seat driver exited: %w (see driver stderr)", err) + } + return nil +} + +func gtkSeatState(ctx context.Context, a *gtkApplication, p *gtkTentativeProbe, pointers *gtkSeatPointer) (gtkSeatSnapshot, error) { + answer := make(chan gtkSeatSnapshot, 1) + a.enqueue(func() { + w := p.w + state := gtkSeatSnapshot{ + focused: w.focused, pointers: pointers.downs, clickCount: pointers.clickCount, + value: p.editor.String(), canUndo: p.editor.CanUndo(), canRedo: p.editor.CanRedo(), + signalCount: len(p.signals), eventCount: len(p.events), + composing: w.text.state.Composing, pressedKeys: len(w.keys.down), + selection: p.editor.Selection(), mirroredSelection: w.text.state.Selection, + editorIdentity: p.editor.TentativeCompositionIdentity(), mirrorIdentity: w.text.state.CompositionIdentity, + } + state.composition, state.compositionActive = p.editor.Composition() + for _, signal := range p.signals { + if strings.HasPrefix(signal, "preedit:") && len(signal) > len("preedit:") { + state.preeditSignals++ + } + if strings.HasPrefix(signal, "commit:") { + state.commits++ + } + } + if len(p.signals) > 0 { + state.lastSignal = p.signals[len(p.signals)-1] + } + for _, event := range p.events { + if event.Kind == platform.TextSetMarked && event.CompositionPhase == text.CompositionUpdate && event.Text != "" { + state.preeditEvents++ + } + if event.CompositionPhase == text.CompositionCancel { + state.cancelEvents++ + } + } + if len(p.events) > 0 { + state.lastEvent = p.events[len(p.events)-1] + } + for _, event := range p.events[max(0, len(p.events)-4):] { + state.lastEvents = append(state.lastEvents, fmt.Sprintf("%d/%d:%.24q", event.Kind, event.CompositionPhase, event.Text)) + } + if w.ime != nil { + state.imeActive = w.ime.ctx != 0 && w.ime.active + state.imeIdentity = w.ime.owner + } + state.mapped = w.wl == nil || w.wl.child != 0 + answer <- state + }) + select { + case state := <-answer: + return state, nil + case <-ctx.Done(): + return gtkSeatSnapshot{}, ctx.Err() + } +} + +func gtkSeatSurface(ctx context.Context, a *gtkApplication, p *gtkTentativeProbe, old uintptr) (gtkSeatSurfaceState, error) { + answer := make(chan gtkSeatSurfaceState, 1) + a.enqueue(func() { + w := p.w + state := gtkSeatSurfaceState{child: w.wl.child, display: w.wl.s.display, closed: w.closed} + state.oldRegistered = w.wl.s.surfaces[old] == w.wl + state.registered = state.child != 0 && w.wl.s.surfaces[state.child] == w.wl + answer <- state + }) + select { + case state := <-answer: + return state, nil + case <-ctx.Done(): + return gtkSeatSurfaceState{}, ctx.Err() + } +} + +func gtkSeatWait(ctx context.Context, a *gtkApplication, p *gtkTentativeProbe, pointers *gtkSeatPointer, label string, check func(gtkSeatSnapshot) bool) error { + deadline := time.NewTimer(2 * time.Second) + defer deadline.Stop() + var last gtkSeatSnapshot + for { + state, err := gtkSeatState(ctx, a, p, pointers) + if err != nil { + return fmt.Errorf("%s: %w", label, err) + } + last = state + if check(state) { + return nil + } + select { + case <-deadline.C: + return fmt.Errorf("%s: deadline; focused=%t imeActive=%t mapped=%t pointerDown=%d preedit=%d/%d cancel=%d keysDown=%d composing=%t undo=%t textLen=%d signals=%d events=%d lastSignal=%.80q lastEvent=%d/%d:%.80q", + label, last.focused, last.imeActive, last.mapped, last.pointers, last.preeditSignals, last.preeditEvents, last.cancelEvents, last.pressedKeys, + last.composing, last.canUndo, len(last.value), last.signalCount, last.eventCount, + last.lastSignal, last.lastEvent.Kind, last.lastEvent.CompositionPhase, last.lastEvent.Text) + case <-ctx.Done(): + return fmt.Errorf("%s: %w", label, ctx.Err()) + case <-time.After(10 * time.Millisecond): + } + } +} + +func gtkSeatRun(ctx context.Context, t *testing.T, a *gtkApplication, p *gtkTentativeProbe, pointers *gtkSeatPointer, backend, path string, remap bool) (failures []string) { + driver, err := newGTKSeatDriver(ctx, path) + if err != nil { + return []string{fmt.Sprintf("start XTest/AT-SPI driver: %v", err)} + } + defer func() { + if err := driver.close(); err != nil { + failures = append(failures, err.Error()) + } + }() + if err := gtkSeatWait(ctx, a, p, pointers, "mapped native window", func(s gtkSeatSnapshot) bool { return s.mapped && s.imeActive }); err != nil { + return []string{err.Error()} + } + if backend == "wayland" && os.Getenv("VIVA_GTK_SEAT_TRACE") == "1" { + surfaces := make(chan [2]uintptr, 1) + a.enqueue(func() { + w := p.w + surfaces <- [2]uintptr{ + w.wl.s.surfaceOf(w.g.widgetGetWindow(w.toplevel)), + w.wl.s.surfaceOf(w.g.widgetGetWindow(w.area)), + } + }) + select { + case value := <-surfaces: + t.Logf("GDK area Wayland surface: top=%#x area=%#x nonzero=%t distinct=%t", value[0], value[1], value[1] != 0, value[1] != 0 && value[1] != value[0]) + case <-ctx.Done(): + return []string{ctx.Err().Error()} + } + } + for _, operation := range []string{"bind", "focus", "grab"} { + if _, err := driver.command(operation, "", backend); err != nil { + return []string{err.Error()} + } + } + if err := gtkSeatWait(ctx, a, p, pointers, "parent GTK focus", func(s gtkSeatSnapshot) bool { return s.focused && s.imeActive }); err != nil { + return []string{err.Error()} + } + selectPinyin := func() error { + deadline := time.NewTimer(3 * time.Second) + defer deadline.Stop() + for { + active, err := nativeFcitxCommand("--check", "-n") + if err != nil { + return fmt.Errorf("Fcitx client registration: %w", err) + } + if active != "" { + break + } + select { + case <-deadline.C: + return fmt.Errorf("Fcitx client did not register the focused native window") + case <-ctx.Done(): + return ctx.Err() + case <-time.After(20 * time.Millisecond): + } + } + return selectNativeFcitxEngine("pinyin") + } + if err := selectPinyin(); err != nil { + return []string{fmt.Sprintf("select Fcitx pinyin: %v", err)} + } + trace := func(stage string, state gtkSeatSnapshot) { + if !remap || os.Getenv("VIVA_GTK_SEAT_TRACE") != "1" || !strings.HasPrefix(stage, "remap ") { + return + } + t.Logf("seat %s value=%.48q selection=%d:%d mirrorSelection=%d:%d composition=%d:%d active=%t owner=%v/%v/%v undo=%t redo=%t focused=%t ime=%t pointerDown=%d clickCount=%d signals=%d events=%d lastEvents=%q", + stage, state.value, state.selection.Start, state.selection.End, + state.mirroredSelection.Start, state.mirroredSelection.End, + state.composition.Start, state.composition.End, state.compositionActive, + state.editorIdentity, state.mirrorIdentity, state.imeIdentity, + state.canUndo, state.canRedo, state.focused, state.imeActive, + state.pointers, state.clickCount, state.signalCount, state.eventCount, state.lastEvents) + } + typeKey := func(phase, symbol string, preedit bool) { + before, err := gtkSeatState(ctx, a, p, pointers) + if err != nil { + failures = append(failures, fmt.Sprintf("%s before %s: %v", phase, symbol, err)) + return + } + trace(phase+" before "+symbol, before) + pressed, err := driver.command("down", symbol, "") + if err != nil { + failures = append(failures, err.Error()) + return + } + released, err := driver.command("up", symbol, "") + if err != nil { + failures = append(failures, err.Error()) + return + } + if pressed.Code == 0 || pressed.Code != released.Code { + failures = append(failures, fmt.Sprintf("%s XTest keycode mismatch for %s: %d/%d", phase, symbol, pressed.Code, released.Code)) + return + } + if preedit { + if err := gtkSeatWait(ctx, a, p, pointers, phase+" GTK/Fcitx preedit "+symbol, func(s gtkSeatSnapshot) bool { + return s.preeditSignals > before.preeditSignals && s.preeditEvents > before.preeditEvents + }); err != nil { + failures = append(failures, err.Error()) + } + } + if after, err := gtkSeatState(ctx, a, p, pointers); err == nil { + trace(phase+" after "+symbol, after) + } else { + failures = append(failures, fmt.Sprintf("%s after %s: %v", phase, symbol, err)) + } + } + trial := func(phase string) { + typeKey(phase, "n", true) + typeKey(phase, "i", true) + before, err := gtkSeatState(ctx, a, p, pointers) + if err != nil { + failures = append(failures, fmt.Sprintf("%s before Escape: %v", phase, err)) + return + } + typeKey(phase, "Escape", false) + if err := gtkSeatWait(ctx, a, p, pointers, phase+" Escape cancel", func(s gtkSeatSnapshot) bool { + return s.cancelEvents == before.cancelEvents+1 && s.value == "abc" && !s.composing && !s.canUndo && s.pressedKeys == 0 + }); err != nil { + failures = append(failures, err.Error()) + } + select { + case <-ctx.Done(): + failures = append(failures, fmt.Sprintf("%s native tail: %v", phase, ctx.Err())) + return + case <-time.After(50 * time.Millisecond): + } + after, err := gtkSeatState(ctx, a, p, pointers) + if err != nil { + failures = append(failures, fmt.Sprintf("%s native tail: %v", phase, err)) + } else if after.cancelEvents != before.cancelEvents+1 || after.pressedKeys != 0 { + failures = append(failures, fmt.Sprintf("%s native tail: cancellations=%d, want=%d; keysDown=%d", phase, after.cancelEvents, before.cancelEvents+1, after.pressedKeys)) + } else if strings.Contains(phase, "content") && after.pointers != 1 { + failures = append(failures, fmt.Sprintf("%s native tail: pointerDown=%d, want=1", phase, after.pointers)) + } + if err == nil { + trace(phase+" settled", after) + } + } + reset := func() error { + ready := make(chan struct{}, 1) + a.enqueue(func() { + p.signals, p.events = nil, nil + pointers.downs, pointers.clickCount = 0, 0 + ready <- struct{}{} + }) + select { + case <-ready: + return nil + case <-ctx.Done(): + return ctx.Err() + } + } + trial("parent AX focus") + if err := reset(); err != nil { + return append(failures, err.Error()) + } + if _, err := driver.command("click", "", ""); err != nil { + return append(failures, err.Error()) + } + if err := gtkSeatWait(ctx, a, p, pointers, "content pointer-down", func(s gtkSeatSnapshot) bool { return s.pointers == 1 }); err != nil { + return append(failures, err.Error()) + } + trial("content click") + if len(failures) != 0 { + return failures + } + for cycle := 1; remap && cycle <= 2; cycle++ { + label := fmt.Sprintf("remap %d", cycle) + before, err := gtkSeatSurface(ctx, a, p, 0) + if err != nil || before.child == 0 || !before.registered || before.display == 0 || before.closed { + return append(failures, fmt.Sprintf("%s initial child: state=%+v error=%v", label, before, err)) + } + hidden := make(chan struct{}, 1) + a.enqueue(func() { + p.w.g.widgetHide(p.w.toplevel) + hidden <- struct{}{} + }) + select { + case <-hidden: + case <-ctx.Done(): + return append(failures, fmt.Sprintf("%s hide: %v", label, ctx.Err())) + } + if err := gtkSeatWait(ctx, a, p, pointers, label+" hidden child", func(s gtkSeatSnapshot) bool { return !s.mapped }); err != nil { + return append(failures, err.Error()) + } + old, err := gtkSeatSurface(ctx, a, p, before.child) + if err != nil || old.child != 0 || old.oldRegistered || old.display == 0 || old.closed { + return append(failures, fmt.Sprintf("%s old child retained: state=%+v error=%v", label, old, err)) + } + shown := make(chan struct{}, 1) + a.enqueue(func() { + p.w.g.widgetShowAll(p.w.toplevel) + shown <- struct{}{} + }) + select { + case <-shown: + case <-ctx.Done(): + return append(failures, fmt.Sprintf("%s show: %v", label, ctx.Err())) + } + if err := gtkSeatWait(ctx, a, p, pointers, label+" new child", func(s gtkSeatSnapshot) bool { return s.mapped }); err != nil { + return append(failures, err.Error()) + } + current, err := gtkSeatSurface(ctx, a, p, 0) + if err != nil || current.child == 0 || !current.registered || current.display == 0 || current.closed { + return append(failures, fmt.Sprintf("%s new child absent: state=%+v error=%v", label, current, err)) + } + for _, operation := range []string{"bind", "focus", "grab"} { + if _, err := driver.command(operation, "", backend); err != nil { + return append(failures, fmt.Sprintf("%s: %v", label, err)) + } + } + if err := gtkSeatWait(ctx, a, p, pointers, label+" parent focus", func(s gtkSeatSnapshot) bool { return s.focused && s.imeActive }); err != nil { + return append(failures, err.Error()) + } + if err := selectPinyin(); err != nil { + return append(failures, fmt.Sprintf("%s select Fcitx pinyin: %v", label, err)) + } + if err := reset(); err != nil { + return append(failures, err.Error()) + } + trial(label + " parent AX focus") + if len(failures) != 0 { + return failures + } + if err := reset(); err != nil { + return append(failures, err.Error()) + } + if state, err := gtkSeatState(ctx, a, p, pointers); err == nil { + trace(label+" before click", state) + } else { + return append(failures, fmt.Sprintf("%s before click: %v", label, err)) + } + if _, err := driver.command("click", "", ""); err != nil { + return append(failures, fmt.Sprintf("%s: %v", label, err)) + } + if err := gtkSeatWait(ctx, a, p, pointers, label+" content pointer-down", func(s gtkSeatSnapshot) bool { return s.pointers == 1 }); err != nil { + return append(failures, err.Error()) + } + if state, err := gtkSeatState(ctx, a, p, pointers); err == nil { + trace(label+" after click", state) + if state.clickCount != 1 { + failures = append(failures, fmt.Sprintf("%s first content click count=%d, want=1", label, state.clickCount)) + } + } else { + return append(failures, fmt.Sprintf("%s after click: %v", label, err)) + } + trial(label + " content click") + if len(failures) != 0 { + return failures + } + } + before, err := gtkSeatState(ctx, a, p, pointers) + if err != nil { + return append(failures, fmt.Sprintf("content commit baseline: %v", err)) + } + typeKey("content commit", "n", true) + typeKey("content commit", "i", true) + typeKey("content commit", "space", false) + if len(failures) != 0 { + return failures + } + if err := gtkSeatWait(ctx, a, p, pointers, "content commit and caret", func(s gtkSeatSnapshot) bool { + return s.commits == before.commits+1 && s.lastEvent.Kind == platform.TextInsert && + s.lastEvent.CompositionPhase == text.CompositionResult && strings.IndexFunc(s.value, func(r rune) bool { return r > 127 }) >= 0 && + !s.composing && !s.compositionActive && s.canUndo && + s.selection.Start == s.selection.End && s.selection.End > before.selection.End && s.pressedKeys == 0 + }); err != nil { + return append(failures, err.Error()) + } + undone := make(chan gtkSeatSnapshot, 1) + a.enqueue(func() { + if !p.editor.Undo() { + undone <- gtkSeatSnapshot{} + return + } + undone <- gtkSeatSnapshot{value: p.editor.String(), canUndo: p.editor.CanUndo(), canRedo: p.editor.CanRedo()} + }) + select { + case state := <-undone: + if state.value != "abc" || state.canUndo || !state.canRedo { + failures = append(failures, fmt.Sprintf("content commit Undo: text=%q undo=%t redo=%t, want abc/false/true", state.value, state.canUndo, state.canRedo)) + } + case <-ctx.Done(): + failures = append(failures, fmt.Sprintf("content commit Undo: %v", ctx.Err())) + } + return failures +} + +func TestGTKNativeSeatKeyboardAfterContentClick(t *testing.T) { + testGTKNativeSeatKeyboard(t, false) +} + +func TestGTKNativeWaylandSeatHideShow(t *testing.T) { + if os.Getenv("VIVA_GTK_SEAT_REMAP") != "1" || os.Getenv("VIVA_FCITX_BACKEND") != "wayland" { + t.Skip("requires the private Wayland seat remap fixture") + } + testGTKNativeSeatKeyboard(t, true) +} + +func testGTKNativeSeatKeyboard(t *testing.T, remap bool) { + t.Helper() + if os.Getenv("VIVA_GTK_SEAT_NATIVE") != "1" { + t.Skip("requires the private Xvfb/DBus/Fcitx seat fixture") + } + backend, path := os.Getenv("VIVA_FCITX_BACKEND"), os.Getenv("VIVA_GTK_SEAT_DRIVER") + if (backend != "x11" && backend != "wayland") || path == "" || os.Getenv("VIVA_GTK_IME_NATIVE") != "1" || os.Getenv("VIVA_ACCESSIBILITY") == "0" { + t.Fatal("native seat fixture is missing its backend, driver or GTK/accessibility settings") + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("native seat driver: %v", err) + } + connection, err := dbus.DialSession() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { connection.Close() }) + restoreA11yStatus(t, connection, "IsEnabled") + var status dbus.Encoder + status.String(a11yStatus) + status.String("IsEnabled") + status.Variant("b") + status.Bool(true) + if _, err := connection.Call(a11yBusName, a11yBusPath, dbusProperties, "Set", "ssv", status.Bytes()); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) + defer cancel() + p := >kTentativeProbe{tentative: true} + gtkTentativeProbeActive = p + defer func() { gtkTentativeProbeActive = nil }() + result := make(chan []string, 1) + pointers := gtkSeatPointer{} + err = RunGTKApplication(func(application platform.Application) error { + a := application.(*gtkApplication) + window, openErr := application.OpenWindow(platform.Config{ + Title: "Viva seat keyboard probe", Width: 800, Height: 600, WindowMode: platform.WindowFrameless, + ClearColor: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + DynamicTextInput: true, + Accessibility: []platform.AccessibilityNode{{ + ID: gfx.Item(1), Role: platform.A11yRoleTextField, Label: "Seat editor", + X: 20, Y: 20, Width: 300, Height: 100, Focusable: true, + }}, + OnAccessibility: func(request platform.AccessibilityRequest, _ func(platform.Frame) error) (bool, error) { + return request.Node == gfx.Item(1) && request.Action == platform.AccessibilityFocus, nil + }, + OnPointer: func(event platform.PointerEvent) (platform.Frame, error) { + if event.Kind == platform.PointerDown { + pointers.downs++ + pointers.clickCount = event.ClickCount + } + return platform.Frame{}, nil + }, + OnRedraw: func() (platform.Frame, error) { return platform.Frame{}, nil }, + }) + if openErr != nil { + return openErr + } + p.w = window.(*gtkWindow) + actual := typeNameOf(a.g, a.g.gdkDisplayDefault()) + want := "GdkX11Display" + if backend == "wayland" { + want = "GdkWaylandDisplay" + } + if actual != want { + p.w.destroy() + return fmt.Errorf("GTK native seat backend=%s, want %s", actual, want) + } + if backend == "wayland" && p.w.wl == nil || backend == "x11" && p.w.wl != nil { + p.w.destroy() + return fmt.Errorf("native content surface does not match %s", backend) + } + a.enqueue(func() { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + result <- []string{"editor refused tentative composition"} + p.w.destroy() + return + } + p.install(editor) + go func() { + failures := gtkSeatRun(ctx, t, a, p, &pointers, backend, path, remap) + result <- failures + a.enqueue(func() { p.w.destroy() }) + }() + }) + return nil + }) + if err != nil { + t.Fatal(err) + } + select { + case failures := <-result: + for _, failure := range failures { + t.Error(failure) + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } +} diff --git a/internal/platform/linux/gtk_wayland_linux.go b/internal/platform/linux/gtk_wayland_linux.go index 908506810..820c446b3 100644 --- a/internal/platform/linux/gtk_wayland_linux.go +++ b/internal/platform/linux/gtk_wayland_linux.go @@ -42,8 +42,9 @@ type wlSession struct { pressed uint32 // pointer buttons down, by GDK button number axis wlAxis - surfaceOf func(window uintptr) uintptr - modifiers func(keymap uintptr) uint32 + surfaceOf func(window uintptr) uintptr + customSurface func(window uintptr) + modifiers func(keymap uintptr) uint32 } // wlAxis collects the axis events of one wl_pointer.frame. @@ -91,6 +92,7 @@ func openWaylandSession(g *gtkLibrary) (*wlSession, error) { }{ {&displayOf, "gdk_wayland_display_get_wl_display"}, {&s.surfaceOf, "gdk_wayland_window_get_wl_surface"}, + {&s.customSurface, "gdk_wayland_window_set_use_custom_surface"}, {&seatOf, "gdk_wayland_seat_get_wl_seat"}, {&s.modifiers, "gdk_keymap_get_modifier_state"}, } { @@ -328,6 +330,7 @@ type waylandSurface struct { id uintptr parent, child, sub, viewport, fractional uintptr + gdkWindow uintptr scale120 uint32 offsetX, offsetY int32 viewportWidth, viewportHeight int32 @@ -363,21 +366,50 @@ func (s *waylandSurface) mapped(w *gtkWindow, on bool) { return } if s.child == 0 { - s.attach() + if err := s.attach(); err != nil { + w.app.fail(err) + } } } -func (s *waylandSurface) attach() { +func (s *waylandSurface) attach() error { session, c, w := s.s, s.s.c, s.w gdkWindow := w.g.widgetGetWindow(w.toplevel) if gdkWindow == 0 { - return + return fmt.Errorf("linux: Wayland parent GDK window is unavailable") } s.parent = session.surfaceOf(gdkWindow) if s.parent == 0 { - return + return fmt.Errorf("linux: Wayland parent surface is unavailable") + } + // GDK must know the surface that receives the compositor's keyboard focus. + // It owns the wl_surface; Viva owns its subsurface role and the picture attached to it. + const gdkWindowSubsurface = 6 + attrs := gdkWindowAttr{ + EventMask: gdkKeyPressMask | gdkKeyReleaseMask | gdkFocusChangeMask, + X: s.offsetX, + Y: s.offsetY, + Width: max(int32(w.width+0.5), 1), + Height: max(int32(w.height+0.5), 1), + WindowType: gdkWindowSubsurface, + } + s.gdkWindow = w.g.gdkWindowNew(gdkWindow, &attrs, 1<<2|1<<3) // GDK_WA_X | GDK_WA_Y + if s.gdkWindow == 0 { + s.parent = 0 + return fmt.Errorf("linux: cannot create the GDK Wayland content window") + } + w.g.widgetRegisterWindow(w.area, s.gdkWindow) + session.customSurface(s.gdkWindow) // map must not assign a second Wayland role or attach a buffer + w.g.gdkWindowTransient(s.gdkWindow, gdkWindow) + w.g.gdkWindowShow(s.gdkWindow) + s.child = session.surfaceOf(s.gdkWindow) + if s.child == 0 { + w.g.widgetUnregisterWindow(w.area, s.gdkWindow) + w.g.gdkWindowDestroy(s.gdkWindow) + s.gdkWindow = 0 + s.parent = 0 + return fmt.Errorf("linux: GDK content window has no Wayland surface") } - s.child = c.create(session.compositor, 0, c.core["wl_surface"], c.version(session.compositor), 0) s.sub = c.create(session.subcompositor, 1, c.core["wl_subsurface"], 1, 0, wlArg(s.child), wlArg(s.parent)) c.request(s.sub, 5) // set_desync: the window's content is committed on its own s.viewport = c.create(session.viewporter, 1, c.viewport, 1, 0, wlArg(s.child)) @@ -392,6 +424,7 @@ func (s *waylandSurface) attach() { s.resized(w) // A new subsurface takes effect with the next commit of its parent: make GTK draw once more. w.g.widgetQueueDraw(w.toplevel) + return nil } func (s *waylandSurface) detach() { @@ -413,7 +446,9 @@ func (s *waylandSurface) detach() { } c.destroy(s.viewport, 0) c.destroy(s.sub, 0) - c.destroy(s.child, 0) + s.w.g.widgetUnregisterWindow(s.w.area, s.gdkWindow) + s.w.g.gdkWindowDestroy(s.gdkWindow) // also destroys the borrowed wl_surface + s.gdkWindow = 0 s.viewport, s.sub, s.child, s.parent = 0, 0, 0, 0 c.flush(session.display) } @@ -428,6 +463,7 @@ func (s *waylandSurface) close() { func (s *waylandSurface) positioned(x, y int32) { s.offsetX, s.offsetY = x, y if s.child != 0 { + s.w.g.gdkWindowMoveResize(s.gdkWindow, x, y, max(int32(s.w.width+0.5), 1), max(int32(s.w.height+0.5), 1)) s.s.c.request(s.sub, 1, wlArg(uint32(x)), wlArg(uint32(y))) s.w.g.widgetQueueDraw(s.w.toplevel) } @@ -454,6 +490,7 @@ func (s *waylandSurface) resized(w *gtkWindow) { } s.buffers = nil width, height := int32(w.width+0.5), int32(w.height+0.5) + w.g.gdkWindowMoveResize(s.gdkWindow, s.offsetX, s.offsetY, max(width, 1), max(height, 1)) s.regionWidth, s.regionHeight = 0, 0 s.updateRegions(w, width, height) s.present(w) @@ -493,13 +530,16 @@ func (s *waylandSurface) updateRegions(w *gtkWindow, width, height int32) { c.request(s.viewport, 2, wlArg(uint32(width)), wlArg(uint32(height))) } region := c.create(s.s.compositor, 1, c.core["wl_region"], c.version(s.s.compositor), 0) + gdkRegion := w.g.cairoRegionRect(&[4]int32{0, 0, width, height}) add := func(x, y, rectWidth, rectHeight int32) { c.request(region, 1, wlArg(uint32(x)), wlArg(uint32(y)), wlArg(uint32(rectWidth)), wlArg(uint32(rectHeight))) + w.g.cairoRegionUnion(gdkRegion, &[4]int32{x, y, rectWidth, rectHeight}) } remove := func(x, y, rectWidth, rectHeight int32) { c.request(region, 2, wlArg(uint32(x)), wlArg(uint32(y)), wlArg(uint32(rectWidth)), wlArg(uint32(rectHeight))) + w.g.cairoRegionSubtract(gdkRegion, &[4]int32{x, y, rectWidth, rectHeight}) } - add(0, 0, width, height) + c.request(region, 1, 0, 0, wlArg(uint32(width)), wlArg(uint32(height))) if w.config.WindowMode == platform.WindowCustomTitlebar && !w.fullscreen.Load() { strip := int32(w.config.TitlebarStrip() + 0.999) remove(0, 0, width, min(strip, height)) @@ -519,6 +559,8 @@ func (s *waylandSurface) updateRegions(w *gtkWindow, width, height int32) { remove(holes[i], holes[i+1], holes[i+2]-holes[i], holes[i+3]-holes[i+1]) i += 4 } + w.g.gdkWindowInputShape(s.gdkWindow, gdkRegion, 0, 0) + w.g.cairoRegionDestroy(gdkRegion) c.request(s.child, 5, wlArg(region)) // set_input_region c.destroy(region, 0) } @@ -646,9 +688,24 @@ func (s *waylandSurface) present(w *gtkWindow) { } b.pending = render.Scissor{} damage = area + if c.version(s.child) < 4 && (s.viewportWidth <= 0 || s.viewportHeight <= 0 || canvas.Width <= 0 || canvas.Height <= 0) { + // updateRegions sets the viewport and repeats the frame later. Until then, skip the frame: the + // buffer copied above is up to date, and the other buffers keep the damage still to be shown. + return + } b.busy = true c.request(s.child, 1, wlArg(b.buffer), 0, 0) // attach - c.request(s.child, 9, wlArg(uint32(damage.Left)), wlArg(uint32(damage.Top)), wlArg(uint32(damage.Right-damage.Left)), wlArg(uint32(damage.Bottom-damage.Top))) + if c.version(s.child) >= 4 { + c.request(s.child, 9, wlArg(uint32(damage.Left)), wlArg(uint32(damage.Top)), wlArg(uint32(damage.Right-damage.Left)), wlArg(uint32(damage.Bottom-damage.Top))) // damage_buffer + } else { + // GDK can create a v3 surface. Damage is then in logical surface coordinates, + // after the viewport has mapped the canvas to the window's size. + left := int32(math.Floor(float64(damage.Left) * float64(s.viewportWidth) / float64(canvas.Width))) + top := int32(math.Floor(float64(damage.Top) * float64(s.viewportHeight) / float64(canvas.Height))) + right := int32(math.Ceil(float64(damage.Right) * float64(s.viewportWidth) / float64(canvas.Width))) + bottom := int32(math.Ceil(float64(damage.Bottom) * float64(s.viewportHeight) / float64(canvas.Height))) + c.request(s.child, 2, wlArg(uint32(left)), wlArg(uint32(top)), wlArg(uint32(right-left)), wlArg(uint32(bottom-top))) // damage + } c.request(s.child, 6) // commit c.flush(s.s.display) } diff --git a/internal/platform/linux/gtk_wayland_regions_native_linux_test.go b/internal/platform/linux/gtk_wayland_regions_native_linux_test.go new file mode 100644 index 000000000..cf573439d --- /dev/null +++ b/internal/platform/linux/gtk_wayland_regions_native_linux_test.go @@ -0,0 +1,508 @@ +//go:build linux && vivagtk + +package linux + +import ( + "context" + "fmt" + "os" + "testing" + "time" + + "github.com/ebitengine/purego" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/dbus" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" + "github.com/vivaui/viva/text" +) + +type gtkRegionProbe struct { + w *gtkWindow + entry uintptr + getFocus func(uintptr) uintptr + contentClicks, titlePresses int + edgePresses, resizeCalls int + entryButtons int + topIn, topOut int + areaIn, areaOut int + entryIn, entryOut int + resizeEdge int32 +} + +type gtkRegionState struct { + mapped, childPointer, focused, nativeKeys, imeActive bool + webFocus uintptr + gtkFocus uintptr + contentClicks, titlePresses, edgePresses int + entryButtons int + topIn, topOut, areaIn, areaOut int + entryIn, entryOut int + resizeCalls int + resizeEdge int32 + gdkPointer, gtkArea uintptr + gdkX, gdkY int32 + scale float32 + canvasWidth, viewportWidth, views, overlays int +} + +func gtkRegionSnapshot(ctx context.Context, app *gtkApplication, probe *gtkRegionProbe) (gtkRegionState, error) { + answer := make(chan gtkRegionState, 1) + app.enqueue(func() { + w := probe.w + state := gtkRegionState{ + mapped: w.wl != nil && w.wl.child != 0, + childPointer: w.wl != nil && w.wl.s.focus == w.wl, + focused: w.focused, + nativeKeys: w.nativeKeys, + webFocus: w.webFocus, + imeActive: w.ime != nil && w.ime.active, + contentClicks: probe.contentClicks, + titlePresses: probe.titlePresses, + edgePresses: probe.edgePresses, + entryButtons: probe.entryButtons, + topIn: probe.topIn, + topOut: probe.topOut, + areaIn: probe.areaIn, + areaOut: probe.areaOut, + entryIn: probe.entryIn, + entryOut: probe.entryOut, + resizeCalls: probe.resizeCalls, + resizeEdge: probe.resizeEdge, + scale: w.scale, + canvasWidth: w.scene.canvas.Width, + viewportWidth: int(w.wl.viewportWidth), + views: len(w.scene.views), + } + device := w.g.gdkSeatPointer(w.g.gdkDisplaySeat(w.g.gdkDisplayDefault())) + state.gdkPointer = w.g.gdkDeviceWindowAt(device, &state.gdkX, &state.gdkY) + state.gtkArea = w.g.widgetGetWindow(w.area) + if state.views > 0 { + state.overlays = len(w.scene.overlays(0)) + } + if probe.getFocus != nil { + state.gtkFocus = probe.getFocus(w.toplevel) + } + answer <- state + }) + select { + case state := <-answer: + return state, nil + case <-ctx.Done(): + return gtkRegionState{}, ctx.Err() + } +} + +func gtkRegionWait(ctx context.Context, app *gtkApplication, probe *gtkRegionProbe, label string, check func(gtkRegionState) bool) error { + deadline := time.NewTimer(2 * time.Second) + defer deadline.Stop() + for { + state, err := gtkRegionSnapshot(ctx, app, probe) + if err != nil { + return fmt.Errorf("%s: %w", label, err) + } + if check(state) { + return nil + } + select { + case <-deadline.C: + return fmt.Errorf("%s: deadline; state=%+v", label, state) + case <-ctx.Done(): + return fmt.Errorf("%s: %w", label, ctx.Err()) + case <-time.After(10 * time.Millisecond): + } + } +} + +func gtkRegionOnLoop(ctx context.Context, app *gtkApplication, change func()) error { + done := make(chan struct{}, 1) + app.enqueue(func() { + change() + done <- struct{}{} + }) + select { + case <-done: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func gtkRegionSelectPinyin(ctx context.Context, app *gtkApplication, probe *gtkRegionProbe) error { + deadline := time.NewTimer(3 * time.Second) + defer deadline.Stop() + for { + active, err := nativeFcitxCommand("--check", "-n") + if err != nil { + return err + } + if active != "" { + return selectNativeFcitxEngine("pinyin") + } + select { + case <-deadline.C: + state, stateErr := gtkRegionSnapshot(ctx, app, probe) + check, checkErr := nativeFcitxCommand("--check") + return fmt.Errorf("Fcitx client did not register the focused native window: GTK=%+v snapshotErr=%v fcitx --check=%q checkErr=%v", state, stateErr, check, checkErr) + case <-ctx.Done(): + return ctx.Err() + case <-time.After(20 * time.Millisecond): + } + } +} + +func gtkRegionFailureTrace(ctx context.Context, app *gtkApplication, probe *gtkRegionProbe, p *gtkTentativeProbe) string { + answer := make(chan string, 1) + app.enqueue(func() { + w := probe.w + signals := p.signals[max(0, len(p.signals)-12):] + events := make([]string, 0, min(len(p.events), 12)) + for _, event := range p.events[max(0, len(p.events)-12):] { + events = append(events, fmt.Sprintf("kind=%d phase=%d text=%q", event.Kind, event.CompositionPhase, event.Text)) + } + ime := w.ime + if ime == nil { + answer <- fmt.Sprintf("signals(%d)=%q events(%d)=%v editor=%q IME unavailable closed=%t", len(p.signals), signals, len(p.events), events, p.editor.String(), w.closed) + return + } + answer <- fmt.Sprintf("signals(%d)=%q events(%d)=%v editor=%q selection=%+v focused=%t nativeKeys=%t webFocus=%#x focusSerial=%d top=%d/%d area=%d/%d entry=%d/%d imeActive=%t imeFocused=%t session=%t ending=%t engineComposing=%t nativeDepth=%d", + len(p.signals), signals, len(p.events), events, p.editor.String(), p.editor.Selection(), w.focused, w.nativeKeys, w.webFocus, w.focusSerial, + probe.topIn, probe.topOut, probe.areaIn, probe.areaOut, probe.entryIn, probe.entryOut, + ime.active, ime.focused, ime.session, ime.ending, ime.engineComposing, ime.nativeDepth) + }) + select { + case trace := <-answer: + return trace + case <-ctx.Done(): + return fmt.Sprintf("failure trace unavailable: %v", ctx.Err()) + } +} + +func gtkRegionRun(ctx context.Context, app *gtkApplication, probe *gtkRegionProbe, p *gtkTentativeProbe, path string) (err error) { + driver, err := newGTKSeatDriver(ctx, path) + if err != nil { + return err + } + defer func() { + if closeErr := driver.close(); err == nil && closeErr != nil { + err = closeErr + } + }() + if err := gtkRegionWait(ctx, app, probe, "content and native-view hole mapped", func(s gtkRegionState) bool { + return s.mapped && s.views == 1 && s.viewportWidth == 800 && s.imeActive + }); err != nil { + return err + } + for _, op := range []string{"bind", "focus", "grab"} { + if _, err := driver.command(op, "", "wayland"); err != nil { + return err + } + } + if err := gtkRegionWait(ctx, app, probe, "GTK parent focused", func(s gtkRegionState) bool { + return s.focused && s.imeActive + }); err != nil { + return err + } + if err := gtkRegionSelectPinyin(ctx, app, probe); err != nil { + return fmt.Errorf("initial Viva parent engine: %w", err) + } + if _, err := driver.commandAt("move", 120, 60); err != nil { + return err + } + if err := gtkRegionWait(ctx, app, probe, "GDK titlebar coordinate origin", func(s gtkRegionState) bool { + return s.gdkPointer == s.gtkArea && s.gdkX >= 0 && s.gdkY >= 0 + }); err != nil { + return err + } + position, err := gtkRegionSnapshot(ctx, app, probe) + if err != nil { + return err + } + originX, originY := 120-int(position.gdkX), 60-int(position.gdkY) + moveClick := func(label string, x, y int, childPointer bool, check func(gtkRegionState) bool) error { + if _, err := driver.commandAt("move", x+originX, y+originY); err != nil { + return fmt.Errorf("%s: %w", label, err) + } + if err := gtkRegionWait(ctx, app, probe, label+" pointer target", func(s gtkRegionState) bool { + return s.childPointer == childPointer + }); err != nil { + return err + } + if _, err := driver.commandAt("click-at", x+originX, y+originY); err != nil { + return fmt.Errorf("%s: %w", label, err) + } + return gtkRegionWait(ctx, app, probe, label, check) + } + if err := moveClick("plain content", 250, 180, true, func(s gtkRegionState) bool { + return s.childPointer && s.contentClicks == 1 && !s.nativeKeys && s.imeActive + }); err != nil { + return err + } + if err := moveClick("GTK titlebar strip", 120, 60, false, func(s gtkRegionState) bool { + return !s.childPointer && s.titlePresses == 1 && s.contentClicks == 1 + }); err != nil { + return err + } + if err := moveClick("GTK left resize edge", 2, 180, false, func(s gtkRegionState) bool { + return !s.childPointer && s.edgePresses == 1 && s.resizeCalls == 1 && s.resizeEdge == 3 && s.contentClicks == 1 + }); err != nil { + return err + } + if err := moveClick("GtkEntry in native-view hole", 500, 300, false, func(s gtkRegionState) bool { + return !s.childPointer && s.webFocus == probe.entry && s.gtkFocus == probe.entry && s.nativeKeys && !s.imeActive && s.contentClicks == 1 && s.entryButtons == 1 + }); err != nil { + return err + } + if err := moveClick("Viva cover inside native-view hole", 440, 240, true, func(s gtkRegionState) bool { + return s.childPointer && s.webFocus == 0 && s.gtkFocus == 0 && !s.nativeKeys && s.imeActive && s.contentClicks == 2 && s.entryButtons == 1 + }); err != nil { + return err + } + if err := gtkRegionOnLoop(ctx, app, func() { + probe.w.wl.preferredScale(180) // a 1.5x canvas mapped onto the same 800 logical pixels + probe.w.present(platform.Frame{ + Rectangles: []render.Rectangle{{ + Kind: scene.KindRectangle, Bounds: scene.Rect{X: 510, Y: 235, Width: 40, Height: 40}, + Color: scene.Color{Red: 1, Alpha: 1}, Layer: 2, + }}, + Update: render.Update{Count: 1, Rebuild: true}, + }, nil) + }); err != nil { + return err + } + if err := gtkRegionWait(ctx, app, probe, "fractional canvas and overlay", func(s gtkRegionState) bool { + return s.scale == 1.5 && s.canvasWidth == 1200 && s.viewportWidth == 800 && s.overlays > 0 + }); err != nil { + return err + } + if err := moveClick("1.5x uncovered GtkEntry", 500, 300, false, func(s gtkRegionState) bool { + return !s.childPointer && s.webFocus == probe.entry && s.gtkFocus == probe.entry && s.nativeKeys && !s.imeActive && s.contentClicks == 2 && s.entryButtons == 2 + }); err != nil { + return err + } + if err := gtkRegionSelectPinyin(ctx, app, probe); err != nil { + return fmt.Errorf("GtkEntry engine before scaled native-to-Viva click: %w", err) + } + entryEngine, entryEngineErr := nativeFcitxCommand("--check", "-n") + before, err := gtkSeatState(ctx, app, p, >kSeatPointer{}) + if err != nil { + return err + } + if _, err := driver.commandAt("move", 530+originX, 250+originY); err != nil { + return err + } + if err := gtkRegionWait(ctx, app, probe, "1.5x drawn overlay pointer target", func(s gtkRegionState) bool { + return s.childPointer + }); err != nil { + return err + } + if _, err := driver.commandAt("click-at", 530+originX, 250+originY); err != nil { + return err + } + var beforeKeyEngine, beforeKeyStatus string + if os.Getenv("VIVA_GTK_REGION_ENGINE_DIAG") == "1" { + beforeKeyEngine, _ = nativeFcitxCommand("--check", "-n") + beforeKeyStatus, _ = nativeFcitxCommand("--check") + } + for _, op := range []string{"down", "up"} { + if _, err := driver.command(op, "n", ""); err != nil { + return err + } + } + afterKeyEngine, afterKeyEngineErr := nativeFcitxCommand("--check", "-n") + afterKeyStatus, afterKeyStatusErr := nativeFcitxCommand("--check") + if err := gtkRegionWait(ctx, app, probe, "1.5x drawn overlay returns pointer to Viva", func(s gtkRegionState) bool { + return s.childPointer && s.webFocus == 0 && s.gtkFocus == 0 && !s.nativeKeys && s.imeActive && s.contentClicks == 3 && s.entryButtons == 2 + }); err != nil { + return err + } + if err := gtkSeatWait(ctx, app, p, >kSeatPointer{}, "immediate key after 1.5x native-to-Viva click", func(s gtkSeatSnapshot) bool { + return s.preeditSignals > before.preeditSignals && s.preeditEvents > before.preeditEvents && s.pressedKeys == 0 && s.composing + }); err != nil { + return fmt.Errorf("%w; Entry engine=%q (%v), before key engine/status=%q/%q, after key engine/status=%q/%q (%v/%v); %s", err, + entryEngine, entryEngineErr, beforeKeyEngine, beforeKeyStatus, afterKeyEngine, afterKeyStatus, afterKeyEngineErr, afterKeyStatusErr, + gtkRegionFailureTrace(ctx, app, probe, p)) + } + if err := gtkRegionOnLoop(ctx, app, func() {}); err != nil { + return err + } + after, err := gtkSeatState(ctx, app, p, >kSeatPointer{}) + if err != nil { + return err + } + if !after.composing || !after.imeActive || after.cancelEvents != before.cancelEvents || after.preeditEvents <= before.preeditEvents { + return fmt.Errorf("immediate preedit was lost after the focus handoff: before=%+v after=%+v", before, after) + } + return nil +} + +// The seat enters a GDK-owned content surface, GTK titlebar, and native-view hole through real +// Weston/XTest pointer events. GtkEntry stands in for WebKit's GTK widget without loading WebKit. +func TestGTKNativeWaylandInputRegions(t *testing.T) { + if os.Getenv("VIVA_GTK_REGION_NATIVE") != "1" || os.Getenv("VIVA_FCITX_BACKEND") != "wayland" { + t.Skip("requires the private Wayland GTK input-region fixture") + } + path := os.Getenv("VIVA_GTK_SEAT_DRIVER") + if path == "" || os.Getenv("VIVA_GTK_SEAT_NATIVE") != "1" || os.Getenv("VIVA_GTK_IME_NATIVE") != "1" || os.Getenv("VIVA_ACCESSIBILITY") == "0" { + t.Fatal("native input-region fixture is missing its seat driver or GTK/accessibility settings") + } + if _, err := os.Stat(path); err != nil { + t.Fatal(err) + } + connection, err := dbus.DialSession() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { connection.Close() }) + restoreA11yStatus(t, connection, "IsEnabled") + var status dbus.Encoder + status.String(a11yStatus) + status.String("IsEnabled") + status.Variant("b") + status.Bool(true) + if _, err := connection.Call(a11yBusName, a11yBusPath, dbusProperties, "Set", "ssv", status.Bytes()); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) + defer cancel() + p := >kTentativeProbe{tentative: true} + gtkTentativeProbeActive = p + defer func() { gtkTentativeProbeActive = nil }() + probe := >kRegionProbe{} + result := make(chan error, 1) + var app *gtkApplication + var originalResize func(uintptr, int32, int32, int32, int32, uint32) + err = RunGTKApplication(func(application platform.Application) error { + app = application.(*gtkApplication) + host := &platform.WebHost{} + window, openErr := application.OpenWindow(platform.Config{ + Title: "Viva seat keyboard probe", Width: 800, Height: 600, + WindowMode: platform.WindowCustomTitlebar, TitlebarHeight: 80, + ClearColor: platform.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, + Web: host, DynamicTextInput: true, + NativeViews: []platform.NativeView{{ + ID: 7, Bounds: gfx.Rect{X: 420, Y: 220, Width: 160, Height: 120}, Layer: 1, + Covers: []gfx.Rect{{X: 420, Y: 220, Width: 40, Height: 40}}, + }}, + Accessibility: []platform.AccessibilityNode{{ + ID: gfx.Item(1), Role: platform.A11yRoleTextField, Label: "Seat editor", + X: 20, Y: 20, Width: 300, Height: 100, Focusable: true, + }}, + OnAccessibility: func(request platform.AccessibilityRequest, _ func(platform.Frame) error) (bool, error) { + return request.Node == gfx.Item(1) && request.Action == platform.AccessibilityFocus, nil + }, + PressAt: func(x, y float32) platform.PressKind { + if x >= 80 && x < 160 && y >= 50 && y < 70 { + probe.titlePresses++ + } + if x >= 0 && x < 6 && y >= 160 && y < 200 { + probe.edgePresses++ + } + if y < 80 { + return platform.PressMove + } + return platform.PressClient + }, + OnPointer: func(event platform.PointerEvent) (platform.Frame, error) { + if event.Kind == platform.PointerDown { + probe.contentClicks++ + } + return platform.Frame{}, nil + }, + OnRedraw: func() (platform.Frame, error) { return platform.Frame{}, nil }, + }) + if openErr != nil { + return openErr + } + probe.w = window.(*gtkWindow) + if typeNameOf(app.g, app.g.gdkDisplayDefault()) != "GdkWaylandDisplay" || probe.w.wl == nil || probe.w.overlay == 0 { + probe.w.destroy() + return fmt.Errorf("input-region test requires the Wayland subsurface and GtkOverlay") + } + var entryNew func() uintptr + if !app.g.lookup(&entryNew, "gtk_entry_new") { + probe.w.destroy() + return fmt.Errorf("GTK input-region fixture lacks GtkEntry") + } + probe.entry = entryNew() + if probe.entry == 0 { + probe.w.destroy() + return fmt.Errorf("GTK cannot create the input-region GtkEntry") + } + g := app.g + if !g.lookup(&probe.getFocus, "gtk_window_get_focus") { + probe.w.destroy() + return fmt.Errorf("GTK input-region fixture lacks gtk_window_get_focus") + } + g.widgetSetHAlign(probe.entry, 1) + g.widgetSetVAlign(probe.entry, 1) + g.widgetSetMarginX(probe.entry, 420) + g.widgetSetMarginY(probe.entry, 220) + g.widgetSetSize(probe.entry, 160, 120) + g.overlayAdd(probe.w.overlay, probe.entry) + g.connect(probe.entry, "focus-in-event", callbacks().event, probe.w.id) + g.connect(probe.entry, "focus-out-event", callbacks().event, probe.w.id) + for _, target := range []struct { + widget uintptr + in, out *int + }{ + {probe.w.toplevel, &probe.topIn, &probe.topOut}, + {probe.w.area, &probe.areaIn, &probe.areaOut}, + {probe.entry, &probe.entryIn, &probe.entryOut}, + } { + in, out := target.in, target.out + g.connect(target.widget, "focus-in-event", purego.NewCallback(func(_, _, _ uintptr) uintptr { + (*in)++ + return 0 + }), 0) + g.connect(target.widget, "focus-out-event", purego.NewCallback(func(_, _, _ uintptr) uintptr { + (*out)++ + return 0 + }), 0) + } + g.connect(probe.entry, "button-press-event", purego.NewCallback(func(_, _, _ uintptr) uintptr { + probe.entryButtons++ + return 0 + }), 0) + g.widgetShow(probe.entry) + originalResize = g.windowBeginResize + g.windowBeginResize = func(window uintptr, edge, button, rootX, rootY int32, timestamp uint32) { + if window == probe.w.toplevel { + probe.resizeCalls++ + probe.resizeEdge = edge + return // keep the test window fixed while checking the native edge path + } + originalResize(window, edge, button, rootX, rootY, timestamp) + } + app.enqueue(func() { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + result <- fmt.Errorf("region editor refused tentative composition") + probe.w.destroy() + return + } + p.w = probe.w + p.install(editor) + go func() { + result <- gtkRegionRun(ctx, app, probe, p, path) + app.enqueue(func() { probe.w.destroy() }) + }() + }) + return nil + }) + if originalResize != nil { + app.g.windowBeginResize = originalResize + } + if err != nil { + t.Fatal(err) + } + select { + case err := <-result: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } +} diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index ca8504ed1..698c83ac5 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -30,9 +30,10 @@ type gtkWindow struct { toplevel, area uintptr // overlay holds the area and the web pages above it; it exists when the application may open pages. - overlay uintptr - ime *gtkIME - wl *waylandSurface + overlay uintptr + ime *gtkIME + wl *waylandSurface + pointerCapture uintptr // unit is the device pixels in one unit of the widget's size: GTK's own scale on X11, where // the drawing area is the canvas; 1 on Wayland, where the area holds no pixels. scale is Viva's @@ -46,11 +47,12 @@ type gtkWindow struct { allocated0 bool cairoSurface uintptr - frame atomic.Pointer[gfx.Rect] - maximized bool - fullscreen atomic.Bool - minimized bool - focused bool + frame atomic.Pointer[gfx.Rect] + maximized bool + fullscreen atomic.Bool + minimized bool + focused bool + focusSerial uint64 // coalesces GDK focus transfers between a Wayland parent and its child regionsDirty bool // dragging and dropping follow a drag of files over the window. @@ -171,6 +173,15 @@ func (a *gtkApplication) OpenWindow(config platform.Config) (platform.Window, er for _, signal := range []string{"button-press-event", "button-release-event", "motion-notify-event", "enter-notify-event", "leave-notify-event", "scroll-event"} { g.connect(w.area, signal, cb.event, data) } + if a.wayland { + g.widgetAddEvents(w.area, gdkKeyPressMask|gdkKeyReleaseMask|gdkFocusChangeMask) + for _, signal := range []string{"key-press-event", "key-release-event", "focus-in-event", "focus-out-event"} { + g.connect(w.area, signal, cb.event, data) + } + w.pointerCapture = g.gestureMultiPressNew(w.toplevel) + g.controllerSetPhase(w.pointerCapture, 1) // GTK_PHASE_CAPTURE + g.connect(w.pointerCapture, "begin", cb.capturePress, data) + } for _, signal := range []string{"key-press-event", "key-release-event", "focus-in-event", "focus-out-event", "window-state-event", "configure-event"} { g.connect(w.toplevel, signal, cb.event, data) } @@ -222,6 +233,11 @@ func (a *gtkApplication) OpenWindow(config platform.Config) (platform.Window, er }) } g.widgetShowAll(w.toplevel) + if a.firstErr != nil { + err := a.firstErr + w.destroy() + return nil, err + } return w, nil } @@ -416,6 +432,10 @@ func (w *gtkWindow) cleanup() { w.wl.close() w.wl = nil } + if w.pointerCapture != 0 { + w.g.objectUnref(w.pointerCapture) + w.pointerCapture = 0 + } w.releaseSurface() if w.scene != nil { w.scene.close() @@ -442,6 +462,20 @@ func (w *gtkWindow) closeRequested() bool { // mapChanged is the window being shown or hidden. func (w *gtkWindow) mapChanged(on bool) { + if !on && w.wl != nil { + // GDK can unmap the parent before reporting a focus-out for its child. + // End this IM session before the parent's Wayland surface is replaced. + // This runs inside GTK's unmap emission, where a panel must not be + // destroyed: Hide keeps the window for Show, so only the keyboard state + // changes here. A focus-out that GDK reports later finds the state + // already changed and does nothing. + w.focusSerial++ + if w.focused { + w.setKeyboard(false) + } + *w.pointer.clicks = input.ClickCounter{} + w.pointer.pending, w.pointer.pendingDelivery = false, false + } if on && w.originPending { // The window manager decorates the window after it is mapped; its frame is known a moment // later. From c99de9204f9613bd1531b65884a3c9e0980d5983 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 00:44:04 +0800 Subject: [PATCH 13/23] feat(ui): add MenuItems.Content for a row the caller paints --- cmd/viva/templates/avatar_editor.go.txt | 32 ++++++++---------------- cmd/viva/templates/context_menu.go.txt | 4 +++ cmd/viva/templates/dropdown_menu.go.txt | 15 +++++++++++ components/context_menu.go | 4 +++ components/dropdown_menu.go | 15 +++++++++++ ui/caption.go | 1 + ui/menu.go | 33 +++++++++++++++++++++++-- ui/menu_test.go | 31 +++++++++++++++++++++++ 8 files changed, 111 insertions(+), 24 deletions(-) diff --git a/cmd/viva/templates/avatar_editor.go.txt b/cmd/viva/templates/avatar_editor.go.txt index 345c673dc..5d4794b69 100644 --- a/cmd/viva/templates/avatar_editor.go.txt +++ b/cmd/viva/templates/avatar_editor.go.txt @@ -281,9 +281,13 @@ func avatarEditorPaintStage(c *gfx.Canvas, theme gfx.Theme, stage gfx.Rect, out border = theme.Ring } if circular { - c.DrawPath(avatarEditorCircleRingPath(), stage, gfx.PathStyle{Fill: border, FillRule: gfx.PathFillEvenOdd}) + // A stroke is centred on its path, so the path sits half a width inside + // the stage to keep the whole ring visible, as Avatar does. + half := avatarEditorBorderWidth / 2 + ring := gfx.Rect{X: stage.X + half, Y: stage.Y + half, Width: stage.Width - 2*half, Height: stage.Height - 2*half} + c.DrawPath(avatarEditorCircleFillPath(), ring, gfx.PathStyle{Stroke: border, StrokeWidth: avatarEditorBorderWidth}) } else { - c.RoundedBorder(stage, 0, 1.5, border, gfx.Color{}) + c.RoundedBorder(stage, 0, avatarEditorBorderWidth, border, gfx.Color{}) } c.Unclip() if !id.IsZero() { @@ -604,11 +608,14 @@ func avatarEditorPaintZoom(c *gfx.Canvas, theme gfx.Theme, id gfx.ID, bounds gfx }) } +// avatarEditorBorderWidth is the stage border's thickness in logical pixels. It +// is constant across stage sizes for both the rectangular and circular stage. +const avatarEditorBorderWidth float32 = 1.5 + var ( avatarEditorCirclePathsOnce sync.Once avatarEditorCircleMask gfx.Path avatarEditorCircleFill gfx.Path - avatarEditorCircleRing gfx.Path ) func avatarEditorCircleMaskPath() gfx.Path { @@ -616,11 +623,6 @@ func avatarEditorCircleMaskPath() gfx.Path { return avatarEditorCircleMask } -func avatarEditorCircleRingPath() gfx.Path { - avatarEditorCirclePathsOnce.Do(initAvatarEditorCirclePaths) - return avatarEditorCircleRing -} - func avatarEditorCircleFillPath() gfx.Path { avatarEditorCirclePathsOnce.Do(initAvatarEditorCirclePaths) return avatarEditorCircleFill @@ -647,20 +649,6 @@ func initAvatarEditorCirclePaths() { gfx.CubicTo(0, 22.386, 22.386, 0, 50, 0), gfx.ClosePath(), ) - avatarEditorCircleRing = gfx.NewPath(100, 100, - gfx.MoveTo(50, 0), - gfx.CubicTo(77.614, 0, 100, 22.386, 100, 50), - gfx.CubicTo(100, 77.614, 77.614, 100, 50, 100), - gfx.CubicTo(22.386, 100, 0, 77.614, 0, 50), - gfx.CubicTo(0, 22.386, 22.386, 0, 50, 0), - gfx.ClosePath(), - gfx.MoveTo(50, .4), - gfx.CubicTo(77.393, .4, 99.6, 22.607, 99.6, 50), - gfx.CubicTo(99.6, 77.393, 77.393, 99.6, 50, 99.6), - gfx.CubicTo(22.607, 99.6, .4, 77.393, .4, 50), - gfx.CubicTo(.4, 22.607, 22.607, .4, 50, .4), - gfx.ClosePath(), - ) } var avatarEditorZoomOutIcon = gfx.Icon{ diff --git a/cmd/viva/templates/context_menu.go.txt b/cmd/viva/templates/context_menu.go.txt index 8aa65ab90..e2541a51c 100644 --- a/cmd/viva/templates/context_menu.go.txt +++ b/cmd/viva/templates/context_menu.go.txt @@ -195,6 +195,10 @@ func (menu *ContextMenu) EndContent() { menu.surface.popOverlay() } // AddSeparator paints the official -mx-1/my-1 divider geometry. func (menu *ContextMenu) AddSeparator() gfx.Rect { return menu.surface.addSeparator() } +// AddContent reserves a row height tall, painted by the caller between BeginContent and +// EndContent. It is not an item: it takes no focus and no hit of its own. +func (menu *ContextMenu) AddContent(height float32) gfx.Rect { return menu.surface.addContent(height) } + // End paints the scrollbar of a menu whose items did not all fit, after the last // item: call it once the last item is painted. func (menu *ContextMenu) End() { menu.surface.end() } diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index e699fb29d..07f539885 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -283,6 +283,10 @@ func (menu *DropdownMenu) EndContent() { menu.surface.popOverlay() } // AddSeparator paints the official -mx-1/my-1 divider geometry. func (menu *DropdownMenu) AddSeparator() gfx.Rect { return menu.surface.addSeparator() } +// AddContent reserves a row height tall, painted by the caller between BeginContent and +// EndContent. It is not an item: it takes no focus and no hit of its own. +func (menu *DropdownMenu) AddContent(height float32) gfx.Rect { return menu.surface.addContent(height) } + // End paints the scrollbar of a menu whose items did not all fit, after the last // item, and ends the menu's entrance and exit: call it once the last item is // painted, or the menu appears and disappears at once. @@ -951,6 +955,17 @@ func (menu *menuSurface) addLabel(label string, inset bool) gfx.Rect { return row } +// addContent reserves a row height tall for the caller to paint into, which the menu +// paints nothing of; it is not an item and takes no focus. It returns the row, or the zero +// rectangle when scrolling has it out of sight. +func (menu *menuSurface) addContent(height float32) gfx.Rect { + row := menu.rowBounds(height) + if !menu.take(row) { + return gfx.Rect{} + } + return row +} + func (menu *menuSurface) addSeparator() gfx.Rect { row := gfx.Rect{X: menu.bounds.X, Y: menu.y, Width: menu.bounds.Width, Height: menuSeparatorHeight} if !menu.take(row) { diff --git a/components/context_menu.go b/components/context_menu.go index ced040f27..703a25661 100644 --- a/components/context_menu.go +++ b/components/context_menu.go @@ -195,6 +195,10 @@ func (menu *ContextMenu) EndContent() { menu.surface.popOverlay() } // AddSeparator paints the official -mx-1/my-1 divider geometry. func (menu *ContextMenu) AddSeparator() gfx.Rect { return menu.surface.addSeparator() } +// AddContent reserves a row height tall, painted by the caller between BeginContent and +// EndContent. It is not an item: it takes no focus and no hit of its own. +func (menu *ContextMenu) AddContent(height float32) gfx.Rect { return menu.surface.addContent(height) } + // End paints the scrollbar of a menu whose items did not all fit, after the last // item: call it once the last item is painted. func (menu *ContextMenu) End() { menu.surface.end() } diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index da05e0f22..04efc8585 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -283,6 +283,10 @@ func (menu *DropdownMenu) EndContent() { menu.surface.popOverlay() } // AddSeparator paints the official -mx-1/my-1 divider geometry. func (menu *DropdownMenu) AddSeparator() gfx.Rect { return menu.surface.addSeparator() } +// AddContent reserves a row height tall, painted by the caller between BeginContent and +// EndContent. It is not an item: it takes no focus and no hit of its own. +func (menu *DropdownMenu) AddContent(height float32) gfx.Rect { return menu.surface.addContent(height) } + // End paints the scrollbar of a menu whose items did not all fit, after the last // item, and ends the menu's entrance and exit: call it once the last item is // painted, or the menu appears and disappears at once. @@ -951,6 +955,17 @@ func (menu *menuSurface) addLabel(label string, inset bool) gfx.Rect { return row } +// addContent reserves a row height tall for the caller to paint into, which the menu +// paints nothing of; it is not an item and takes no focus. It returns the row, or the zero +// rectangle when scrolling has it out of sight. +func (menu *menuSurface) addContent(height float32) gfx.Rect { + row := menu.rowBounds(height) + if !menu.take(row) { + return gfx.Rect{} + } + return row +} + func (menu *menuSurface) addSeparator() gfx.Rect { row := gfx.Rect{X: menu.bounds.X, Y: menu.y, Width: menu.bounds.Width, Height: menuSeparatorHeight} if !menu.take(row) { diff --git a/ui/caption.go b/ui/caption.go index e31782d9a..10e743769 100644 --- a/ui/caption.go +++ b/ui/caption.go @@ -12,6 +12,7 @@ import ( // elements it does nothing. // // f.Checkbox(syncID, m.sync).Caption("Sync over SSH") +// // Mixed paints a Checkbox as neither on nor off, a dash in a filled box: the select-all of a // list of which only some rows are chosen. Declare it from the rows' state each paint; a // press still flips the bound value, so the application decides what the next state is. diff --git a/ui/menu.go b/ui/menu.go index 9c9e7fd5c..4afac0851 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -266,6 +266,8 @@ func (m *MenuItems) size() (width, height float32) { height += components.DropdownMenuSeparatorHeight case menuRowLabel: height += components.DropdownMenuLabelHeight + case menuRowContent: + height += item.height default: row := m.row(i) if m.context { @@ -306,6 +308,7 @@ const ( menuRowItem menuRowKind = iota menuRowLabel menuRowSeparator + menuRowContent ) // MenuItems is an open Menu or ContextMenu being declared: what its rows are, and, @@ -435,8 +438,10 @@ type menuRow struct { key gfx.Key destructive bool disabled bool - submenu bool // the row opens a submenu - checked int8 // 1 a checked checkbox, 2 an unchecked one, 3 a chosen radio, 4 an unchosen one + submenu bool // the row opens a submenu + height float32 // a content row's height + content func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) // what paints a content row + checked int8 // 1 a checked checkbox, 2 an unchecked one, 3 a chosen radio, 4 an unchosen one } // minWidth is shadcn's: 8rem for a DropdownMenu, 9rem for a ContextMenu. @@ -541,6 +546,26 @@ func (m *MenuItems) WidthRange(least, greatest float32) { m.widthMin, m.widthMax = least, greatest } +// Content adds a row height tall that body paints: the room for what a menu row cannot say, +// such as a strip of color swatches. It is not an item, so the keyboard passes over it; body +// takes the row's rectangle and declares its own hits, inside the menu's clip, and is not +// called while scrolling has the row out of sight. +func (m *MenuItems) Content(height float32, body func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme)) { + m.items = append(m.items, menuRow{kind: menuRowContent, height: height, content: body}) +} + +// paintContent calls a content row's painter over its row, inside the menu's clip. +func (m *MenuItems) paintContent(canvas *gfx.Canvas, theme gfx.Theme, row *menuRow, bounds gfx.Rect, begin, end func(), menu gfx.Rect) { + if bounds.Width <= 0 || row.content == nil { + return + } + begin() + canvas.Clip(gfx.Rect{X: menu.X, Y: menu.Y + components.DropdownMenuPadding/2, Width: menu.Width, Height: menu.Height - components.DropdownMenuPadding}) + row.content(canvas, bounds, theme) + canvas.Unclip() + end() +} + // Label adds a heading over the items that follow it. func (m *MenuItems) Label(label string) { m.items = append(m.items, menuRow{kind: menuRowLabel, label: label}) @@ -650,6 +675,8 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer menu.AddSeparator() case menuRowLabel: menu.AddLabel(row.label, false) + case menuRowContent: + m.paintContent(canvas, *theme, row, menu.AddContent(row.height), func() { menu.BeginContent() }, func() { menu.EndContent() }, menu.Bounds()) default: if r := menu.AddItem(contextItem(m.row(i))); i == m.sub { trigger = r @@ -683,6 +710,8 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer menu.AddSeparator() case menuRowLabel: menu.AddLabel(row.label, false) + case menuRowContent: + m.paintContent(canvas, *theme, row, menu.AddContent(row.height), func() { menu.BeginContent() }, func() { menu.EndContent() }, menu.Bounds()) default: if r := menu.AddItem(m.row(i)); i == m.sub { trigger = r diff --git a/ui/menu_test.go b/ui/menu_test.go index 72aa8bb18..860a0cb7b 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -604,3 +604,34 @@ func TestContextMenuAtNamedByAZeroSizeSlotTakesTheArrows(t *testing.T) { t.Fatalf("connected %q, open %v: the arrows did not reach the menu", m.connected, m.open) } } + +// A Content row takes room in the menu and is painted by the caller; the arrows pass over it. +func TestMenuContentRow(t *testing.T) { + m := &menuModel{open: true} + painted := gfx.Rect{} + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + more := ui.Button(c, "More") + ui.Menu(c, more, &m.open, func(menu *ui.MenuItems) { + menu.Item("One") + menu.Content(40, func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) { + painted = bounds + canvas.Hit(gfx.Item(77), bounds) + }) + if menu.Item("Two").Clicked() { + m.renamed++ + } + }) + }) + }) + one, two := d.hit("One").Bounds, d.hit("Two").Bounds + if painted.Height != 40 || two.Y-one.Y < 40 { + t.Fatalf("content %v, rows %v and %v: the row took no room", painted, one, two) + } + d.key(gfx.KeyDown) + d.key(gfx.KeyDown) + d.key(gfx.KeyEnter) + if m.renamed != 1 { + t.Fatalf("the arrows did not pass over the content row to Two (%d)", m.renamed) + } +} From c87661f9fd133b07d033146fed8a11d97dce0621 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 00:54:07 +0800 Subject: [PATCH 14/23] feat(ui): add MenuItem.Trailing for a control at a row's end --- ui/menu.go | 60 ++++++++++++++++++++++++++++++++++++++----------- ui/menu_test.go | 27 ++++++++++++++++++++++ 2 files changed, 74 insertions(+), 13 deletions(-) diff --git a/ui/menu.go b/ui/menu.go index 4afac0851..1048837a2 100644 --- a/ui/menu.go +++ b/ui/menu.go @@ -433,15 +433,17 @@ type menuRow struct { icon gfx.Icon // The shortcut the row shows, a keymap.Chord's fields: the Page's type would // keep that type's methods in every program, Menu or not. - modifiers gfx.Modifiers - char byte - key gfx.Key - destructive bool - disabled bool - submenu bool // the row opens a submenu - height float32 // a content row's height - content func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) // what paints a content row - checked int8 // 1 a checked checkbox, 2 an unchecked one, 3 a chosen radio, 4 an unchosen one + modifiers gfx.Modifiers + char byte + key gfx.Key + destructive bool + disabled bool + submenu bool // the row opens a submenu + trailingWidth float32 + trailing func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) + height float32 // a content row's height + content func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) // what paints a content row + checked int8 // 1 a checked checkbox, 2 an unchecked one, 3 a chosen radio, 4 an unchosen one } // minWidth is shadcn's: 8rem for a DropdownMenu, 9rem for a ContextMenu. @@ -456,7 +458,7 @@ func (m *MenuItems) minWidth() float32 { // good until the next row. func (m *MenuItems) row(i int) components.DropdownMenuItem { row := &m.items[i] - item := components.DropdownMenuItem{ID: m.scope.At(menuRows + i), Label: row.label, Description: row.description, Disabled: row.disabled, Icon: row.icon} + item := components.DropdownMenuItem{ID: m.scope.At(menuRows + i), Label: row.label, Description: row.description, Disabled: row.disabled, Icon: row.icon, TrailingWidth: row.trailingWidth} if row.destructive { item.Variant = components.DropdownMenuItemDestructive } @@ -566,6 +568,16 @@ func (m *MenuItems) paintContent(canvas *gfx.Canvas, theme gfx.Theme, row *menuR end() } +// paintTrailing calls a row's trailing painter over the slot the menu reserved at its end. +func (m *MenuItems) paintTrailing(canvas *gfx.Canvas, theme gfx.Theme, row *menuRow, slot gfx.Rect, begin, end func()) { + if slot.Width <= 0 || row.trailing == nil { + return + } + begin() + row.trailing(canvas, slot, theme) + end() +} + // Label adds a heading over the items that follow it. func (m *MenuItems) Label(label string) { m.items = append(m.items, menuRow{kind: menuRowLabel, label: label}) @@ -576,6 +588,16 @@ func (m *MenuItems) Separator() { m.items = append(m.items, menuRow{kind: menuRowSeparator}) } +// Trailing reserves width pixels at the item's end and has paint fill them: a small control +// of the row's own, such as the eye that hides a shell from a list. The control declares its +// own hit, over the row's, so pressing it does not choose the row; it is not called while +// scrolling has the row out of sight. A menu row has either Trailing or a shortcut. +func (item MenuItem) Trailing(width float32, paint func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme)) MenuItem { + row := &item.menu.items[item.i] + row.trailingWidth, row.trailing = width, paint + return item +} + // Destructive paints the item in the destructive color: an action that deletes. func (item MenuItem) Destructive() MenuItem { item.menu.items[item.i].destructive = true @@ -678,7 +700,13 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer case menuRowContent: m.paintContent(canvas, *theme, row, menu.AddContent(row.height), func() { menu.BeginContent() }, func() { menu.EndContent() }, menu.Bounds()) default: - if r := menu.AddItem(contextItem(m.row(i))); i == m.sub { + if row.trailing != nil { + r, slot := menu.AddItemSlot(contextItem(m.row(i))) + if i == m.sub { + trigger = r + } + m.paintTrailing(canvas, *theme, row, slot, menu.BeginContent, menu.EndContent) + } else if r := menu.AddItem(contextItem(m.row(i))); i == m.sub { trigger = r } } @@ -713,7 +741,13 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer case menuRowContent: m.paintContent(canvas, *theme, row, menu.AddContent(row.height), func() { menu.BeginContent() }, func() { menu.EndContent() }, menu.Bounds()) default: - if r := menu.AddItem(m.row(i)); i == m.sub { + if row.trailing != nil { + r, slot := menu.AddItemSlot(m.row(i)) + if i == m.sub { + trigger = r + } + m.paintTrailing(canvas, *theme, row, slot, menu.BeginContent, menu.EndContent) + } else if r := menu.AddItem(m.row(i)); i == m.sub { trigger = r } } @@ -739,7 +773,7 @@ func (m *MenuItems) paintAt(canvas *gfx.Canvas, theme *Theme, bounds Rect, layer // contextItem is a dropdown row as a context menu's: the two describe one row. func contextItem(item components.DropdownMenuItem) components.ContextMenuItem { context := components.ContextMenuItem{ - ID: item.ID, Label: item.Label, Description: item.Description, Keys: item.Keys, Icon: item.Icon, Disabled: item.Disabled, + ID: item.ID, Label: item.Label, Description: item.Description, Keys: item.Keys, Icon: item.Icon, Disabled: item.Disabled, TrailingWidth: item.TrailingWidth, Checked: item.Checked, Selected: item.Selected, } switch item.Kind { diff --git a/ui/menu_test.go b/ui/menu_test.go index 860a0cb7b..b3632a29f 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -635,3 +635,30 @@ func TestMenuContentRow(t *testing.T) { t.Fatalf("the arrows did not pass over the content row to Two (%d)", m.renamed) } } + +// A Trailing control has a hit of its own at the row's end: pressing it does not choose the row. +func TestMenuItemTrailingControl(t *testing.T) { + m := &menuModel{open: true} + var eye gfx.Rect + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Children(func() { + more := ui.Button(c, "More") + ui.Menu(c, more, &m.open, func(menu *ui.MenuItems) { + if menu.Item("One").Trailing(24, func(canvas *gfx.Canvas, bounds gfx.Rect, theme gfx.Theme) { + eye = bounds + canvas.HitWithOptions(gfx.Item(88), bounds, "Hide", gfx.HitOptions{Role: gfx.RoleButton}) + }).Clicked() { + m.renamed++ + } + }) + }) + }) + row := d.hit("One").Bounds + if eye.Width != 24 || eye.X+eye.Width > row.X+row.Width { + t.Fatalf("trailing slot %v not at the end of row %v", eye, row) + } + d.click("Hide") + if m.renamed != 0 { + t.Fatal("pressing the trailing control chose the row") + } +} From 076233a65b0c2638872ddb9035d357281af537f6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 01:13:45 +0800 Subject: [PATCH 15/23] test(ui): cover a scroll area over hand-painted content --- ui/page_test.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/ui/page_test.go b/ui/page_test.go index 2c40df96e..d63bf90f2 100644 --- a/ui/page_test.go +++ b/ui/page_test.go @@ -610,3 +610,31 @@ func TestPageTextAreaID(t *testing.T) { t.Fatalf("focused %v, want the identity the application gave it", d.driver.Snapshot().Focused) } } + +// Content the application paints itself scrolls in a ui.Scroll: a slot as tall as the content +// moves with the offset, its hits move with it, and the area clips and draws the scrollbar. +// This is how a hand-painted surface gets a page scrollbar. +func TestScrollAreaOverHandPaintedContent(t *testing.T) { + var rect gfx.Rect + var area ui.Box + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(8).Children(func() { + area = ui.Scroll(c).Height(100).Width(200).Scrollbars() + area.Children(func() { + ui.Slot(c).Width(180).Height(400).Draw(func(dc *ui.DrawContext) { + rect = dc.Rect + dc.Canvas.Hit(gfx.Item(5), gfx.Rect{X: dc.Rect.X, Y: dc.Rect.Y + 300, Width: 50, Height: 20}) + }) + }) + }) + }) + before := rect.Y + area.ScrollState().ScrollTo(150) + d.repaint() + if rect.Y >= before || before-rect.Y < 100 { + t.Fatalf("painted content did not move with the offset: %v -> %v", before, rect.Y) + } + if got := area.ScrollState().Max(); got != 300 { + t.Fatalf("scroll extent %v, want content 400 less viewport 100", got) + } +} From b51885df31fa0567ebfa316240e88fd5e9646fb6 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 01:18:01 +0800 Subject: [PATCH 16/23] feat(ui): add Kbd for a shortcut's keycaps in a page --- ui/kbd.go | 22 ++++++++++++++++++++++ ui/kbd_test.go | 18 ++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 ui/kbd.go create mode 100644 ui/kbd_test.go diff --git a/ui/kbd.go b/ui/kbd.go new file mode 100644 index 000000000..d7f487d6c --- /dev/null +++ b/ui/kbd.go @@ -0,0 +1,22 @@ +package ui + +import "github.com/vivaui/viva/gfx" + +// Kbd adds the keycaps of a shortcut side by side, one per key, as shadcn's KbdGroup +// does: each a hairline-bordered chip on the muted fill, as wide as its text and +// at least as wide as it is tall. Keys come from a chord's Keycaps. +// +// ui.Kbd(c, "⌘", "W") +func Kbd(c C, keys ...string) Box { + th := c.f.theme + m := th.Metrics + height := m.FontSizeS + 9 + radius := m.RadiusControl * 0.75 + return Row(c).Gap(4).Items(Center).Shrink(0).Children(func() { + for _, key := range keys { + Text(c, key).FontSize(m.FontSizeS).Weight(gfx.WeightMedium).Color(th.MutedForeground). + Background(th.Muted).Border(1, th.Border).Radius(radius). + Height(height).MinWidth(height).PadX(4).TextCenter().Shrink(0) + } + }) +} diff --git a/ui/kbd_test.go b/ui/kbd_test.go new file mode 100644 index 000000000..d9b6a0d8f --- /dev/null +++ b/ui/kbd_test.go @@ -0,0 +1,18 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/ui" +) + +func TestKbdLaysKeycapsSideBySide(t *testing.T) { + var group ui.Box + openPage(t, func(c ui.C) { + ui.Column(c).Pad(8).Children(func() { group = ui.Kbd(c, "⌘", "W") }) + }) + r := group.Rect() + if r.Width <= 2*20 || r.Height < 12 { + t.Fatalf("keycaps are %vx%v, want two chips side by side", r.Width, r.Height) + } +} From 451bc9bd784e0558c8358d6da60733360d8aeb4d Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 01:24:54 +0800 Subject: [PATCH 17/23] feat(ui): add Radio and RadioGroup for a single choice in a page --- ui/radio.go | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ ui/radio_test.go | 31 +++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 ui/radio.go create mode 100644 ui/radio_test.go diff --git a/ui/radio.go b/ui/radio.go new file mode 100644 index 000000000..112dcdbb7 --- /dev/null +++ b/ui/radio.go @@ -0,0 +1,51 @@ +package ui + +import "github.com/vivaui/viva/gfx" + +// Radio adds one option of a radio group, shadcn's RadioGroupItem with its label: a +// 16 pixel circle that is filled with the primary color and holds a dot while *value is +// option, and the label after it. A click sets *value to option (RadioBase's rules), and +// the focus moving onto it with the arrow keys of a RadioGroup chooses it, as a native +// radio group does. Name it with c.Key when the options are reordered; Hit gives it the +// application's identity. +// +// ui.Radio(c, &m.plan, Monthly, "Monthly") +func Radio[T comparable](c C, value *T, option T, label string) Box { + th := c.f.theme + m := th.Metrics + b := RadioBase(c, value, option, label) + if b.State().FocusVisible && *value != option { + *value = option + } + chosen := *value == option + border, fill := th.Input, th.Background + fill.Alpha = 0 + if chosen { + border, fill = th.Primary, th.Primary + } + ring := th.Ring + ring.Alpha *= 0.5 + b.Height(m.ControlHeight).Gap(m.GapItem).Children(func() { + Row(c).Width(16).Height(16).Shrink(0).Radius(8).Border(1, border).Background(fill). + Items(Center).Justify(Center).StateFrom(b).Focus(Look{}.Border(th.Ring).Ring(3, ring)). + Children(func() { + if chosen { + Row(c).Width(8).Height(8).Radius(4).Background(th.PrimaryForeground) + } + }) + Text(c, label).FontSize(m.FontSizeM).Weight(gfx.WeightMedium) + }) + return b +} + +// RadioGroup adds a column for the Radio options inside it: Tab reaches the chosen one +// (else the first) and goes on out of the group, and the arrow keys move the focus, +// and with it the choice, among them. +// +// ui.RadioGroup(c).Children(func() { +// ui.Radio(c.Key("m"), &m.plan, Monthly, "Monthly") +// ui.Radio(c.Key("y"), &m.plan, Yearly, "Yearly") +// }) +func RadioGroup(c C) Box { + return Column(c).Gap(12).FocusGroup(FocusBoth) +} diff --git a/ui/radio_test.go b/ui/radio_test.go new file mode 100644 index 000000000..219be2d97 --- /dev/null +++ b/ui/radio_test.go @@ -0,0 +1,31 @@ +package ui_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +func TestRadioGroupChoosesByClickAndArrows(t *testing.T) { + choice := "a" + d := openPage(t, func(c ui.C) { + ui.RadioGroup(c).Children(func() { + for _, name := range []string{"a", "b", "c"} { + ui.Radio(c.Key(name), &choice, name, name) + } + }) + }) + d.click("b") + if choice != "b" { + t.Fatalf("a click chose %q", choice) + } + d.key(gfx.KeyDown) + if choice != "c" || d.focused() != "c" { + t.Fatalf("Down chose %q with the focus on %q", choice, d.focused()) + } + d.key(gfx.KeyDown) + if choice != "a" { + t.Fatalf("Down from the last chose %q, want it to wrap to a", choice) + } +} From 7153eaebc52a03a38f666b2929f017d457e730c8 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 01:25:43 +0800 Subject: [PATCH 18/23] feat(ui): add RadioID for an option the application names --- ui/radio.go | 16 +++++++++++++++- ui/radio_test.go | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/ui/radio.go b/ui/radio.go index 112dcdbb7..b66318e16 100644 --- a/ui/radio.go +++ b/ui/radio.go @@ -11,9 +11,23 @@ import "github.com/vivaui/viva/gfx" // // ui.Radio(c, &m.plan, Monthly, "Monthly") func Radio[T comparable](c C, value *T, option T, label string) Box { + return radio(c, c.page.controlID(pkRadio), value, option, label) +} + +// RadioID is Radio for an option the application already names, as TextFieldID is for +// TextField: id is the option's identity in the page's Tree, so an initial focus, the +// application's own routing or a test can address it. +// +// ui.RadioID(c, hitKeepParent, &m.ungroup, false, "Keep hosts in the parent") +func RadioID[T comparable](c C, id gfx.ID, value *T, option T, label string) Box { + return radio(c, id, value, option, label) +} + +func radio[T comparable](c C, id gfx.ID, value *T, option T, label string) Box { th := c.f.theme m := th.Metrics - b := RadioBase(c, value, option, label) + b := c.f.RadioBase(id, label, *value == option) + choose(c, b, value, option) if b.State().FocusVisible && *value != option { *value = option } diff --git a/ui/radio_test.go b/ui/radio_test.go index 219be2d97..5be824381 100644 --- a/ui/radio_test.go +++ b/ui/radio_test.go @@ -29,3 +29,22 @@ func TestRadioGroupChoosesByClickAndArrows(t *testing.T) { t.Fatalf("Down from the last chose %q, want it to wrap to a", choice) } } + +func TestRadioIDKeepsTheApplicationsIdentity(t *testing.T) { + id := gfx.Item(41) + ungroup := false + d := openPage(t, func(c ui.C) { + ui.RadioGroup(c).Children(func() { + ui.RadioID(c.Key("keep"), gfx.Item(40), &ungroup, false, "Keep") + ui.RadioID(c.Key("ungroup"), id, &ungroup, true, "Ungroup") + }) + }) + d.click("Ungroup") + if !ungroup { + t.Fatal("a click on the identified option did not choose it") + } + d.key(gfx.KeyUp) + if ungroup || d.focused() != "Keep" { + t.Fatalf("Up chose ungroup=%v with the focus on %q", ungroup, d.focused()) + } +} From bcf54a066065d2cd8d96731b8a16e01151d88fce Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 01:28:42 +0800 Subject: [PATCH 19/23] fix(ui): end a Radio label with an ellipsis when it does not fit --- ui/radio.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/radio.go b/ui/radio.go index b66318e16..97a64dbe7 100644 --- a/ui/radio.go +++ b/ui/radio.go @@ -47,7 +47,7 @@ func radio[T comparable](c C, id gfx.ID, value *T, option T, label string) Box { Row(c).Width(8).Height(8).Radius(4).Background(th.PrimaryForeground) } }) - Text(c, label).FontSize(m.FontSizeM).Weight(gfx.WeightMedium) + Text(c, label).FontSize(m.FontSizeM).Weight(gfx.WeightMedium).Ellipsis() }) return b } From fa760330b43cd090f2f22d092f76b0c63c9f3a86 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 01:39:53 +0800 Subject: [PATCH 20/23] feat(ui): move the rows of a List with Reorder by Alt and the arrows --- ui/list.go | 6 +++++- ui/list_reorder.go | 26 ++++++++++++++++++++++++++ ui/list_test.go | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/ui/list.go b/ui/list.go index 4c08287b2..8a04d617d 100644 --- a/ui/list.go +++ b/ui/list.go @@ -57,7 +57,8 @@ type ListState struct { // rows for the end). Move them there: the list shows where they would go as // they are dragged and scrolls near its edges, Escape lets go of the drag, and // a drop that changes nothing calls nothing. The drag starts on the row itself; - // a press on a control in it (a button) is that control's. + // a press on a control in it (a button) is that control's. Alt with Up or Down on + // a row does the same for the keyboard, one place at a time. Reorder func(rows []int, to int) // RowWidth, when positive, makes the rows at least that wide: where they are // wider than the list it scrolls sideways too (the horizontal wheel, or the @@ -1160,6 +1161,9 @@ func (p *Page) listKey(event gfx.KeyEvent) (gfx.EventResult, bool) { if n == 0 { return gfx.EventResult{}, false } + if s.Reorder != nil && event.Modifiers == gfx.ModifierAlt && (event.Key == gfx.KeyUp || event.Key == gfx.KeyDown) { + return s.reorderByKey(row, event.Key == gfx.KeyUp) + } how, ok := moveOf(event, s.Selection != nil) if !ok { return gfx.EventResult{}, false diff --git a/ui/list_reorder.go b/ui/list_reorder.go index 90153af69..40aabc1c0 100644 --- a/ui/list_reorder.go +++ b/ui/list_reorder.go @@ -123,3 +123,29 @@ func (in *listInternals) drawOver(d *DrawContext) { y = min(max(y, d.Rect.Y+1), d.Rect.Y+d.Rect.Height-1) d.Canvas.Fill(Rect{X: d.Rect.X, Y: y - 1, Width: d.Rect.Width, Height: 2}, d.Theme.Primary) } + +// reorderByKey is Alt with Up or Down on a row of a List with Reorder: the rows the +// drag would carry go one row up or down, as a drop would put them, and the keyboard +// stays on the row. At the first or the last row it moves nothing. +func (s *ListState) reorderByKey(row int, up bool) (gfx.EventResult, bool) { + var drag listDrag + drag.from = row + s.carriedRows(&drag) + rows := drag.rows + to := rows[len(rows)-1] + 2 // before the row after the one below the run + if up { + to = rows[0] - 1 + } + if to < 0 || to > s.list.n || s.isHeader(min(to, s.list.n-1)) { + return gfx.EventResult{Handled: true}, true + } + focus := s.key(row) // a keyed row keeps its identity where it goes + if s.Key == nil { + focus = row + 1 // an index names the row: it is one place on + if up { + focus = row - 1 + } + } + s.Reorder(rows, to) + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.list.rows.At(focus), FocusVisible: true}, true +} diff --git a/ui/list_test.go b/ui/list_test.go index b336777c7..fcd166671 100644 --- a/ui/list_test.go +++ b/ui/list_test.go @@ -436,3 +436,37 @@ func BenchmarkListStreamingAppend(b *testing.B) { drawPage(page, canvas, m.view) } } + +// Alt with the arrows moves the rows of a List with Reorder, as a drag would, for the +// keyboard: the focus stays on the row. +func TestListReorderByKeyboard(t *testing.T) { + names := []string{"a", "b", "c"} + var state ui.ListState + state.Key = func(i int) int { return int(names[i][0] - 'a') } + state.Label = func(i int) string { return names[i] } + state.Reorder = func(rows []int, to int) { + moved := names[rows[0]] + rest := append(append([]string(nil), names[:rows[0]]...), names[rows[0]+1:]...) + if to > rows[0] { + to-- + } + names = append(append(append([]string(nil), rest[:to]...), moved), rest[to:]...) + } + d := openPage(t, func(c ui.C) { + ui.List(c, &state, len(names), func(row ui.ListRow) { + ui.Text(row.C, names[row.Index]) + }).Height(150) + }) + d.click("b") + d.driver.Key(gfx.KeyUp, gfx.ModifierAlt) + d.repaint() + if got := names[0] + names[1] + names[2]; got != "bac" { + t.Fatalf("Alt+Up left %q, want bac", got) + } + d.driver.Key(gfx.KeyDown, gfx.ModifierAlt) + d.driver.Key(gfx.KeyDown, gfx.ModifierAlt) + d.repaint() + if got := names[0] + names[1] + names[2]; got != "acb" { + t.Fatalf("Alt+Down twice left %q, want acb", got) + } +} From 83e5375fdc0153f2bd556dbadabf67fc55a554a7 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 01:45:16 +0800 Subject: [PATCH 21/23] fix(ui): let go of a List drag when the platform takes the press --- ui/list_test.go | 29 +++++++++++++++++++++++++++++ ui/page.go | 5 +++++ 2 files changed, 34 insertions(+) diff --git a/ui/list_test.go b/ui/list_test.go index fcd166671..3fdd265ed 100644 --- a/ui/list_test.go +++ b/ui/list_test.go @@ -470,3 +470,32 @@ func TestListReorderByKeyboard(t *testing.T) { t.Fatalf("Alt+Down twice left %q, want acb", got) } } + +// A press the platform takes for itself ends a drag of rows without dropping them. +func TestListReorderDragCancelledByThePlatformDropsNothing(t *testing.T) { + names := []string{"a", "b", "c"} + dropped := false + var state ui.ListState + state.Label = func(i int) string { return names[i] } + state.Reorder = func(rows []int, to int) { dropped = true } + d := openPage(t, func(c ui.C) { + ui.List(c, &state, len(names), func(row ui.ListRow) { + ui.Text(row.C, names[row.Index]).Height(30) + }).Height(150) + }) + a, c3 := d.hit("a").Bounds, d.hit("c").Bounds + ax, ay, cx, cy := a.X+a.Width/2, a.Y+a.Height/2, c3.X+c3.Width/2, c3.Y+c3.Height/2 + for _, err := range []error{ + d.driver.Press(ax, ay, gfx.PointerButtonPrimary), + d.driver.Move(cx, cy), + d.driver.Cancel(), + d.driver.Release(cx, cy, gfx.PointerButtonPrimary), + } { + if err != nil { + t.Fatal(err) + } + } + if dropped { + t.Fatal("a cancelled press dropped the rows") + } +} diff --git a/ui/page.go b/ui/page.go index 433f85c07..e47c91ee5 100644 --- a/ui/page.go +++ b/ui/page.go @@ -561,6 +561,11 @@ func (p *Page) onPointer(event gfx.PointerEvent) gfx.EventResult { p.pointer, p.pointerIn = gfx.Point{X: event.X, Y: event.Y}, true case gfx.PointerExit: p.pointerIn = false + // A press the platform took for itself (a window move) never gets its release: + // the rows a List was carrying are not dropped. + for _, s := range p.listStates { + s.list.drag.reset() + } } // A bar is revealed by the pointer being over its area, and an area with no // hit regions of its own would otherwise move no hover and never repaint to From f4c637e7abcea275ce8e9ce17323fb75c28e30ae Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 10:27:27 +0800 Subject: [PATCH 22/23] feat(ui): let a Combobox validate the text it shows --- ui/combobox.go | 21 +++++++++++++++++++++ ui/combobox_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/ui/combobox.go b/ui/combobox.go index 44c77a768..5bb9c9545 100644 --- a/ui/combobox.go +++ b/ui/combobox.go @@ -2,6 +2,7 @@ package ui import ( "strconv" + "strings" "unsafe" "github.com/vivaui/viva/app" @@ -135,6 +136,7 @@ type comboState struct { gen uint32 label, placeholder, empty string createPrefix string + check func(string) bool // what the field may create clearable bool layer uint16 } @@ -199,6 +201,11 @@ func (s *comboState) draw(d *DrawContext) { if s.clearable { options.ClearID, options.ClearLabel = ids.clear, "Clear "+s.label } + if s.check != nil { + if typed := strings.TrimSpace(s.list.Query.String()); typed != "" { + options.Invalid = !s.check(typed) + } + } components.PaintSingleSelect(d.Canvas, *d.Theme, d.Rect, &s.list, options) } @@ -244,6 +251,20 @@ func (b Box) Creatable(prefix string) Box { return b } +// Validate gives the Combobox a rule for the text it shows: while what is typed +// is no choice and check says it cannot be one, the field paints as invalid. The +// check is asked once per paint with the trimmed text; the application still +// decides what to do with a Created name. nil disables it. +// +// ui.Combobox(c, &m.group, m.groups, nil, "Group").Creatable(""). +// Validate(validGroupName) +func (b Box) Validate(check func(string) bool) Box { + if s := b.combo(); s != nil { + s.check = check + } + return b +} + // Created reports what the user typed and chose as a new choice in this paint. The // value is not changed: add it to the choices and set the value to it. // diff --git a/ui/combobox_test.go b/ui/combobox_test.go index 878d26679..1fcc0cefb 100644 --- a/ui/combobox_test.go +++ b/ui/combobox_test.go @@ -3,6 +3,8 @@ package ui_test import ( "testing" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -184,3 +186,28 @@ func TestComboboxEmpty(t *testing.T) { t.Fatalf("rows %v, the empty text shown %v", options(d), tooltipShown(d, "No zone matches")) } } + +// Validate is asked for what is typed, and the field paints as invalid while the +// check refuses it, before the application decides about the created name. +func TestComboboxPaintsWhatValidateRefuses(t *testing.T) { + var checked []string + m := &groupModel{groups: []string{"prod"}} + d := openPage(t, func(c ui.C) { + ui.Combobox(c, &m.group, m.groups, nil, "Group").Creatable("").Validate(func(value string) bool { + checked = append(checked, value) + return len(value) <= 4 + }) + }) + d.click("Group") + d.typeText("toolong") + if len(checked) == 0 || checked[len(checked)-1] != "toolong" { + t.Fatalf("Validate saw %v", checked) + } + want := components.TextEntryRecipe(pageTheme, gfx.State{Invalid: true}).Border + for _, primitive := range d.driver.Snapshot().Primitives { + if primitive.Kind == app.RectanglePrimitive && primitive.Color == want { + return + } + } + t.Fatal("the field did not paint as invalid") +} From 059256b5ba10f4f5eee09473857baaa467b8b638 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Wed, 18 Nov 2026 10:28:43 +0800 Subject: [PATCH 23/23] Revert "feat(ui): let a Combobox validate the text it shows" This reverts commit f4c637e7abcea275ce8e9ce17323fb75c28e30ae. --- ui/combobox.go | 21 --------------------- ui/combobox_test.go | 27 --------------------------- 2 files changed, 48 deletions(-) diff --git a/ui/combobox.go b/ui/combobox.go index 5bb9c9545..44c77a768 100644 --- a/ui/combobox.go +++ b/ui/combobox.go @@ -2,7 +2,6 @@ package ui import ( "strconv" - "strings" "unsafe" "github.com/vivaui/viva/app" @@ -136,7 +135,6 @@ type comboState struct { gen uint32 label, placeholder, empty string createPrefix string - check func(string) bool // what the field may create clearable bool layer uint16 } @@ -201,11 +199,6 @@ func (s *comboState) draw(d *DrawContext) { if s.clearable { options.ClearID, options.ClearLabel = ids.clear, "Clear "+s.label } - if s.check != nil { - if typed := strings.TrimSpace(s.list.Query.String()); typed != "" { - options.Invalid = !s.check(typed) - } - } components.PaintSingleSelect(d.Canvas, *d.Theme, d.Rect, &s.list, options) } @@ -251,20 +244,6 @@ func (b Box) Creatable(prefix string) Box { return b } -// Validate gives the Combobox a rule for the text it shows: while what is typed -// is no choice and check says it cannot be one, the field paints as invalid. The -// check is asked once per paint with the trimmed text; the application still -// decides what to do with a Created name. nil disables it. -// -// ui.Combobox(c, &m.group, m.groups, nil, "Group").Creatable(""). -// Validate(validGroupName) -func (b Box) Validate(check func(string) bool) Box { - if s := b.combo(); s != nil { - s.check = check - } - return b -} - // Created reports what the user typed and chose as a new choice in this paint. The // value is not changed: add it to the choices and set the value to it. // diff --git a/ui/combobox_test.go b/ui/combobox_test.go index 1fcc0cefb..878d26679 100644 --- a/ui/combobox_test.go +++ b/ui/combobox_test.go @@ -3,8 +3,6 @@ package ui_test import ( "testing" - "github.com/vivaui/viva/app" - "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) @@ -186,28 +184,3 @@ func TestComboboxEmpty(t *testing.T) { t.Fatalf("rows %v, the empty text shown %v", options(d), tooltipShown(d, "No zone matches")) } } - -// Validate is asked for what is typed, and the field paints as invalid while the -// check refuses it, before the application decides about the created name. -func TestComboboxPaintsWhatValidateRefuses(t *testing.T) { - var checked []string - m := &groupModel{groups: []string{"prod"}} - d := openPage(t, func(c ui.C) { - ui.Combobox(c, &m.group, m.groups, nil, "Group").Creatable("").Validate(func(value string) bool { - checked = append(checked, value) - return len(value) <= 4 - }) - }) - d.click("Group") - d.typeText("toolong") - if len(checked) == 0 || checked[len(checked)-1] != "toolong" { - t.Fatalf("Validate saw %v", checked) - } - want := components.TextEntryRecipe(pageTheme, gfx.State{Invalid: true}).Border - for _, primitive := range d.driver.Snapshot().Primitives { - if primitive.Kind == app.RectanglePrimitive && primitive.Color == want { - return - } - } - t.Fatal("the field did not paint as invalid") -}