diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0242774e5..25e7aa565 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -182,7 +182,7 @@ jobs: run: | sudo apt-get install -y xvfb libxcb-shape0 libgtk-3-0 || { sudo apt-get update && sudo apt-get install -y xvfb libxcb-shape0 libgtk-3-0; } - xvfb-run -a -s '-screen 0 1280x1024x24 -noreset' go test ./internal/platform/linux -run '^Test(PreviewNativeX11Contract|NotificationNativeX11|TrayWindowQueuedRedrawBeforeInput|TrayWindowRepaintsLaterExposure|AFileDragOutReachesAnotherClient)$' -count=1 -v + xvfb-run -a -s '-screen 0 1280x1024x24 -noreset' go test ./internal/platform/linux -run '^Test(PreviewNativeX11Contract|NotificationNativeX11|TrayWindowQueuedRedrawBeforeInput|TrayWindowRepaintsLaterExposure|TrayPanelPreservesHostAnchorAtScale|AFileDragOutReachesAnotherClient)$' -count=1 -v GDK_BACKEND=x11 VIVA_TEST_GTK_NOTIFICATION=1 xvfb-run -a go test -tags vivagtk ./internal/platform/linux -run '^TestGTKNotificationFocusHints$' -count=1 -v - name: Native X11 global shortcut env: @@ -379,12 +379,21 @@ jobs: run: go test ./internal/platform/windows ./app -run '^Test(FileDialogInitialDirectory|DriverInterceptsOpenDirectory)$' -count=1 -v - name: Material contracts and controls (WARP) run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|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|DragPreview|QueuedMenuKeysLeaveTerminalCompositionWithItsOwner|MenuKeysPreserveSystemChordsAndShift|TerminalMenuStopsCapturingWhenWindowLosesFocus|DisabledIMEOffersMenuShortcutDuringComposition)' -count=1 -v + - name: Offscreen incremental frame pixels + run: | + $test = 'TestOffscreenIncrementalUpdatesDrawWhatARebuildDraws' + go test -json ./internal/platform/windows -run "^${test}$" -count=1 -timeout=2m | Tee-Object -Variable events + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $passed = $events | ConvertFrom-Json | Where-Object { $_.Action -eq 'pass' -and $_.Test -eq $test } + if (-not $passed) { throw "$test did not pass on the Windows runner" } - name: Web view partitions run: go test ./internal/platform/windows -run '^Test(APageWithoutAPartitionAsksForNoProfileOfItsOwn|APartitionNamesTheWebView2Profile|AnEphemeralPartitionIsAnOffTheRecordProfile|EphemeralPagesWithoutAPartitionEachGetAProfileOfTheirOwn)$' -count=1 -v - name: Terminal keyboard routing run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v - name: Native window and grouped taskbar icons run: go test ./internal/platform/windows -run '^TestWindowIconUpdatesOnTheWindowThread$' -count=1 -v + - name: Native window decoration changes + run: go test ./internal/platform/windows -run '^TestNativeWindowDecoration' -count=1 -v -timeout=90s - name: Non-activating desktop notification env: VIVA_TEST_NOTIFICATION_DESKTOP: '1' @@ -397,8 +406,8 @@ jobs: env: VIVA_WINDOWS_CLIPBOARD: '1' run: go test ./internal/platform/windows -run '^TestColumnClipboardNative' -count=1 -v -timeout=2m - - name: Native Direct2D text origins and hidden labels - run: go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|HiddenNativeEditorDoesNotDrawColorEmoji|TextEngineRasterizesProportionalText)$' -count=1 -v + - name: Native Direct2D text origins, hidden labels and font fallback + run: go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|HiddenNativeEditorDoesNotDrawColorEmoji|TextEngineRasterizesProportionalText|RegisteredFontDrawsFallbackCharacters)$' -count=1 -v - name: Promised file drag run: go test ./internal/platform/windows -run '^Test(ThePromiseDataObject|ThePromiseStream|ThePromiseEnumerator|PromiseNames)' -count=1 -v # The installer contracts, including WinVerifyTrust's struct layout, only @@ -416,6 +425,8 @@ jobs: needs: changes if: needs.changes.outputs.code == 'true' runs-on: windows-11-arm + env: + VIVA_SOFTWARE_RENDERING: '1' steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 @@ -423,10 +434,12 @@ jobs: go-version-file: go.mod architecture: arm64 cache: true - - name: Native ARM64 Direct2D text origins + - name: Native ARM64 Direct2D text origins and font fallback run: | if ((go env GOARCH) -ne 'arm64') { throw 'Expected native ARM64 Go' } - go test ./internal/platform/windows -run '^TestDirectTextLayoutOriginByValue$' -count=1 -v + go test ./internal/platform/windows -run '^Test(DirectTextLayoutOriginByValue|RegisteredFontDrawsFallbackCharacters)$' -count=1 -v + - name: Native ARM64 window decoration changes + run: go test ./internal/platform/windows -run '^TestNativeWindowDecoration' -count=1 -v -timeout=90s # A noise-tolerant benchmark regression gate for the pure-Go paths: the base # revision and the pull request run the same benchmarks on the same runner, diff --git a/app/accessibility_test.go b/app/accessibility_test.go index 423fab09f..421128af3 100644 --- a/app/accessibility_test.go +++ b/app/accessibility_test.go @@ -262,3 +262,25 @@ func TestSyncSemanticsUpdatesZeroIDContainerOnIncrementalPaint(t *testing.T) { t.Fatalf("stale zero-ID container accessibility node: %+v", nodes) } } + +// A pointer region over painted words (a selectable text's) is no node of its own and +// takes no focus, while the control it belongs to stays one. +func TestPresentationalHitsAreNoAccessibilityNodes(t *testing.T) { + var canvas gfx.Canvas + config := Config{Title: "presentational", Width: 200, Height: 120} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{Width: 200, Height: 100}, "", gfx.HitOptions{Role: gfx.RoleGroup, SkipTab: true}) + canvas.HitWithOptions(gfx.Item(2), gfx.Rect{Y: 10, Width: 120, Height: 16}, "", gfx.HitOptions{ + Role: gfx.RoleGroup, Cursor: gfx.PointerCursorText, Presentational: true, + }) + } + painter := newTestPainter(t, &canvas, config) + if len(painter.accessibility) != 1 || painter.accessibility[0].ID != gfx.Item(1) { + t.Fatalf("accessibility = %+v", painter.accessibility) + } + for _, hit := range canvas.Hits() { + if hit.ID == gfx.Item(2) && (hit.Focusable || hit.Cursor != gfx.PointerCursorText) { + t.Fatalf("the pointer region is %+v", hit) + } + } +} diff --git a/app/app.go b/app/app.go index 678b56158..409e3fc95 100644 --- a/app/app.go +++ b/app/app.go @@ -46,6 +46,8 @@ const ( // bottom-right of the pointer monitor's work area without taking keyboard // focus. Mark the parts the user may drag with gfx.Canvas.MoveRegion or // ui.Box.MovesWindow and save Frame's X and Y for Config.Origin. + // On Windows and macOS, an Anchor takes precedence over Origin and + // places the notification beside the status item. // On native Wayland, the compositor decides placement, stacking and // keyboard focus. Use SendNotification for a system-managed notification. WindowNotification WindowMode = WindowMode(platform.WindowNotification) @@ -109,8 +111,8 @@ type Config struct { // change. Nil, or a zero field, takes a color that suits ClearColor. Use // TitlebarInsets to keep your own content clear of the buttons. WindowControls func() WindowControlsStyle - // Anchor is where a WindowPanel opens: beside the status item whose click - // supplied it. Without one the panel is centered on the screen. + // Anchor places a WindowPanel or WindowNotification beside a status item. + // Without one, a WindowPanel is centered on the screen. Anchor StatusAnchor ClearColor Color // Transparent composites the window over the desktop: the part of the canvas diff --git a/app/application.go b/app/application.go index d618e2743..e06cf227b 100644 --- a/app/application.go +++ b/app/application.go @@ -23,6 +23,7 @@ var ErrNoWindows = errors.New("app: application opened no windows") // before resize/frame callbacks and repaints afterward. // An always-on-top host additionally implements SetAlwaysOnTop(bool) error. // A size-capable host additionally implements SetSize(int, int) error. +// A decoration-capable host additionally implements SetDecorated(bool, func(error)) error. type WindowControl interface { Close() Hide() @@ -371,11 +372,30 @@ func (application *Application) AddStatusItem(config StatusItemConfig) (*StatusI if err := config.Icon.validate(); err != nil { return nil, err } + item := &StatusItem{application: application} + dismiss := func() { + if preview := item.preview.Load(); preview != nil { + preview.close() + } + } + if click := config.OnClick; click != nil { + config.OnClick = func(event StatusClick) { + dismiss() + click(event) + } + } + if menu := config.Menu; menu != nil { + config.Menu = func() []MenuItem { + dismiss() + return menu() + } + } control, err := application.host.AddStatusItem(config) if err != nil { return nil, err } - return &StatusItem{control: control}, nil + item.control = control + return item, nil } // SetDockBadge marks the application's Dock icon with text, the red badge macOS diff --git a/app/application_native.go b/app/application_native.go index 7c9617420..0ec3ae514 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -144,6 +144,14 @@ func (window resultWindow) SetAlwaysOnTop(enabled bool) error { return control.SetAlwaysOnTop(enabled) } +func (window resultWindow) SetDecorated(decorated bool, done func(error)) error { + control, ok := window.WindowControl.(decorationControl) + if !ok { + return platform.ErrWindowDecorationUnsupported + } + return control.SetDecorated(decorated, done) +} + func (window resultWindow) MoveTo(origin gfx.Point) { if control, ok := window.WindowControl.(platform.WindowMover); ok { control.MoveTo(origin) @@ -265,3 +273,12 @@ func (item nativeStatusItem) SetIcon(icon StatusIcon) error { } func (item nativeStatusItem) SetTooltip(tooltip string) { item.item.SetTooltip(tooltip) } func (item nativeStatusItem) Remove() { item.item.Remove() } +func (item nativeStatusItem) SetStatusHover(handler func(StatusAnchor, bool)) bool { + if handler == nil { + return item.item.SetHover(nil) + } + return item.item.SetHover(func(event platform.StatusHover) { + handler(StatusAnchor{rect: event.Anchor, set: event.Entered}, event.Entered) + }) +} +func (item nativeStatusItem) RefreshMenu() { item.item.RefreshMenu() } diff --git a/app/application_native_test.go b/app/application_native_test.go index b0295f911..1f809797b 100644 --- a/app/application_native_test.go +++ b/app/application_native_test.go @@ -54,3 +54,20 @@ func TestResultWindowForwardsSetTitle(t *testing.T) { t.Fatalf("wrapped unsupported window error = %v", err) } } + +func TestResultWindowForwardsSetDecorated(t *testing.T) { + native := &decorationTestControl{decorated: true} + window := &Window{control: resultWindow{WindowControl: native}} + called := false + if err := window.SetDecorated(false, func(error) { called = true }); err != nil || native.decorated || native.done == nil || called { + t.Fatalf("decorations did not reach the native control: %v", err) + } + native.done(nil) + if !called { + t.Fatal("native completion did not reach caller") + } + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetDecorated(false, func(error) {}); !errors.Is(err, ErrUnsupported) { + t.Fatalf("wrapped unsupported native error = %v", err) + } +} diff --git a/app/decoration.go b/app/decoration.go new file mode 100644 index 000000000..33c248d4e --- /dev/null +++ b/app/decoration.go @@ -0,0 +1,43 @@ +package app + +import ( + "errors" + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +type decorationControl interface { + SetDecorated(bool, func(error)) error +} + +// SetDecorated changes the native decorations of a normal, mapped window +// without replacing it or moving its content. It does not change fullscreen +// or always-on-top state. It is safe to call from any goroutine. +// +// A non-nil error rejects the request without calling done. An accepted +// request calls done once on the native window loop after the transition is +// confirmed, fails, or is interrupted by closing the window. Do not block +// the window loop waiting for done. Hosts without this capability return an +// error wrapping ErrUnsupported. +func (window *Window) SetDecorated(decorated bool, done func(error)) error { + if done == nil { + return fmt.Errorf("app: window decoration completion callback is required") + } + if window == nil || window.closed.Load() { + return fmt.Errorf("app: window is closed") + } + control, ok := window.control.(decorationControl) + if !ok { + return fmt.Errorf("%w: window decorations", ErrUnsupported) + } + err := control.SetDecorated(decorated, func(err error) { done(windowDecorationError(err)) }) + return windowDecorationError(err) +} + +func windowDecorationError(err error) error { + if errors.Is(err, platform.ErrWindowDecorationUnsupported) { + return fmt.Errorf("%w: window decorations", ErrUnsupported) + } + return err +} diff --git a/app/decoration_test.go b/app/decoration_test.go new file mode 100644 index 000000000..ecb0b8920 --- /dev/null +++ b/app/decoration_test.go @@ -0,0 +1,55 @@ +package app + +import ( + "errors" + "testing" + + "github.com/vivaui/viva/internal/platform" +) + +type decorationTestControl struct { + WindowControl + decorated bool + done func(error) + err error +} + +func (c *decorationTestControl) SetDecorated(decorated bool, done func(error)) error { + c.decorated, c.done = decorated, done + return c.err +} + +func TestSetDecoratedReportsCompletionOnlyFromHost(t *testing.T) { + control := &decorationTestControl{decorated: true} + window := &Window{control: control} + var completed []error + if err := window.SetDecorated(false, func(err error) { completed = append(completed, err) }); err != nil { + t.Fatal(err) + } + if control.decorated || control.done == nil || len(completed) != 0 { + t.Fatal("submission did not reach the host, or completed before the host replied") + } + rollback := errors.New("previous frame restored") + control.done(rollback) + if len(completed) != 1 || !errors.Is(completed[0], rollback) { + t.Fatalf("completion = %v", completed) + } +} + +func TestSetDecoratedRejectsUnsupportedAndClosedWindows(t *testing.T) { + unsupported := &Window{control: struct{ WindowControl }{}} + for _, window := range []*Window{unsupported, {control: &decorationTestControl{err: platform.ErrWindowDecorationUnsupported}}} { + if err := window.SetDecorated(false, func(error) { t.Error("unsupported submission completed") }); !errors.Is(err, ErrUnsupported) { + t.Fatalf("unsupported submission: %v", err) + } + } + control := &decorationTestControl{} + window := &Window{control: control} + if err := window.SetDecorated(false, nil); err == nil { + t.Fatal("submission without a completion callback succeeded") + } + window.closed.Store(true) + if err := window.SetDecorated(false, func(error) {}); err == nil || control.done != nil { + t.Fatalf("closed submission reached host: %v", err) + } +} diff --git a/app/hit_gate_test.go b/app/hit_gate_test.go index c02ce3405..d5a5c91b7 100644 --- a/app/hit_gate_test.go +++ b/app/hit_gate_test.go @@ -185,16 +185,29 @@ func TestRepaintReleasesFocusWhenThePaintAsksWithoutChangingHits(t *testing.T) { // A page that formats its labels every frame declares the same text in a new // allocation each time: that is an unchanged hit list, which keeps the repaint on -// the path that skips the semantic mirror. -func TestSameHitsComparesLabelsByText(t *testing.T) { +// the path that skips the semantic mirror. Changed words still reach it. +func TestRepaintComparesLabelsByText(t *testing.T) { + page := &hitGatePage{label: "Clicked 3 times", bounds: gfx.Rect{Width: 80, Height: 20}} fresh := func(text string) string { return string([]byte(text)) } - published := []gfx.Hit{{ID: gfx.Item(1), Label: fresh("Clicked 3 times"), Value: fresh("3")}} - current := []gfx.Hit{{ID: gfx.Item(1), Label: fresh("Clicked 3 times"), Value: fresh("3")}} - if !sameHits(published, current) { - t.Fatal("the same labels in new allocations compared as a change") + config := Config{Title: "gate", Width: 200, Height: 80, Paint: page.paint} + var canvas gfx.Canvas + painter := newTestPainter(t, &canvas, config) + + page.label = fresh("Clicked 3 times") + frame, err := painter.repaint() + if err != nil { + t.Fatal(err) + } + if frame.Accessibility != nil { + t.Fatal("the same label in a new allocation republished the accessibility payload") + } + + page.label = fresh("Clicked 4 times") + frame, err = painter.repaint() + if err != nil { + t.Fatal(err) } - current[0].Label = fresh("Clicked 4 times") - if sameHits(published, current) { + if frame.Accessibility == nil || painter.accessibility[0].Label != "Clicked 4 times" { t.Fatal("a changed label compared as unchanged") } } diff --git a/app/key_traversal_frame_test.go b/app/key_traversal_frame_test.go index b0d7f49de..aa1085b9f 100644 --- a/app/key_traversal_frame_test.go +++ b/app/key_traversal_frame_test.go @@ -56,13 +56,15 @@ func TestContinueTraversalKeyPublishesOneConsistentFrame(t *testing.T) { if count >= base { t.Fatalf("the popup did not close: %d -> %d", base, count) } - // The platform still holds base rectangles. A frame that carries a different - // number of them has to say so with a rebuild. - if len(frame.Rectangles) != base && !frame.Update.Rebuild { - t.Fatalf("frame does not match the platform's base: base=%d frame=%d update=%+v", base, len(frame.Rectangles), frame.Update) + // The platform still holds base rectangles. A frame that carries fewer has + // to say so: a rebuild, or a shrink whose range runs to the new end, which + // every backend applies to the base and then truncates. + update := frame.Update + if len(frame.Rectangles) != count { + t.Fatalf("frame carries %d rectangles, the renderer holds %d", len(frame.Rectangles), count) } - if !frame.Update.Rebuild || frame.Update.Count != count { - t.Fatalf("update = %+v, want a rebuild of all %d rectangles", frame.Update, count) + if !update.Rebuild && (!update.Shrink || update.First > count || update.First+update.Count != count) { + t.Fatalf("update = %+v cannot take the platform from %d rectangles to %d", update, base, count) } } diff --git a/app/painter.go b/app/painter.go index 2fb0c0dda..0b7720968 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1,12 +1,14 @@ package app import ( + "bytes" "errors" "fmt" "math" "slices" "time" "unicode" + "unsafe" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/framebuild" @@ -87,7 +89,6 @@ type painter struct { // allocations alive, so equal pointers mean equal bytes) lets a repaint that // declared the same hits reuse both instead of mirroring the list again. publishedHits []gfx.Hit - semanticDirty []gfx.ID publishedFocus gfx.ID publishedTrap gfx.ID publishedInitial gfx.ID @@ -100,13 +101,13 @@ type painter struct { publishedComposing bool publishedTextField bool hitsPublished bool - // hitsSame remembers, for the canvas as painted, whether its hits equal - // publishedHits (0 unknown, 1 equal, 2 different), so the focus settling - // and the publish of one paint compare the list once. - hitsSame uint8 - // focusSynced says the focus was synced with the canvas as painted, so the - // publish need not sync it again. - focusSynced bool + // hitChanges is how the canvas as painted differs from publishedHits, + // worked out once per paint for the focus settling, the publish and the + // semantic mirror (see diffHits). + hitChanges hitDiff + // focusSettled is what was decided about the focus for the canvas as + // painted, so the publish of a repaint does not decide it again. + focusSettled focusSettlement labelNames map[gfx.ID]string labelNamePeak int // controls draws the window buttons of a custom titlebar, on platforms where @@ -1050,6 +1051,17 @@ func (painter *painter) titlebarInsets() (leading, trailing float32) { return platformTitlebarInsets() } +// focusSettlement is what a paint decided about the focus: nothing yet, synced +// with the canvas, or kept because the canvas asks for nothing the focus and the +// input regions do not already reflect. +type focusSettlement uint8 + +const ( + focusUnsettled focusSettlement = iota + focusSynced + focusReused +) + // maxFocusPasses bounds the paints settleFocus adds to one frame: a page whose // every paint moves the focus somewhere new shows the last move. const maxFocusPasses = 2 @@ -1064,11 +1076,12 @@ func (painter *painter) settleFocus() { } for range maxFocusPasses { if !painter.regionsNeedSync() { + painter.focusSettled = focusReused return } before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus() painter.focus.Sync(painter.canvas) - painter.focusSynced = true + painter.focusSettled = focusSynced if painter.focus.Focused() == before && painter.focus.KeyboardFocus() == beforeVisible { return } @@ -1089,7 +1102,7 @@ func (painter *painter) regionsNeedSync() bool { } func (painter *painter) paintCanvas() { - painter.hitsSame, painter.focusSynced = 0, false + painter.hitChanges.known, painter.focusSettled = false, focusUnsettled if painter.paint == nil { return } @@ -1139,10 +1152,14 @@ func (painter *painter) publish() (platform.Frame, error) { // A repaint settled the focus already; a publish of a canvas painted outside // repaint syncs it here. hitStructuresUnchanged := painter.hitStructuresUnchanged() - if !painter.focusSynced && painter.regionsNeedSync() { - painter.focus.Sync(painter.canvas) - painter.focusSynced = true - } else if !painter.focusSynced { + if painter.focusSettled == focusUnsettled { + painter.focusSettled = focusReused + if painter.regionsNeedSync() { + painter.focus.Sync(painter.canvas) + painter.focusSettled = focusSynced + } + } + if painter.focusSettled == focusReused { painter.reusedHits++ } if err := painter.syncCursor(); err != nil { @@ -1243,7 +1260,7 @@ func (painter *painter) trim() { framebuild.ReleaseTail(painter.accessibility, &painter.tails.accessibility) painter.hitScratch = framebuild.TrimCapacity(painter.hitScratch) painter.publishedHits = framebuild.TrimCapacity(painter.publishedHits) - painter.semanticDirty = framebuild.TrimCapacity(painter.semanticDirty) + painter.hitChanges.dirty = framebuild.TrimCapacity(painter.hitChanges.dirty) painter.publishedReturns = framebuild.TrimCapacity(painter.publishedReturns) painter.accessibility = framebuild.TrimCapacity(painter.accessibility) if painter.labelNamePeak > 4096 && len(painter.labelNames)*4 < painter.labelNamePeak { @@ -1605,13 +1622,7 @@ func (painter *painter) hitStructuresUnchanged() bool { if !painter.structuresUnchanged() { return false } - if painter.hitsSame == 0 { - painter.hitsSame = 2 - if hits := painter.canvas.Hits(); len(hits) == len(painter.publishedHits) && sameHits(painter.publishedHits, hits) { - painter.hitsSame = 1 - } - } - return painter.hitsSame == 1 + return painter.diffHits().same } // regionStructuresUnchanged reports whether the paint produced the same input @@ -1632,16 +1643,7 @@ func (painter *painter) regionStructuresUnchanged() bool { !slices.Equal(painter.canvas.FocusReturns(), painter.publishedReturns) { return false } - hits := painter.canvas.Hits() - if len(hits) != len(painter.publishedHits) { - return false - } - for index := range hits { - if !sameRegionHit(&painter.publishedHits[index], &hits[index]) { - return false - } - } - return true + return painter.diffHits().sameRegions } // sameRegionHit compares the hit fields Focus.Sync copies into an input.Region. @@ -1661,6 +1663,7 @@ func sameRegionHit(published, current *gfx.Hit) bool { published.BlockSurface == current.BlockSurface && published.Container == current.Container && published.IsLabel == current.IsLabel && + published.Presentational == current.Presentational && published.Backdrop == current.Backdrop && published.MovesWindow == current.MovesWindow && published.PassSecondary == current.PassSecondary && @@ -1698,22 +1701,100 @@ func (painter *painter) structuresUnchanged() bool { return true } -// sameHits reports whether two hit lists are identical in the fields the -// semantic tree and the accessibility payload read. The text-editor geometry -// lives beside the hits (Canvas.HitText) and feeds neither, so it is not part of -// the comparison. Strings compare by content: a page that formats a label every -// frame makes a new allocation of the same text, and that is an unchanged hit. -// The index into the text table can only make the comparison stricter (an -// unnecessary publish), never more permissive. -func sameHits(published, current []gfx.Hit) bool { - return slices.Equal(published, current) +// maxPatchedHits is the most changed controls the semantic mirror patches in +// place; past it, rebuilding every entry is no dearer than finding them. +const maxPatchedHits = 64 + +// hitDiff is how one paint's hits differ from the published ones. Hits compare +// whole: the semantic tree and the accessibility payload read every field. The +// text-editor geometry lives beside the hits (Canvas.HitText) and feeds +// neither, so it is not part of the comparison. Strings compare by content: a +// page that formats a label every frame makes a new allocation of the same +// text, and that is an unchanged hit (see sameHit). The index into the text +// table can only make the comparison stricter (an unnecessary publish), never +// more permissive. +type hitDiff struct { + known bool + // same is set when every hit equals its published counterpart. + same bool + // sameRegions is set when every hit equals its counterpart in the fields an + // input region is built from (sameRegionHit): a label, value or description + // change keeps every region. + sameRegions bool + // patchable is set when the hits kept their identities and kinds and at + // most maxPatchedHits of them changed; dirty then names those controls. + patchable bool + dirty []gfx.ID +} + +// sameHit reports whether two hits are equal. Most hits of a repaint are the +// published ones again, byte for byte, so the bytes are compared first: Go +// strings are immutable and publishedHits keeps the previous frame's strings +// reachable, so the same pointer cannot name different text, and padding can +// only make the bytes differ. Hits whose bytes differ compare by value, which +// is what tells a label formatted again with the same words from a change. +func sameHit(published, current *gfx.Hit) bool { + size := unsafe.Sizeof(*published) + left := unsafe.Slice((*byte)(unsafe.Pointer(published)), size) + right := unsafe.Slice((*byte)(unsafe.Pointer(current)), size) + return bytes.Equal(left, right) || *published == *current +} + +// diffHits compares the canvas as painted with publishedHits once per paint, +// in one pass, and answers every caller of that paint from the result. +func (painter *painter) diffHits() *hitDiff { + diff := &painter.hitChanges + if diff.known { + return diff + } + diff.known = true + diff.dirty = diff.dirty[:0] + current, published := painter.canvas.Hits(), painter.publishedHits + if len(current) != len(published) { + diff.same, diff.sameRegions, diff.patchable = false, false, false + return diff + } + diff.same, diff.sameRegions, diff.patchable = true, true, true + for index := range current { + now, was := ¤t[index], &published[index] + if sameHit(was, now) { + continue + } + diff.same = false + if diff.sameRegions && !sameRegionHit(was, now) { + diff.sameRegions = false + } + if diff.patchable { + diff.patchable = now.ID == was.ID && now.IsLabel == was.IsLabel && + now.Presentational == was.Presentational && now.Block == was.Block && now.MovesWindow == was.MovesWindow && + now.Backdrop == was.Backdrop + // A zero ID is tracked like any other: it marks every zero-ID node + // (headings, groups, live regions) for a rebuild, and matches nothing + // for an occluder or drag region, which has none. + if diff.patchable && !slices.Contains(diff.dirty, now.ID) { + diff.dirty = append(diff.dirty, now.ID) + diff.patchable = len(diff.dirty) <= maxPatchedHits + } + } + if !diff.patchable { + // Only the regions are still in question, and they read a subset of + // each hit: compare just that for the rest of the list. + for rest := index + 1; diff.sameRegions && rest < len(current); rest++ { + diff.sameRegions = sameRegionHit(&published[rest], ¤t[rest]) + } + break + } + } + return diff } // recordHitStructures keeps the state that lets the next repaint skip the // region and semantic mirror when nothing that feeds them changed. func (painter *painter) recordHitStructures() { painter.publishedHits = append(painter.publishedHits[:0], painter.canvas.Hits()...) - painter.hitsSame = 1 + painter.hitChanges.known = true + painter.hitChanges.same, painter.hitChanges.sameRegions, painter.hitChanges.patchable = true, true, true + painter.hitChanges.dirty = painter.hitChanges.dirty[:0] painter.publishedFocus = painter.focus.Focused() painter.publishedTrap = painter.canvas.TrappedFocusScope() painter.publishedInitial = painter.canvas.InitialFocus() @@ -1750,46 +1831,19 @@ func (painter *painter) syncSemantics(incremental bool) (changed bool) { canvasHits := painter.canvas.Hits() // incremental is set when only the hit list changed: the focus, text state // and view are the same, so a control whose hit and label are unchanged - // keeps its accessibility node. Compare the raw hits first and remember the - // few ids whose entry may have moved; a structural change, a label-map - // fallback or too many dirty ids falls back to the full mirror below. - fast := incremental && len(canvasHits) == len(painter.publishedHits) - dirty := painter.semanticDirty[:0] - if fast { - for index := range canvasHits { - current, previous := &canvasHits[index], &painter.publishedHits[index] - if current.ID != previous.ID || current.IsLabel != previous.IsLabel || - current.Block != previous.Block || current.MovesWindow != previous.MovesWindow || - current.Backdrop != previous.Backdrop { - fast = false - break - } - if *current != *previous { - // A zero ID is tracked like any other: it marks every zero-ID - // node (headings, groups, live regions) for a rebuild below, and - // matches nothing for an occluder or drag region, which has none. - known := false - for _, id := range dirty { - if id == current.ID { - known = true - break - } - } - if !known { - dirty = append(dirty, current.ID) - if len(dirty) > 64 { - fast = false - break - } - } - } - } + // keeps its accessibility node. The paint's hit diff names the few ids + // whose entry may have moved; a structural change, a label-map fallback or + // too many dirty ids falls back to the full mirror below. + fast := false + var dirty []gfx.ID + if incremental { + diff := painter.diffHits() + fast, dirty = diff.patchable, diff.dirty } - painter.semanticDirty = dirty for index := range canvasHits { hit := &canvasHits[index] switch { - case hit.Block, hit.MovesWindow: + case hit.Block, hit.MovesWindow, hit.Presentational: case hit.IsLabel: labelled = true switch { diff --git a/app/status_item.go b/app/status_item.go index 8db5472f5..e59fc5f26 100644 --- a/app/status_item.go +++ b/app/status_item.go @@ -111,8 +111,10 @@ type StatusItemControl interface { // menu bar on macOS, the notification area on Windows, the StatusNotifier host // (the tray of most Linux desktops) elsewhere. type StatusItem struct { - control StatusItemControl - removed atomic.Bool + control StatusItemControl + removed atomic.Bool + application *Application + preview atomic.Pointer[statusPreview] } // SetIcon replaces the icon. Like SetTooltip it must be called on the event-loop @@ -138,6 +140,9 @@ func (item *StatusItem) SetTooltip(tooltip string) { // called from any goroutine. func (item *StatusItem) Remove() { if item != nil && !item.removed.Swap(true) { + if preview := item.preview.Swap(nil); preview != nil { + item.application.Post(preview.close) + } item.control.Remove() } } diff --git a/app/status_preview.go b/app/status_preview.go new file mode 100644 index 000000000..68e903898 --- /dev/null +++ b/app/status_preview.go @@ -0,0 +1,161 @@ +package app + +import ( + "time" + + "github.com/vivaui/viva/gfx" +) + +const statusPreviewLeaveDelay = 220 * time.Millisecond + +// StatusPreview describes the content of a non-activating status item preview. +// Viva sets the window mode and anchor. Opened receives the window or the error +// from opening it, so the application can release content it prepared on failure. +type StatusPreview struct { + Config Config + Opened func(*Window, error) +} + +// statusHoverControl is the optional part of StatusItemControl used by hosts +// that report native pointer entry and exit. Transitions run on the event loop. +type statusHoverControl interface { + SetStatusHover(func(anchor StatusAnchor, entered bool)) bool +} + +// statusMenuControl is the optional part of StatusItemControl used by hosts +// that cache the native menu outside the application. +type statusMenuControl interface{ RefreshMenu() } + +// SetHoverPreview shows build's window when the pointer rests on the icon. +// Call it on the event loop. Passing nil disables the preview and closes it. +// False means the host cannot provide a usable hover event for this icon. +// The normal click and menu remain available. A preview closes after the +// pointer leaves both surfaces, or when the application closes the window. +// While a preview is enabled the system tooltip is not shown, so SetTooltip has +// no visible effect. Windows reports false when the icon is hidden in the +// overflow area at that moment and does not retry: call it again once the icon +// is visible. +func (item *StatusItem) SetHoverPreview(build func() StatusPreview) bool { + if item == nil || item.removed.Load() { + return false + } + if build == nil { + if preview := item.preview.Swap(nil); preview != nil { + preview.close() + } + if host, ok := item.control.(statusHoverControl); ok { + return host.SetStatusHover(nil) + } + return true + } + host, ok := item.control.(statusHoverControl) + if !ok { + return false + } + if preview := item.preview.Load(); preview != nil { + preview.build = build + } else { + preview = &statusPreview{item: item, build: build} + item.preview.Store(preview) + if !host.SetStatusHover(preview.hover) { + item.preview.CompareAndSwap(preview, nil) + preview.close() + return false + } + if item.removed.Load() { + item.preview.CompareAndSwap(preview, nil) + return false + } + } + return true +} + +// RefreshMenu tells the current host to reload the menu after its contents +// change. Call it on the event loop. Hosts that build on each open do nothing. +func (item *StatusItem) RefreshMenu() { + if item != nil && !item.removed.Load() { + if menu, ok := item.control.(statusMenuControl); ok { + menu.RefreshMenu() + } + } +} + +type statusPreview struct { + item *StatusItem + build func() StatusPreview + window *Window + stop func() + onIcon, onWindow bool +} + +func (p *statusPreview) hover(anchor StatusAnchor, entered bool) { + if p.item.removed.Load() || entered == p.onIcon { + return + } + p.onIcon = entered + if !entered { + p.leave() + return + } + p.cancelLeave() + if p.window != nil { + return + } + spec := p.build() + cfg := spec.Config + if cfg.Paint == nil || p.item.removed.Load() || p.item.preview.Load() != p { + return + } + cfg.WindowMode, cfg.Anchor, cfg.Origin = WindowNotification, anchor, nil + pointer, closed := cfg.OnPointer, cfg.OnClosed + cfg.OnPointer = func(event gfx.PointerEvent) gfx.EventResult { + switch event.Kind { + case gfx.PointerExit: + p.onWindow = false + p.leave() + case gfx.PointerMove, gfx.PointerDown: + p.onWindow = true + p.cancelLeave() + } + if pointer != nil { + return pointer(event) + } + return gfx.EventResult{} + } + cfg.OnClosed = func() { + p.window, p.onWindow = nil, false + p.cancelLeave() + if closed != nil { + closed() + } + } + window, err := p.item.application.OpenWindow(cfg, nil) + p.window = window + if spec.Opened != nil { + spec.Opened(window, err) + } +} + +func (p *statusPreview) leave() { + if p.window == nil || p.onIcon || p.onWindow || p.stop != nil { + return + } + p.stop = p.item.application.PostAfter(statusPreviewLeaveDelay, func() { + p.stop = nil + p.close() + }) +} + +func (p *statusPreview) cancelLeave() { + if p.stop != nil { + p.stop() + p.stop = nil + } +} + +func (p *statusPreview) close() { + p.cancelLeave() + if p.window != nil { + p.window.Close() + } +} diff --git a/app/status_preview_bench_test.go b/app/status_preview_bench_test.go new file mode 100644 index 000000000..586f6c393 --- /dev/null +++ b/app/status_preview_bench_test.go @@ -0,0 +1,46 @@ +//go:build darwin || windows || linux + +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// Measure the public API and event dispatch with an in-memory host. Window +// creation includes app bookkeeping, not a native graphics driver or compositor. +func BenchmarkStatusPreview(b *testing.B) { + for _, path := range []string{"configure", "duplicate-enter", "open-close", "refresh-menu"} { + b.Run(path, func(b *testing.B) { + host := &previewTestHost{} + application := &Application{host: host} + item, err := application.AddStatusItem(StatusItemConfig{Icon: StatusIcon{Size: 1, RGBA: make([]byte, 4)}}) + if err != nil { + b.Fatal(err) + } + build := func() StatusPreview { return StatusPreview{Config: Config{Paint: func(*gfx.Canvas, gfx.Size) {}}} } + item.SetHoverPreview(build) + if path == "duplicate-enter" { + host.hover(StatusAnchor{}, true) + defer host.windows[0].Close() + } + b.ReportAllocs() + for b.Loop() { + switch path { + case "configure": + item.SetHoverPreview(build) + case "duplicate-enter": + host.hover(StatusAnchor{}, true) + case "open-close": + host.hover(StatusAnchor{}, true) + host.windows[0].Close() + host.windows = host.windows[:0] + host.hover(StatusAnchor{}, false) + case "refresh-menu": + item.RefreshMenu() + } + } + }) + } +} diff --git a/app/status_preview_test.go b/app/status_preview_test.go new file mode 100644 index 000000000..21febafc0 --- /dev/null +++ b/app/status_preview_test.go @@ -0,0 +1,216 @@ +//go:build darwin || windows || linux + +package app + +import ( + "testing" + "time" + + "github.com/vivaui/viva/gfx" +) + +type previewTestHost struct { + fakeHost + hover func(StatusAnchor, bool) + posts chan func() + refreshes int +} + +func (h *previewTestHost) AddStatusItem(cfg StatusItemConfig) (StatusItemControl, error) { + item, err := h.fakeHost.AddStatusItem(cfg) + return previewTestIcon{item, h}, err +} + +func (h *previewTestHost) OpenWindow(cfg Config, canvas *gfx.Canvas, closed func()) (WindowControl, error) { + return h.fakeHost.OpenWindow(cfg, canvas, func() { + if cfg.OnClosed != nil { + cfg.OnClosed() + } + closed() + }) +} + +func (h *previewTestHost) Post(fn func()) { h.posts <- fn } + +type previewTestIcon struct { + StatusItemControl + host *previewTestHost +} + +func (i previewTestIcon) SetStatusHover(fn func(StatusAnchor, bool)) bool { + i.host.hover = fn + return true +} + +func (i previewTestIcon) RefreshMenu() { i.host.refreshes++ } + +func TestStatusPreviewCrossesGapAndClosesOnce(t *testing.T) { + host := &previewTestHost{posts: make(chan func(), 4)} + app := &Application{host: host} + t.Cleanup(func() { + for _, window := range host.windows { + window.Close() + } + }) + item, err := app.AddStatusItem(StatusItemConfig{Icon: StatusIcon{Size: 1, RGBA: make([]byte, 4)}}) + if err != nil { + t.Fatal(err) + } + closed := 0 + if !item.SetHoverPreview(func() StatusPreview { + return StatusPreview{Config: Config{ + Paint: func(*gfx.Canvas, gfx.Size) {}, + OnClosed: func() { closed++ }, + }} + }) { + t.Fatal("preview registration failed") + } + anchor := StatusAnchor{set: true} + host.hover(anchor, true) + host.hover(anchor, true) + if len(host.windows) != 1 || host.windows[0].config.WindowMode != WindowNotification || host.windows[0].config.Anchor != anchor { + t.Fatal("expected one non-activating window beside the icon") + } + window := host.windows[0] + host.hover(anchor, false) + window.config.OnPointer(gfx.PointerEvent{Kind: gfx.PointerMove}) + if window.done { + t.Fatal("moving from the icon to the window closed the preview") + } + window.config.OnPointer(gfx.PointerEvent{Kind: gfx.PointerExit}) + select { + case task := <-host.posts: + task() + case <-time.After(2 * time.Second): + t.Fatal("leaving both surfaces did not post a close") + } + if !window.done || closed != 1 { + t.Fatalf("window done=%v, OnClosed called %d times", window.done, closed) + } + host.hover(anchor, true) + host.windows[1].Close() + host.hover(anchor, true) + if len(host.windows) != 2 { + t.Fatal("closing while still hovering reopened the preview") + } + host.hover(anchor, false) + host.hover(anchor, true) + item.Remove() + (<-host.posts)() + if len(host.windows) != 3 || closed != 3 || !host.windows[2].done { + t.Fatal("removing the item did not close its preview") + } +} + +func TestStatusPreviewWithoutHoverControlLeavesIconUsable(t *testing.T) { + host := &fakeHost{} + app := &Application{host: host} + clicked := false + item, err := app.AddStatusItem(StatusItemConfig{ + Icon: StatusIcon{Size: 1, RGBA: make([]byte, 4)}, + OnClick: func(StatusClick) { clicked = true }, + }) + if err != nil { + t.Fatal(err) + } + if item.SetHoverPreview(func() StatusPreview { t.Fatal("built on unsupported host"); return StatusPreview{} }) { + t.Fatal("ordinary status item unexpectedly supports hover") + } + if !item.SetHoverPreview(nil) || !item.SetHoverPreview(nil) { + t.Fatal("disabling a preview must succeed on a host without hover support") + } + host.items[0].config.OnClick(StatusClick{}) + if !clicked { + t.Fatal("normal click was lost") + } +} + +func TestStatusPreviewClosesBeforeClickAndMenuCallbacks(t *testing.T) { + for _, event := range []string{"click", "menu"} { + t.Run(event, func(t *testing.T) { + host := &previewTestHost{posts: make(chan func(), 4)} + application := &Application{host: host} + called, closed := 0, 0 + check := func() { + t.Helper() + called++ + if len(host.windows) != 1 || !host.windows[0].done || closed != 1 { + t.Fatal("native callback ran before the preview closed") + } + } + item, err := application.AddStatusItem(StatusItemConfig{ + Icon: StatusIcon{Size: 1, RGBA: make([]byte, 4)}, + OnClick: func(click StatusClick) { + check() + if click.Button != gfx.PointerButtonPrimary || !click.PanelDismissed { + t.Fatal("click wrapping changed the native event") + } + }, + Menu: func() []MenuItem { check(); return []MenuItem{{Title: "current menu"}} }, + }) + if err != nil { + t.Fatal(err) + } + item.SetHoverPreview(func() StatusPreview { + return StatusPreview{Config: Config{Paint: func(*gfx.Canvas, gfx.Size) {}, OnClosed: func() { closed++ }}} + }) + host.hover(StatusAnchor{}, true) + if event == "click" { + host.items[0].config.OnClick(StatusClick{Button: gfx.PointerButtonPrimary, PanelDismissed: true}) + } else if menu := host.items[0].config.Menu(); len(menu) != 1 || menu[0].Title != "current menu" { + t.Fatal("menu wrapping lost the supplied entries") + } + if called != 1 || len(application.windows) != 0 { + t.Fatalf("callback count = %d, live windows = %d", called, len(application.windows)) + } + }) + } +} + +func TestStatusPreviewReportsOpenFailureAndCanRetry(t *testing.T) { + host := &previewTestHost{posts: make(chan func(), 4)} + host.reject = "preview" + application := &Application{host: host} + item, err := application.AddStatusItem(StatusItemConfig{Icon: StatusIcon{Size: 1, RGBA: make([]byte, 4)}}) + if err != nil { + t.Fatal(err) + } + var opened *Window + var reported error + calls := 0 + item.SetHoverPreview(func() StatusPreview { + return StatusPreview{ + Config: Config{Title: "preview", Paint: func(*gfx.Canvas, gfx.Size) {}}, + Opened: func(window *Window, err error) { calls++; opened, reported = window, err }, + } + }) + host.hover(StatusAnchor{}, true) + if calls != 1 || opened != nil || reported == nil || reported.Error() != "rejected" || len(application.windows) != 0 { + t.Fatalf("open failure = (%p, %v), calls=%d, live windows=%d", opened, reported, calls, len(application.windows)) + } + host.reject = "" + host.hover(StatusAnchor{}, false) + host.hover(StatusAnchor{}, true) + if calls != 2 || opened == nil || reported != nil { + t.Fatalf("retry = (%p, %v), calls=%d", opened, reported, calls) + } + opened.Close() +} + +func TestStatusPreviewRefreshesTheCachedMenu(t *testing.T) { + host := &previewTestHost{} + application := &Application{host: host} + item, err := application.AddStatusItem(StatusItemConfig{Icon: StatusIcon{Size: 1, RGBA: make([]byte, 4)}}) + if err != nil { + t.Fatal(err) + } + item.RefreshMenu() + if host.refreshes != 1 { + t.Fatalf("menu refreshes = %d, want 1", host.refreshes) + } + item.Remove() + item.RefreshMenu() + if host.refreshes != 1 { + t.Fatal("removed icon refreshed its cached menu") + } +} diff --git a/base/accessors.go b/base/accessors.go index 2819da67b..b96e86b82 100644 --- a/base/accessors.go +++ b/base/accessors.go @@ -648,6 +648,9 @@ func (x *MenuRow) GetChecked() int8 { return x.checked } // GetDescription reads the description of MenuRow for the styled painting layer. func (x *MenuRow) GetDescription() string { return x.description } +// GetMnemonic reads the mnemonic of MenuRow for the styled painting layer. +func (x *MenuRow) GetMnemonic() string { return x.mnemonic } + // GetDestructive reads the destructive of MenuRow for the styled painting layer. func (x *MenuRow) GetDestructive() bool { return x.destructive } diff --git a/base/frame.go b/base/frame.go index ece512803..3b2001f83 100644 --- a/base/frame.go +++ b/base/frame.go @@ -229,6 +229,8 @@ type Extra struct { addons int32 // 1 + the index of the field's icon and button in frame.addons, or 0 focusGroup FocusAxis // FocusGroup: the arrow keys that move the focus between the controls inside; zero is none highlight int32 // 1 + the index of this text's query in frame.highlights; zero is none + textArea int32 // 1 + the index of the TextSelectionArea the element is in frame.textAreas, or 0 + unselectable bool // Unselectable: the element's texts take no part in the area they are in focusOrder FocusOrder // FocusOrder: how the group chooses the next member; nil is its axis layout Layout // CustomLayout: who measures and places the children swatchFlush bool // a ColorSwatch fills its border with its color @@ -305,10 +307,20 @@ type Frame struct { Lines []string highlights []textHighlight paintHighlightFn func(*Frame, *Node, string, Rect, gfx.TextStyle, gfx.Alignment) - controls any // the layer above's control declarations: see widgetsOf - Ellipses []gfx.EllipsisCache // the cut-off ends of wrapped texts, kept between frames - Wraps []wrapCache // the full line sets of wrapped texts, kept between frames - wrapCursor int + // textAreas are the TextSelectionAreas of the paint; area is the one being + // painted, whose texts are collected unless areaSkip says a control or an + // Unselectable element they are in keeps them out. lineAt is where the next line + // of the text being collected is looked for in its source, and selectionSpans + // reuses the spans of a selected line. + textAreas []*TextSelectionState + area *TextSelectionState + areaSkip int32 + lineAt int + selectionSpans []gfx.TextSpan + controls any // the layer above's control declarations: see widgetsOf + Ellipses []gfx.EllipsisCache // the cut-off ends of wrapped texts, kept between frames + Wraps []wrapCache // the full line sets of wrapped texts, kept between frames + wrapCursor int // tails is how long each reused slice that holds pointers was when the last // frame ended: what lies past its length up to there is the last frame's, // cleared by releaseTail so a page that shrank does not keep it reachable. @@ -358,6 +370,9 @@ func (View *View) Begin(Surface *gfx.Canvas, Palette Theme, bounds Rect) *Frame f.Surface, f.Palette, f.bounds, f.done = Surface, Palette, bounds, false f.Nodes = f.Nodes[:0] f.Lines = f.Lines[:0] + clear(f.textAreas) + f.textAreas = f.textAreas[:0] + f.area, f.areaSkip = nil, 0 clear(f.highlights) f.highlights = f.highlights[:0] f.Exts = append(f.Exts[:0], Extra{}) diff --git a/base/menu.go b/base/menu.go index c8a44ea97..13b961644 100644 --- a/base/menu.go +++ b/base/menu.go @@ -2,6 +2,8 @@ package base import ( "time" + "unicode" + "unicode/utf8" "unsafe" "github.com/vivaui/viva/gfx" @@ -312,6 +314,7 @@ type MenuItemParts struct { Theme gfx.Theme Rect gfx.Rect Label string + Mnemonic string Description string Shortcut string Checked bool @@ -360,7 +363,7 @@ func (m *MenuItems) paintItem(parts style.MenuItemPaint) { } m.drawItem(MenuItemParts{ Canvas: parts.Canvas, Theme: parts.Theme, Rect: parts.Bounds, - Label: parts.Label, Description: parts.Description, Shortcut: parts.Shortcut, + Label: parts.Label, Mnemonic: parts.Mnemonic, Description: parts.Description, Shortcut: parts.Shortcut, Checked: parts.Checked, Selected: parts.Selected, Expanded: parts.Expanded, Disabled: parts.Disabled, Active: parts.Active, Destructive: parts.Destructive, Separator: parts.Separator, GroupLabel: parts.GroupLabel, Foreground: parts.Foreground, @@ -377,6 +380,7 @@ func (m *MenuItems) paintPanel(Surface *gfx.Canvas, bounds gfx.Rect, Palette gfx type MenuRow struct { Kind MenuRowKind Label string + mnemonic string description string icon gfx.Icon // The shortcut the row shows, a keymap.Chord's fields: the Page's type would @@ -539,6 +543,15 @@ func (item MenuItem) Description(Text string) MenuItem { return item } +// Mnemonic moves focus to this item before label typeahead when its key is +// pressed, unless a label search is already in progress. It only moves focus: +// Enter still activates, unlike the activate-on-key mnemonics of native menus. +// The first rune is matched case-insensitively. +func (item MenuItem) Mnemonic(key string) MenuItem { + item.menu.Items[item.i].mnemonic = key + return item +} + // Icon paints icon before the item's label. func (item MenuItem) Icon(icon gfx.Icon) MenuItem { item.menu.Items[item.i].icon = icon @@ -632,6 +645,14 @@ func (p *Page) MenuKey(event gfx.KeyEvent) (gfx.EventResult, bool) { if result, ok := m.submenuKey(event, inside); ok { return result, true } + if text := event.Text; !event.Release && event.Modifiers&^gfx.ModifierShift == 0 && text != "" { + // A label search in progress owns the letters: "wr" keeps searching + // instead of jumping to an item whose mnemonic is R. + if id, ok := m.mnemonicMatch(text, event.Target); ok && !m.typeahead.Typing(ClockEpoch.Add(m.f.Surface.Now())) { + m.typeahead.Reset() + return gfx.EventResult{Handled: true, Repaint: true, Focus: id, FocusVisible: true}, true + } + } if text := event.Text; !event.Release && event.Modifiers&^gfx.ModifierShift == 0 && (text != "" || event.Key == gfx.KeySpace) { if text == "" { text = " " @@ -661,6 +682,29 @@ func (p *Page) MenuKey(event gfx.KeyEvent) (gfx.EventResult, bool) { return gfx.EventResult{}, false } +func (m *MenuItems) mnemonicMatch(text string, from gfx.ID) (gfx.ID, bool) { + r, size := utf8.DecodeRuneInString(text) + if r == utf8.RuneError || size != len(text) { + return gfx.ID{}, false + } + start := -1 + if row, ok := from.In(m.scope); ok { + start = int(row) - MenuRowsPart + } + for offset := 1; offset <= len(m.Items); offset++ { + index := (start + offset + len(m.Items)) % len(m.Items) + item := &m.Items[index] + if item.Kind != MenuRowItem || item.disabled || item.mnemonic == "" { + continue + } + mnemonic, mnemonicSize := utf8.DecodeRuneInString(item.mnemonic) + if mnemonicSize > 0 && unicode.ToLower(mnemonic) == unicode.ToLower(r) { + return m.scope.At(MenuRowsPart + index), true + } + } + return gfx.ID{}, false +} + // submenuKey opens the submenu of the row the keyboard is on with Right, Enter or // Space, its first row taking the focus, and goes back to that row with Left. func (m *MenuItems) submenuKey(event gfx.KeyEvent, inside bool) (gfx.EventResult, bool) { diff --git a/base/menu_parts_test.go b/base/menu_parts_test.go index a4b0fb4cb..a60fe0206 100644 --- a/base/menu_parts_test.go +++ b/base/menu_parts_test.go @@ -27,13 +27,16 @@ func TestAnUnpaintedMenuDrawsItsOwnPartsAndKeepsItsHits(t *testing.T) { rows = append(rows, parts) parts.Canvas.Fill(parts.Rect, rowColor) }) - menu.Item("One") + menu.Item("One").Mnemonic("o") menu.Item("Two") }) }) if len(rows) != 2 || rows[0].Label != "One" || rows[1].Label != "Two" { t.Fatalf("rows = %+v, want two actions", rows) } + if rows[0].Mnemonic != "o" { + t.Fatalf("mnemonic = %q, want o", rows[0].Mnemonic) + } if rows[0].Rect.Height <= 0 { t.Errorf("the first row has no rectangle: %+v", rows[0].Rect) } diff --git a/base/page.go b/base/page.go index 2179e79c8..c08403b3b 100644 --- a/base/page.go +++ b/base/page.go @@ -168,6 +168,7 @@ const ( pkDisclosure pkProgress pkAlertDialog + pkTextSelection pkKinds ) diff --git a/base/page_bases.go b/base/page_bases.go index 5428d0d21..efc927fe1 100644 --- a/base/page_bases.go +++ b/base/page_bases.go @@ -132,8 +132,8 @@ func SelectBase[T comparable](c C, Value *T, choices []T, Label func(T) string) } // TextFieldBase is TextField without a look: the editable text, with no padding, -// background, border or corners of its own. -func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string) Box { - b, _ := textFieldOf(c, Value, Label, placeholder, true, gfx.ID{}, nil) +// background, border or corners of its own. It takes the options of TextField. +func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { + b, _ := textFieldOf(c, Value, Label, placeholder, true, namedBy("TextFieldBase", opts), opts) return b } diff --git a/base/paint.go b/base/paint.go index 10b543d25..2a6787566 100644 --- a/base/paint.go +++ b/base/paint.go @@ -39,6 +39,22 @@ func (f *Frame) paintElement(i int32) { f.Surface.PushLayer(n.Band) defer f.Surface.PopLayer() } + if len(f.textAreas) > 0 { + // The texts of a TextSelectionArea are collected as it is painted, in reading + // order; a control inside it, or what Unselectable takes out, keeps its own. + if extra := &f.Exts[n.Ext]; extra.textArea != 0 { + area, skip := f.area, f.areaSkip + f.area, f.areaSkip = f.textAreas[extra.textArea-1], 0 + f.beginTextArea(f.area) + defer func() { + f.endTextArea(f.area) + f.area, f.areaSkip = area, skip + }() + } else if f.area != nil && (actsOnPress(n, extra) || extra.unselectable) { + f.areaSkip++ + defer func() { f.areaSkip-- }() + } + } if n.Flags&flagDialog != 0 { f.paintDialog(n) return @@ -69,7 +85,7 @@ func (f *Frame) paintElement(i int32) { f.Surface.BeginGlide(extra.glideIdentity(n), 0, gfx.Point{X: n.Rect.X + extra.glideScroll.X, Y: n.Rect.Y + extra.glideScroll.Y}, extra.glide) defer f.Surface.EndPose() } - if memo := f.Exts[n.Ext].memo; memo != 0 && f.memoFn != nil { + if memo := f.Exts[n.Ext].memo; memo != 0 && f.memoFn != nil && f.area == nil { if f.memoFn(f, i, true) { return } @@ -400,6 +416,14 @@ func (f *Frame) paintText(n *Node) { style.Direction = gfx.TextDirectionOf(n.Text) } lh := n.leading() + if f.area != nil && f.areaSkip == 0 { + f.beginSelectableText(n, r, style, alignment) + for k := int32(0); k < n.LineCount; k++ { + bounds := Rect{X: r.X, Y: r.Y + float32(k)*lh, Width: r.Width, Height: lh} + f.addSelectableLine(n, f.Lines[n.LineFirst+k], bounds, k == n.LineCount-1) + } + f.paintSelection() + } for k := int32(0); k < n.LineCount; k++ { bounds := Rect{X: r.X, Y: r.Y + float32(k)*lh, Width: r.Width, Height: lh} line := f.Lines[n.LineFirst+k] @@ -420,6 +444,11 @@ func (f *Frame) paintText(n *Node) { if clipped { f.Surface.Clip(r) } + if f.area != nil && f.areaSkip == 0 { + f.beginSelectableText(n, r, style, alignment) + f.addSelectableLine(n, n.Text, bounds, true) + f.paintSelection() + } f.paintLabel(n, n.Text, bounds, style, alignment) if n.TextDecor&textStrike != 0 { f.paintStrike(n.Text, bounds, style, alignment) diff --git a/components/text_selection.go b/base/text_selection.go similarity index 78% rename from components/text_selection.go rename to base/text_selection.go index aef475a1e..6a7fa3dae 100644 --- a/components/text_selection.go +++ b/base/text_selection.go @@ -1,4 +1,4 @@ -package components +package base import ( "math" @@ -9,7 +9,7 @@ import ( // TextPoint is a place in a run of painted texts that a selection can cross: // Surface numbers the text in reading order, from 0, and Offset is a byte -// offset in that text, as MarkdownView.OffsetAt reports it. +// offset in that text, as MarkdownView.OffsetAt or a TextSelectionArea reports it. type TextPoint struct { Surface int Offset int @@ -38,6 +38,50 @@ type TextSelection struct { dragging bool } +// TextRange is the selected part of one text, in byte offsets: of a Text in a +// TextSelectionArea, of the rendered text of a MarkdownView. Anchor is where the +// user began and Focus is where the pointer is now; either may be ahead of the +// other. Range clamps and orders them against the text, so a selection that was +// made before the text changed still copies the part that is there. +type TextRange struct { + Anchor, Focus int +} + +// Range returns the selected bytes, ordered and clamped to text. Clamping snaps +// both ends back to the start of the rune they point into, because a selection +// kept while a streaming message shortened can land inside a multi-byte +// character; without the snap SelectedText would return invalid UTF-8. +func (s TextRange) Range(text []byte) (start, end int) { + start, end = s.Anchor, s.Focus + if start > end { + start, end = end, start + } + start = snapRune(text, min(max(start, 0), len(text))) + end = snapRune(text, min(max(end, 0), len(text))) + return start, end +} + +// rangeIn is Range for a text held as a string. +func (s TextRange) rangeIn(text string) (start, end int) { + start, end = s.Anchor, s.Focus + if start > end { + start, end = end, start + } + start = snapRune(text, min(max(start, 0), len(text))) + end = snapRune(text, min(max(end, 0), len(text))) + return start, end +} + +// snapRune moves offset back to the leading byte of the rune it points into. +// Offsets that are already at a boundary, including len(text), are returned as +// they are. +func snapRune[T string | []byte](text T, offset int) int { + for offset > 0 && offset < len(text) && text[offset]&0xC0 == 0x80 { + offset-- + } + return offset +} + // TextSelectionResult says what Pointer did with an event. type TextSelectionResult struct { // Handled is true when the event belongs to the selection, so nothing else @@ -152,28 +196,28 @@ func (selection *TextSelection) Pointer(event gfx.PointerEvent, at func(gfx.Poin // selection begins or ends only the part on its side. Within one surface the // Anchor and the Focus keep the order the drag gave them, so a drag upward is // not turned round on each paint. The offsets of a surface the selection runs -// past the end of are larger than its text; MarkdownSelection clamps them. -func (selection *TextSelection) In(surface int) MarkdownSelection { +// past the end of are larger than its text; TextRange.Range clamps them. +func (selection *TextSelection) In(surface int) TextRange { if selection.Empty() { - return MarkdownSelection{} + return TextRange{} } first, last := selection.Anchor, selection.Focus if last.before(first) { first, last = last, first } if surface < first.Surface || surface > last.Surface { - return MarkdownSelection{} + return TextRange{} } if first.Surface == last.Surface { - return MarkdownSelection{Anchor: selection.Anchor.Offset, Focus: selection.Focus.Offset} + return TextRange{Anchor: selection.Anchor.Offset, Focus: selection.Focus.Offset} } switch surface { case first.Surface: - return MarkdownSelection{Anchor: first.Offset, Focus: math.MaxInt} + return TextRange{Anchor: first.Offset, Focus: math.MaxInt} case last.Surface: - return MarkdownSelection{Anchor: 0, Focus: last.Offset} + return TextRange{Anchor: 0, Focus: last.Offset} } - return MarkdownSelection{Anchor: 0, Focus: math.MaxInt} + return TextRange{Anchor: 0, Focus: math.MaxInt} } // Text is the selected text of surfaces texts in reading order, with separator @@ -181,7 +225,7 @@ func (selection *TextSelection) In(surface int) MarkdownSelection { // clipboard. text gives the text of one surface for the part In reports for it; // surfaces with nothing selected are skipped and add no separator. It returns "" // for an empty selection. -func (selection *TextSelection) Text(surfaces int, separator string, text func(surface int, part MarkdownSelection) string) string { +func (selection *TextSelection) Text(surfaces int, separator string, text func(surface int, part TextRange) string) string { if selection.Empty() { return "" } diff --git a/base/text_selection_area.go b/base/text_selection_area.go new file mode 100644 index 000000000..2f4c69844 --- /dev/null +++ b/base/text_selection_area.go @@ -0,0 +1,738 @@ +package base + +import ( + "math" + "strings" + "time" + "unicode/utf8" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +// SetPrimarySelection makes text the primary selection of an X11 desktop, which +// selecting text fills and a middle click pastes. The styled layer installs the +// system's; a host that installs nothing has none. +var SetPrimarySelection func(string) error + +// TextSelectionState is the selection of one TextSelectionArea: what the user has +// selected in it and where the last paint drew its texts. Keep it in the model +// next to what the area shows; its zero value selects nothing. +type TextSelectionState struct { + // Selection is the selected run, from the press (Anchor) to where the pointer + // or the keyboard took it (Focus). Surface numbers the area's texts in reading + // order, as the last paint drew them; Offset is a byte offset in that text. + Selection TextSelection + + id gfx.ID + handlers Handlers + bound *TextSelectionState // the state handlers were made for, so a copy of a state makes its own + canvas *gfx.Canvas + + // texts and lines are what the last paint drew, which the events between two + // paints are read against. + texts []selectableText + lines []selectableLine + // parent is the element the last text collected sits in, and inRow whether + // that element lays its children out in a row, which joins two texts with a tab. + parent int32 + + // pressed says a primary press on a text is held; press is where it went + // down, moved whether it has left that spot, and pointer where it is now. + pressed, moved bool + press, pointer gfx.Point + unit selectUnit + // span is the word or line the press picked, which a drag by words or lines + // keeps whole. anchor is where the last press began, which Shift with a press + // extends from even when that press selected nothing. + span [2]TextPoint + anchor TextPoint + hasAnchor bool + + focused bool // the area had the keyboard focus in the last paint, or lost it to nothing + page *Page + menuBody func(*MenuItems) + menuOpen bool + menuWas bool // the menu was open in the last paint: the keyboard is on its way back + menuAt gfx.Point + primary string // what the area last made the primary selection + + scroll *ScrollState // the area the area scrolls in, which a drag past its edge scrolls + scrollNode int32 // its element, whose rectangle the last paint gave it + scrollRect Rect + stepAt time.Duration +} + +// selectUnit is what a press selects and a drag extends by. +type selectUnit uint8 + +const ( + unitChar selectUnit = iota + unitWord + unitLine +) + +// selectableText is one text of an area as a paint drew it. +type selectableText struct { + text string + style gfx.TextStyle + align gfx.Alignment + // first and count are its lines in TextSelectionState.lines. + first, count int32 + bounds Rect // where its element put it + // tab joins it to the text before it with a tab instead of a line break: the two + // sit side by side in one row, as a label and its value. + tab bool +} + +// selectableLine is one line of a text: the source bytes from to to, drawn as +// shown in bounds. A line cut short by an ellipsis shows fewer bytes than it +// covers: the cut-off rest belongs to it. +type selectableLine struct { + from, to int + shown string + visible int // how many bytes of shown are the text's own, before an ellipsis + bounds Rect +} + +// TextSelectionArea declares a column whose texts the user can select with the +// pointer and copy, as the labels of a dialog, an error or a detail page are in a +// desktop application. Text, Paragraph and Wrap inside it take part, across their +// boundaries: a drag may begin in one and end in another. Text that belongs to a +// control does not (a button's, a link's, a field's, a label given LabelFor: +// anything inside an element that takes presses; a group region given HitWith to +// name its content keeps it in), nor what Unselectable takes out; a field and a +// view with a selection of its own keep theirs. +// +// A press on a text begins a selection, a double press selects a word and a triple +// press a line; Shift with a press extends it. A press in the area's blank part +// begins at the nearest text, so a click there drops the selection. Primary+C +// copies, Primary+A selects all the area holds, Shift with the arrow keys extends +// the selection and Escape drops it; a secondary press opens the page's Copy and +// Select All menu (see PageConfig.EditMenu). The selection is dropped when another +// control takes the keyboard. A drag past the edge of +// the scrolling area the area is in scrolls it. +// +// The area takes no Tab stop. Its texts are copied as their source: a text cut +// short by an ellipsis copies whole. Texts side by side in a row are joined with a +// tab, others with a line break. A text inside a Memo is drawn but not selected. +// +// ui.TextSelectionArea(c, &m.details).Gap(6).Children(func() { +// ui.Text(c, m.fingerprint) +// }) +func TextSelectionArea(c C, state *TextSelectionState) Box { + p := c.page + p.ForbidInMemo("TextSelectionArea") + if state == nil { + panic("ui: TextSelectionArea needs its state") + } + id := p.boundID(pkTextSelection, unsafe.Pointer(state)) + state.id = id + if state.bound != state { + state.bound = state + state.handlers = Handlers{Role: gfx.RoleGroup, Pointer: state.onPointer, Key: state.onKey} + state.menuBody = state.menu + } + state.handlers.parts = p.tree.Sub(id.Scope(), id.Name()) + p.controls = append(p.controls, controlEntry{ID: id, handlers: &state.handlers}) + if p.pointerRoute == nil { + p.keyRoute, p.pointerRoute = (*Page).RouteKey, (*Page).routePointer + } + canvas := c.f.Surface + state.canvas = canvas + if canvas != nil { + state.followFocus(canvas.Focused()) + } + state.menuWas = state.menuOpen + + state.scroll, state.scrollNode = nil, -1 + for i := c.f.Parent; i >= 0; i = c.f.Nodes[i].Parent { + if n := &c.f.Nodes[i]; n.Ext != 0 && c.f.Exts[n.Ext].scrollState != nil { + state.scroll, state.scrollNode = c.f.Exts[n.Ext].scrollState, i + break + } + } + if canvas != nil { + state.dragScroll(canvas) + } + + b := p.container(c.f.Column()) + b.HitWith(id, "", gfx.HitOptions{Role: gfx.RoleGroup, SkipTab: true}) + c.f.textAreas = append(c.f.textAreas, state) + c.f.Extra(b.i).textArea = int32(len(c.f.textAreas)) + + if p.shortcut(c, Primary, "c", id, 0, 0) && state.Has() { + state.copy() + } + if p.shortcut(c, Primary, "a", id, 0, 0) { + state.SelectAll() + } + state.page = p + ContextMenuAt(c, b, &state.menuOpen, state.menuAt, state.menuBody) + return b +} + +// actsOnPress reports whether an element takes presses, which keeps the text inside +// it out of the TextSelectionArea it is in: a button, a link, a label of a control. +// A group region, which declares a hit to name what it holds for assistive +// technology and does nothing when pressed, leaves its text in. +func actsOnPress(n *Node, extra *Extra) bool { + return n.Flags&flagHasHit != 0 && (n.Flags&flagLabelFor != 0 || extra.hit.Role != gfx.RoleGroup) +} + +// Unselectable keeps the element and what it holds out of the TextSelectionArea it +// is in: words the user has no use for copying, such as a decorative caption. +func (b Box) Unselectable() Box { + b.N() + b.f.Extra(b.i).unselectable = true + return b +} + +// Has reports whether text is selected. +func (s *TextSelectionState) Has() bool { + if s.Selection.Empty() { + return false + } + for i := range s.texts { + if s.selected(i) != "" { + return true + } + } + return false +} + +// Text is the selected text, what Primary+C puts on the clipboard: each text's +// selected part in reading order, the parts of two texts in a row joined with a +// tab and others with a line break. +func (s *TextSelectionState) Text() string { + if s.Selection.Empty() { + return "" + } + var out strings.Builder + for i := range s.texts { + piece := s.selected(i) + if piece == "" { + continue + } + if out.Len() > 0 { + if s.texts[i].tab { + out.WriteByte('\t') + } else { + out.WriteByte('\n') + } + } + out.WriteString(piece) + } + return out.String() +} + +// Clear drops the selection. +func (s *TextSelectionState) Clear() { + s.Selection.Clear() + s.pressed, s.hasAnchor = false, false +} + +// SelectAll selects every text the area held in its last paint. +func (s *TextSelectionState) SelectAll() { + s.Selection.SelectAll(len(s.texts), s.length) + s.pressed = false + s.publish() +} + +func (s *TextSelectionState) length(surface int) int { return len(s.texts[surface].text) } + +// selected is the selected part of text i. +func (s *TextSelectionState) selected(i int) string { + value := s.texts[i].text + start, end := s.Selection.In(i).rangeIn(value) + return value[start:end] +} + +// followFocus drops the selection once another control has taken the keyboard, as +// a selectable label's selection goes when it stops being the first responder. The +// area's own menu, which holds the keyboard while it is open, does not count, and +// neither does a press on nothing, which leaves the focus nowhere. +func (s *TextSelectionState) followFocus(focused gfx.ID) { + switch { + case focused == s.id: + s.focused = true + case s.menuOpen, s.menuWas: + case focused.IsZero(): + default: + if s.focused && !s.Selection.Empty() { + s.Clear() + } + s.focused = false + } +} + +func (s *TextSelectionState) copy() { + if value := s.Text(); value != "" && SetClipboardText != nil { + _ = SetClipboardText(value) + } +} + +// publish makes the selection the primary selection, where the desktop has one. +func (s *TextSelectionState) publish() { + if SetPrimarySelection == nil { + return + } + value := s.Text() + if value == "" || value == s.primary { + return + } + if SetPrimarySelection(value) == nil { + s.primary = value + } +} + +// menu is the body of the area's context menu: the page's words for Copy and +// Select All, which act on the area. +func (s *TextSelectionState) menu(menu *MenuItems) { + var labels EditMenuLabels + if s.page != nil && s.page.config.EditMenu != nil { + labels = *s.page.config.EditMenu + } + labels = labels.WithDefaults() + // The item chosen acts on the area and gives it the keyboard back, as a field's + // edit menu does. + if menu.Item(labels.Copy).Keys(Primary, "c").Disabled(!s.Has()).Clicked() { + s.copy() + s.page.editFocus = s.id + } + menu.Separator() + if menu.Item(labels.SelectAll).Keys(Primary, "a").Disabled(len(s.texts) == 0).Clicked() { + s.SelectAll() + s.page.editFocus = s.id + } +} + +// dragScroll scrolls the area the selection is dragged out of, a step of lines +// every 50 ms that grows with the distance past its edge, as a text view does. It +// asks for the frames of the steps only while a drag holds the pointer outside. +func (s *TextSelectionState) dragScroll(canvas *gfx.Canvas) { + if !s.pressed || !s.moved || s.scroll == nil { + return + } + top, bottom := s.scrollRect.Y, s.scrollRect.Y+s.scrollRect.Height + var distance float32 + switch { + case s.pointer.Y < top: + distance = s.pointer.Y - top + case s.pointer.Y > bottom: + distance = s.pointer.Y - bottom + default: + return + } + line := s.lineHeight() + if now := canvas.Now(); now-s.stepAt >= textDragStep { + s.stepAt = now + lines := min(1+float32(math.Abs(float64(distance)))/line, 8) + if distance < 0 { + lines = -lines + } + s.scroll.ScrollTo(min(max(s.scroll.Offset+float32(int(lines))*line, 0), s.scroll.Max())) + } + canvas.RequestFrameIn(textDragStep) +} + +const textDragStep = 50 * time.Millisecond + +// lineHeight is the height of a line of the area's first text, which a drag past +// the edge scrolls by. +func (s *TextSelectionState) lineHeight() float32 { + for _, line := range s.lines { + if line.bounds.Height > 0 { + return line.bounds.Height + } + } + return 16 +} + +// partOf is the text a press landed on, given the target of the event. +func (s *TextSelectionState) partOf(target gfx.ID) (int, bool) { + i, ok := target.In(s.handlers.parts) + return i, ok && i < len(s.texts) +} + +func (s *TextSelectionState) onPointer(event gfx.PointerEvent) gfx.EventResult { + at := gfx.Point{X: event.X, Y: event.Y} + switch event.Kind { + case gfx.PointerDown: + if event.Button == gfx.PointerButtonSecondary { + s.menuOpen, s.menuAt = true, at + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.id} + } + if event.Button != gfx.PointerButtonPrimary { + return gfx.EventResult{} + } + // A press beside the words, in the area's blank part, begins at the nearest of + // them, as a drag in a document does; a click there selects nothing. + var point TextPoint + if surface, onText := s.partOf(event.Target); onText { + point = s.pointIn(surface, at) + } else if nearest, ok := s.pointAt(at); ok { + point = nearest + } else { + had := !s.Selection.Empty() + s.Clear() + return gfx.EventResult{Handled: true, Repaint: had, Focus: s.id} + } + clicks := max(event.ClickCount, 1) + if event.Modifiers&gfx.ModifierShift != 0 && clicks == 1 && (s.hasAnchor || !s.Selection.Empty()) { + s.unit = unitChar + if s.Selection.Empty() { + s.Selection.Anchor = s.anchor + } + s.Selection.Focus = point + } else { + s.unit = unitChar + switch { + case clicks >= 3: + s.unit = unitLine + case clicks == 2: + s.unit = unitWord + } + s.span[0], s.span[1] = s.unitSpan(point) + s.Selection.Select(s.span[0], s.span[1]) + s.anchor, s.hasAnchor = point, true + } + s.pressed, s.moved, s.press, s.pointer = true, false, at, at + return gfx.EventResult{Handled: true, Repaint: true, Focus: s.id} + case gfx.PointerMove: + if !s.pressed { + return gfx.EventResult{} + } + s.pointer = at + if !s.moved && math.Abs(float64(at.X-s.press.X)) < 3 && math.Abs(float64(at.Y-s.press.Y)) < 3 { + return gfx.EventResult{Handled: true} + } + s.moved = true + return gfx.EventResult{Handled: true, Repaint: s.extendTo(at)} + case gfx.PointerUp: + if !s.pressed { + return gfx.EventResult{} + } + s.pressed = false + if s.moved { + s.extendTo(at) + } + if s.Selection.Empty() { + s.Selection.Clear() + } + s.publish() + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.PointerExit: + // The release of a held press was not seen: the system took the press, or + // the button came up outside the window. + if s.pressed { + s.pressed = false + s.publish() + return gfx.EventResult{Handled: true, Repaint: true} + } + } + return gfx.EventResult{} +} + +// extendTo moves the selection's focus to the text under a point of the window, by +// the unit of the press, and reports whether the selection changed. +func (s *TextSelectionState) extendTo(at gfx.Point) bool { + point, ok := s.pointAt(at) + if !ok { + return false + } + was := s.Selection + if s.unit == unitChar { + s.Selection.Focus = point + } else { + from, to := s.unitSpan(point) + if from.before(s.span[0]) { + s.Selection.Anchor, s.Selection.Focus = s.span[1], from + } else { + s.Selection.Anchor, s.Selection.Focus = s.span[0], to + } + } + return s.Selection != was +} + +// unitSpan is the unit of the press around a point: the point itself for +// characters, the word or the line of its text around it. +func (s *TextSelectionState) unitSpan(point TextPoint) (TextPoint, TextPoint) { + if s.unit == unitChar || point.Surface >= len(s.texts) { + return point, point + } + value := s.texts[point.Surface].text + index := utf8.RuneCountInString(value[:min(point.Offset, len(value))]) + var picked text.Range + if s.unit == unitWord { + picked = text.WordRange(value, index) + } else { + picked = text.LineRange(value, index) + } + from, to := byteOfRune(value, picked.Start), byteOfRune(value, picked.End) + return TextPoint{point.Surface, from}, TextPoint{point.Surface, to} +} + +// byteOfRune is the byte offset of rune index i in value, its length past the end. +func byteOfRune(value string, i int) int { + n := 0 + for offset := range value { + if n == i { + return offset + } + n++ + } + return len(value) +} + +func (s *TextSelectionState) onKey(event gfx.KeyEvent) gfx.EventResult { + if event.Release { + return gfx.EventResult{} + } + switch event.Key { + case gfx.KeyEscape: + if s.Selection.Empty() { + return gfx.EventResult{} + } + s.Clear() + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyLeft, gfx.KeyRight, gfx.KeyUp, gfx.KeyDown: + if event.Modifiers&^gfx.ModifierShift != 0 || event.Modifiers&gfx.ModifierShift == 0 || s.Selection.Empty() { + return gfx.EventResult{} + } + focus, ok := s.step(s.Selection.Focus, event.Key) + if !ok || focus == s.Selection.Focus { + return gfx.EventResult{Handled: true} + } + s.Selection.Focus = focus + s.publish() + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} +} + +// step is the place one character to either side of point, across the end of a +// text into the next, or one line above or below it, at the same distance across. +func (s *TextSelectionState) step(point TextPoint, key gfx.Key) (TextPoint, bool) { + if point.Surface < 0 || point.Surface >= len(s.texts) { + return point, false + } + value := s.texts[point.Surface].text + offset := min(max(point.Offset, 0), len(value)) + switch key { + case gfx.KeyLeft: + if offset > 0 { + return TextPoint{point.Surface, text.PreviousGraphemeBoundary(value, offset)}, true + } + if point.Surface > 0 { + return TextPoint{point.Surface - 1, len(s.texts[point.Surface-1].text)}, true + } + return point, true + case gfx.KeyRight: + if offset < len(value) { + return TextPoint{point.Surface, nextGraphemeOf(value, offset)}, true + } + if point.Surface+1 < len(s.texts) { + return TextPoint{point.Surface + 1, 0}, true + } + return point, true + } + caret, line, ok := s.caretOf(point) + if !ok { + return point, false + } + y := line.Y - 1 + if key == gfx.KeyDown { + y = line.Y + line.Height + 1 + } + if next, ok := s.pointAt(gfx.Point{X: caret, Y: y}); ok { + return next, true + } + return point, true +} + +func nextGraphemeOf(value string, offset int) int { + for next := offset + 1; next < len(value); next++ { + if gfx.GraphemeStart(value, next) == next { + return next + } + } + return len(value) +} + +// caretOf is the x of the place point is in the line the last paint drew it on, +// and that line's box. +func (s *TextSelectionState) caretOf(point TextPoint) (float32, Rect, bool) { + t := &s.texts[point.Surface] + if t.count == 0 || s.canvas == nil { + return 0, Rect{}, false + } + lines := s.lines[t.first : t.first+t.count] + index := len(lines) - 1 + for k, line := range lines { + if point.Offset < line.to || k == len(lines)-1 { + index = k + break + } + } + line := lines[index] + within := min(max(point.Offset-line.from, 0), line.visible) + origin := s.canvas.LabelOrigin(line.shown, line.bounds, t.style, t.align) + return origin + s.canvas.TextCaretStyle(line.shown, t.style, within), line.bounds, true +} + +// pointAt is the place in the area's texts under a point of the window: in the +// text under it, or else the nearest one, so a drag that leaves a text or crosses +// the gap between two goes on into the next. Above a text it is the text's start +// and below it its end. ok is false for an area with no text. +func (s *TextSelectionState) pointAt(at gfx.Point) (TextPoint, bool) { + best, found := -1, false + var bestDistance float32 + for i := range s.texts { + b := s.texts[i].bounds + dy := max(b.Y-at.Y, at.Y-(b.Y+b.Height), 0) + dx := max(b.X-at.X, at.X-(b.X+b.Width), 0) + distance := dy*1_000_000 + dx + if !found || distance < bestDistance { + best, bestDistance, found = i, distance, true + } + } + if !found { + return TextPoint{}, false + } + return s.pointIn(best, at), true +} + +// pointIn is the place in text i nearest a point of the window. +func (s *TextSelectionState) pointIn(i int, at gfx.Point) TextPoint { + t := &s.texts[i] + if t.count == 0 { + return TextPoint{Surface: i} + } + lines := s.lines[t.first : t.first+t.count] + switch { + case at.Y < lines[0].bounds.Y: + return TextPoint{Surface: i} + case at.Y >= lines[len(lines)-1].bounds.Y+lines[len(lines)-1].bounds.Height: + return TextPoint{Surface: i, Offset: len(t.text)} + } + line := lines[len(lines)-1] + for _, candidate := range lines { + if at.Y < candidate.bounds.Y+candidate.bounds.Height { + line = candidate + break + } + } + if s.canvas == nil { + return TextPoint{Surface: i, Offset: line.from} + } + origin := s.canvas.LabelOrigin(line.shown, line.bounds, t.style, t.align) + offset := s.canvas.TextOffsetAtStyle(line.shown, t.style, at.X-origin) + if offset > line.visible { + // The ellipsis stands for the rest of the text. + return TextPoint{Surface: i, Offset: line.to} + } + return TextPoint{Surface: i, Offset: line.from + offset} +} + +// beginTextArea starts collecting the texts of an area as its element is painted. +func (f *Frame) beginTextArea(s *TextSelectionState) { + s.texts, s.lines, s.parent = s.texts[:0], s.lines[:0], -1 + if s.scrollNode >= 0 && int(s.scrollNode) < len(f.Nodes) { + s.scrollRect = f.Nodes[s.scrollNode].Rect + } +} + +// endTextArea keeps the selection inside the texts the paint drew, and follows a +// drag the paint scrolled the texts under. +func (f *Frame) endTextArea(s *TextSelectionState) { + // A press that has not moved yet holds an empty selection, which is the start of + // a drag and not one to drop. + s.Selection.dragging = s.pressed + s.Selection.Clamp(len(s.texts), s.length) + s.Selection.dragging = false + if s.pressed && s.moved { + s.extendTo(s.pointer) + } +} + +// beginSelectableText collects a Text of the area being painted, whose element +// put it in r; addSelectableLine then gives each of its lines as painted, and +// paintSelection draws its selected part and the region over it that takes the +// pointer for the area, before its words are drawn over that. +func (f *Frame) beginSelectableText(n *Node, r Rect, style gfx.TextStyle, alignment gfx.Alignment) { + s := f.area + t := selectableText{text: n.Text, style: style, align: alignment, first: int32(len(s.lines)), bounds: r} + t.tab = n.Parent >= 0 && n.Parent == s.parent && f.Nodes[n.Parent].Dir == row + s.parent = n.Parent + s.texts = append(s.texts, t) + f.lineAt = 0 +} + +func (f *Frame) addSelectableLine(n *Node, shown string, bounds Rect, last bool) { + s := f.area + line := selectableLine{shown: shown, bounds: bounds} + line.from, line.to, line.visible, f.lineAt = sourceOfLine(n.Text, shown, f.lineAt, last) + s.lines = append(s.lines, line) + s.texts[len(s.texts)-1].count++ +} + +func (f *Frame) paintSelection() { + s := f.area + canvas := f.Surface + if canvas == nil { + return + } + surface := len(s.texts) - 1 + t := &s.texts[surface] + canvas.HitWithOptions(s.handlers.parts.At(surface), t.bounds, "", gfx.HitOptions{Role: gfx.RoleGroup, Cursor: gfx.PointerCursorText, Presentational: true}) + start, end := s.Selection.In(surface).rangeIn(t.text) + if start >= end { + return + } + color := fade(f.Palette.Selection, f.Opacity) + for _, line := range s.lines[t.first : t.first+t.count] { + lo, hi := max(start, line.from), min(end, line.to) + if lo >= hi { + continue + } + from, to := min(lo-line.from, line.visible), hi-line.from + if to > line.visible { + to = len(line.shown) // into the ellipsis, which stands for the rest + } + f.selectionSpans = canvas.TextSelectionStyle(f.selectionSpans[:0], line.shown, t.style, from, to) + origin := canvas.LabelOrigin(line.shown, line.bounds, t.style, t.align) + for _, span := range f.selectionSpans { + canvas.Fill(Rect{X: origin + span.X, Y: line.bounds.Y, Width: span.Width, Height: line.bounds.Height}, color) + } + } +} + +// sourceOfLine finds a line a Text was broken into in its source, from pos on: the +// bytes it covers, how many bytes of shown are the source's own, and where the next +// line is looked for. A line is the source as it is, without the spaces a break +// took; the last may end in an ellipsis, standing for the rest of the text. +func sourceOfLine(source, shown string, pos int, last bool) (from, to, visible, next int) { + pos = min(pos, len(source)) + if shown == "" { + if pos < len(source) && source[pos] == '\n' { + pos++ + } + return pos, pos, 0, pos + } + if at := strings.Index(source[pos:], shown); at >= 0 { + from = pos + at + return from, from + len(shown), len(shown), from + len(shown) + } + prefix := strings.TrimSuffix(shown, ellipsisMark) + if at := strings.Index(source[pos:], prefix); at >= 0 { + return pos + at, len(source), len(prefix), len(source) + } + if last { + return pos, len(source), 0, len(source) + } + return pos, pos, 0, pos +} + +const ellipsisMark = "…" diff --git a/components/text_selection_test.go b/base/text_selection_test.go similarity index 79% rename from components/text_selection_test.go rename to base/text_selection_test.go index c2c6978a6..46f3b69db 100644 --- a/components/text_selection_test.go +++ b/base/text_selection_test.go @@ -1,4 +1,4 @@ -package components +package base import ( "testing" @@ -17,7 +17,7 @@ func selectionAt(point gfx.Point) (TextPoint, bool) { return TextPoint{Surface: surface, Offset: min(int(point.X), len(selectionTexts[surface]))}, true } -func selectionText(surface int, part MarkdownSelection) string { +func selectionText(surface int, part TextRange) string { text := []byte(selectionTexts[surface]) start, end := part.Range(text) return string(text[start:end]) @@ -25,25 +25,25 @@ func selectionText(surface int, part MarkdownSelection) string { func selectionLength(surface int) int { return len(selectionTexts[surface]) } -func press(x, y float32) gfx.PointerEvent { +func selectPress(x, y float32) gfx.PointerEvent { return gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: x, Y: y} } -func drag(x, y float32) gfx.PointerEvent { +func selectDrag(x, y float32) gfx.PointerEvent { return gfx.PointerEvent{Kind: gfx.PointerMove, Button: gfx.PointerButtonPrimary, X: x, Y: y, Captured: true} } -func release(x, y float32) gfx.PointerEvent { +func selectRelease(x, y float32) gfx.PointerEvent { return gfx.PointerEvent{Kind: gfx.PointerUp, Button: gfx.PointerButtonPrimary, X: x, Y: y, Captured: true} } func TestTextSelectionDragsFromOneSurfaceIntoAnother(t *testing.T) { var selection TextSelection - if result := selection.Pointer(press(6, 1), selectionAt); !result.Handled || !result.Changed || !selection.Dragging() { + if result := selection.Pointer(selectPress(6, 1), selectionAt); !result.Handled || !result.Changed || !selection.Dragging() { t.Fatalf("press = %+v dragging=%v", result, selection.Dragging()) } - selection.Pointer(drag(3, 31), selectionAt) - result := selection.Pointer(release(5, 31), selectionAt) + selection.Pointer(selectDrag(3, 31), selectionAt) + result := selection.Pointer(selectRelease(5, 31), selectionAt) if !result.Handled || selection.Dragging() { t.Fatalf("release = %+v dragging=%v", result, selection.Dragging()) } @@ -67,10 +67,10 @@ func TestTextSelectionDraggedBackwardCopiesTheSameText(t *testing.T) { func TestTextSelectionInKeepsTheDragOrderWithinOneSurface(t *testing.T) { var selection TextSelection selection.Select(TextPoint{Surface: 1, Offset: 4}, TextPoint{Surface: 1, Offset: 1}) - if got := selection.In(1); got != (MarkdownSelection{Anchor: 4, Focus: 1}) { + if got := selection.In(1); got != (TextRange{Anchor: 4, Focus: 1}) { t.Fatalf("In = %+v: a drag upward was turned round", got) } - if got := selection.In(0); got != (MarkdownSelection{}) { + if got := selection.In(0); got != (TextRange{}) { t.Fatalf("a surface outside the selection covers %+v", got) } } @@ -91,13 +91,13 @@ func TestTextSelectionCoversWholeSurfacesBetweenItsEnds(t *testing.T) { func TestTextSelectionPressOnNothingIsLeftToTheCaller(t *testing.T) { var selection TextSelection selection.Select(TextPoint{Surface: 0, Offset: 1}, TextPoint{Surface: 0, Offset: 4}) - if result := selection.Pointer(press(0, 500), selectionAt); result.Handled || result.Changed { + if result := selection.Pointer(selectPress(0, 500), selectionAt); result.Handled || result.Changed { t.Fatalf("press off every surface = %+v", result) } if selection.Empty() { t.Fatal("a press the selection did not take cleared it") } - secondary := press(1, 1) + secondary := selectPress(1, 1) secondary.Button = gfx.PointerButtonSecondary if result := selection.Pointer(secondary, selectionAt); result.Handled { t.Fatalf("a secondary press = %+v", result) @@ -106,8 +106,8 @@ func TestTextSelectionPressOnNothingIsLeftToTheCaller(t *testing.T) { func TestTextSelectionClickWithoutDragSelectsNothing(t *testing.T) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) - selection.Pointer(release(2, 1), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) + selection.Pointer(selectRelease(2, 1), selectionAt) if !selection.Empty() || selection.Dragging() || selection != (TextSelection{}) { t.Fatalf("a click left %+v", selection) } @@ -115,22 +115,22 @@ func TestTextSelectionClickWithoutDragSelectsNothing(t *testing.T) { func TestTextSelectionMovesWithoutAHeldButtonDoNothing(t *testing.T) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) - hover := drag(8, 1) + selection.Pointer(selectPress(2, 1), selectionAt) + hover := selectDrag(8, 1) hover.Captured = false if result := selection.Pointer(hover, selectionAt); result.Handled || selection.Focus.Offset != 2 { t.Fatalf("a hovering move = %+v focus=%+v", result, selection.Focus) } var idle TextSelection - if result := idle.Pointer(drag(8, 1), selectionAt); result.Handled { + if result := idle.Pointer(selectDrag(8, 1), selectionAt); result.Handled { t.Fatalf("a move with no drag = %+v", result) } } func TestTextSelectionKeepsWhatWasSelectedWhenThePointerLeavesTheWindow(t *testing.T) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) - selection.Pointer(drag(7, 1), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) + selection.Pointer(selectDrag(7, 1), selectionAt) exit := gfx.PointerEvent{Kind: gfx.PointerExit} if result := selection.Pointer(exit, selectionAt); !result.Handled || selection.Dragging() || selection.Empty() { t.Fatalf("exit = %+v selection=%+v", result, selection) @@ -165,9 +165,9 @@ func TestTextSelectionClampFollowsTextThatChanged(t *testing.T) { func TestTextSelectionPointerPathDoesNotAllocate(t *testing.T) { var selection TextSelection allocs := testing.AllocsPerRun(100, func() { - selection.Pointer(press(2, 1), selectionAt) - selection.Pointer(drag(7, 31), selectionAt) - selection.Pointer(release(7, 31), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) + selection.Pointer(selectDrag(7, 31), selectionAt) + selection.Pointer(selectRelease(7, 31), selectionAt) _ = selection.In(1) }) if allocs != 0 { @@ -177,11 +177,11 @@ func TestTextSelectionPointerPathDoesNotAllocate(t *testing.T) { func BenchmarkTextSelectionDrag(b *testing.B) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) b.ReportAllocs() for b.Loop() { - selection.Pointer(drag(7, 31), selectionAt) - selection.Pointer(drag(3, 11), selectionAt) + selection.Pointer(selectDrag(7, 31), selectionAt) + selection.Pointer(selectDrag(3, 11), selectionAt) } } @@ -198,13 +198,13 @@ func BenchmarkTextSelectionIn(b *testing.B) { func TestTextSelectionEndDragKeepsTheSelection(t *testing.T) { var selection TextSelection - selection.Pointer(press(2, 1), selectionAt) - selection.Pointer(drag(7, 1), selectionAt) + selection.Pointer(selectPress(2, 1), selectionAt) + selection.Pointer(selectDrag(7, 1), selectionAt) selection.EndDrag() if selection.Dragging() || selection.Empty() { t.Fatalf("EndDrag left %+v", selection) } - if result := selection.Pointer(drag(1, 1), selectionAt); result.Handled || selection.Focus.Offset != 7 { + if result := selection.Pointer(selectDrag(1, 1), selectionAt); result.Handled || selection.Focus.Offset != 7 { t.Fatalf("a move after EndDrag = %+v focus=%+v", result, selection.Focus) } } diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go index 5e1b47f85..3c6092061 100644 --- a/cmd/viva/components_gen.go +++ b/cmd/viva/components_gen.go @@ -119,7 +119,7 @@ var componentRequires = map[string][]string{ "button-group": {"button"}, "calendar": {"direction", "tree"}, "carousel": {"direction", "tree"}, - "chart-area": {"chart", "label"}, + "chart-area": {"chart"}, "chart-bar": {"chart", "chart-area"}, "checkbox": {"button"}, "code-diff": {"code-diff-model", "code-editor", "code-editor-layout", "scroll-area", "textarea"}, @@ -131,16 +131,16 @@ var componentRequires = map[string][]string{ "code-merge": {"code-diff", "code-diff-model", "code-editor", "code-editor-layout", "scroll-area"}, "color-picker": {"button", "input", "popover"}, "column-resize": {"button"}, - "combobox": {"checkbox", "dialog", "dropdown-menu", "input", "label", "popover", "tree"}, + "combobox": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"}, "command": {"checkbox", "dialog", "dropdown-menu"}, "context-menu": {"dialog", "dropdown-menu", "popover"}, "dialog": {"button"}, "drawer": {"button", "dialog"}, - "dropdown-menu": {"checkbox", "dialog", "hover-card", "kbd", "label", "popover", "tree"}, + "dropdown-menu": {"checkbox", "dialog", "hover-card", "kbd", "popover", "tree"}, "find-bar": {"button", "dialog", "input", "toggle", "tree"}, "go-to-line": {"button", "find-bar", "input"}, "graph": {"graph-sim"}, - "hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "label", "popover", "tree"}, + "hierarchy-menu": {"checkbox", "dialog", "dropdown-menu", "popover", "tree"}, "hover-card": {"dialog", "popover"}, "input": {"textarea"}, "input-group": {"button", "input", "spinner", "textarea"}, @@ -151,7 +151,7 @@ var componentRequires = map[string][]string{ "marker": {"spinner"}, "menubar": {"dialog", "direction", "dropdown-menu", "hover-card", "popover"}, "metric-card": {"card"}, - "multi-select": {"checkbox", "combobox", "dialog", "dropdown-menu", "input", "label", "popover", "tree"}, + "multi-select": {"checkbox", "combobox", "dialog", "dropdown-menu", "input", "popover", "tree"}, "native-select": {"input", "tree"}, "navigation-menu": {"dialog", "direction", "hover-card", "tree"}, "pagination": {"breadcrumb", "tree"}, @@ -160,10 +160,10 @@ var componentRequires = map[string][]string{ "radio-group": {"button", "direction"}, "resizable": {"button"}, "segmented-control": {"button", "direction"}, - "select": {"checkbox", "dialog", "dropdown-menu", "input", "label", "popover", "tree"}, + "select": {"checkbox", "dialog", "dropdown-menu", "input", "popover", "tree"}, "sheet": {"button", "dialog"}, "sidebar": {"button"}, - "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "label", "popover", "tree"}, + "single-select": {"checkbox", "dialog", "dropdown-menu", "hierarchy-menu", "input", "popover", "tree"}, "slider": {"button", "direction"}, "sonner": {"dialog", "toast"}, "split-button": {"button", "button-group", "tree"}, diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index 1fa5b9b95..fb8147105 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -235,7 +235,7 @@ func (m *model) page(c ui.C) { `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, - `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. + `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns the lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. @@ -321,7 +321,7 @@ func (m *model) page(c ui.C) { model: `m.drop.Over()` paints the highlight while files are over it, and `m.drop.Dropped()` returns the files (and their paths, empty in a browser) once. `ui.OpenFiles(c, options, done)` is the system's picker, answering with files that read the same way; `ui.FilePath(file)` is a file's path where there is one. For a whole upload - area with a file list, use `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. + area with a file list, use `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - For a divider between two panes, use `ui.Splitter` (see "Keys, drag and the mouse"), not a `DragState`. ## Mistakes that compile (and how each is reported) diff --git a/cmd/viva/templates/chart_area.go.txt b/cmd/viva/templates/chart_area.go.txt index b1d0ab86b..9f201794c 100644 --- a/cmd/viva/templates/chart_area.go.txt +++ b/cmd/viva/templates/chart_area.go.txt @@ -502,7 +502,8 @@ func chartBeginFrame(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, spec // Edge ticks remain anchored to their data, but their labels must // fit inside the chart container rather than spill into a neighbor. x := min(max(plot.X+frac*plot.Width-width/2, area.X), area.X+area.Width-width) - labelEllipsis(canvas, text, gfx.Rect{X: x, Y: plot.Y + plot.Height + chartAxisGap*scale, Width: width, Height: rowHeight}, labelStyle, gfx.ID{}) + text = canvas.FitLine(text, fontSize, gfx.WeightRegular, width) + canvas.Label(text, gfx.Rect{X: x, Y: plot.Y + plot.Height + chartAxisGap*scale, Width: width, Height: rowHeight}, labelStyle) } } return chartFrame{layout: layout, plot: ChartPlot{ChartLayout: layout, Plot: plot, geo: geo}, scale: scale} diff --git a/cmd/viva/templates/combobox.go.txt b/cmd/viva/templates/combobox.go.txt index c2bc5f072..3177b18a3 100644 --- a/cmd/viva/templates/combobox.go.txt +++ b/cmd/viva/templates/combobox.go.txt @@ -218,7 +218,7 @@ func (combobox *Combobox) AddItem(item ComboboxItem) gfx.Rect { labelWidth = maxLabelWidth } - labelEllipsis(combobox.canvas, item.Label, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ + combobox.canvas.LabelEllipsis(item.Label, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeM, Weight: gfx.WeightRegular, Color: foreground, }, item.ID) @@ -229,7 +229,7 @@ func (combobox *Combobox) AddItem(item ComboboxItem) gfx.Rect { if item.Disabled { detailColor.Alpha *= .5 } - labelEllipsis(combobox.canvas, item.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ + combobox.canvas.LabelEllipsis(item.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeS, Weight: gfx.WeightRegular, Color: detailColor, }, item.ID) } @@ -454,7 +454,7 @@ func (combobox Combobox) paintInput() { if labelWidth > maxLabelWidth { labelWidth = maxLabelWidth } - labelEllipsis(canvas, options.Value, gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ + canvas.LabelEllipsis(options.Value, gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeM, Weight: gfx.WeightRegular, Color: foreground, }, options.InputID) detailX := bounds.X + inset + labelWidth + 8 @@ -464,12 +464,12 @@ func (combobox Combobox) paintInput() { if options.Disabled { detailColor.Alpha *= 0.50 } - labelEllipsis(canvas, options.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ + canvas.LabelEllipsis(options.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeS, Weight: gfx.WeightRegular, Color: detailColor, }, options.InputID) } } else if options.Query == "" || options.InputID.IsZero() || canvas.Focused() != options.InputID || options.Disabled { - labelEllipsis(canvas, value, textRect, gfx.TextStyle{Size: combobox.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground}, options.InputID) + canvas.LabelEllipsis(value, textRect, gfx.TextStyle{Size: combobox.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground}, options.InputID) } if !options.InputID.IsZero() { canvas.HitWithOptions(options.InputID, bounds, options.Label, gfx.HitOptions{ diff --git a/cmd/viva/templates/context_menu.go.txt b/cmd/viva/templates/context_menu.go.txt index e2541a51c..12dca3a80 100644 --- a/cmd/viva/templates/context_menu.go.txt +++ b/cmd/viva/templates/context_menu.go.txt @@ -84,6 +84,9 @@ type ContextMenuOptions struct { type ContextMenuItem struct { ID gfx.ID Label string + // Mnemonic is an optional one-character key shown after the label and + // matched before ordinary menu typeahead. + Mnemonic string // Description is an optional muted second line. It increases the item height // and is ellipsized to the available width; Hint may carry the full text. Description string @@ -113,7 +116,7 @@ type ContextMenuItem struct { func (item ContextMenuItem) common() menuItem { return menuItem{ Description: item.Description, - ID: item.ID, Label: item.Label, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, + ID: item.ID, Label: item.Label, Mnemonic: item.Mnemonic, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, Value: item.Value, Hint: item.Hint, Kind: menuKind(item.Kind), Destructive: item.Variant == ContextMenuItemDestructive, Checked: item.Checked, Selected: item.Selected, Disabled: item.Disabled, Inset: item.Inset, Expanded: item.Expanded, Icon: item.Icon, } diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index 1ab6b34c1..4abfaa507 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -19,6 +19,17 @@ const ( DropdownMenuItemDestructive ) +// menuMnemonicGap is the space on each side of the mnemonic shown after a label. +const menuMnemonicGap = 4 + +func menuMnemonicLabel(value string) string { + runeValue, size := utf8.DecodeRuneInString(value) + if size == 0 || runeValue == utf8.RuneError { + return "" + } + return "(" + string(unicode.ToUpper(runeValue)) + ")" +} + // DropdownMenuItemKind selects the item's indicator and semantic state. type DropdownMenuItemKind uint8 @@ -175,8 +186,12 @@ type DropdownMenuOptions struct { // DropdownMenuItem describes one stable menu action. type DropdownMenuItem struct { - ID gfx.ID - Label string + ID gfx.ID + Label string + // Mnemonic is an optional one-character key shown after the label and + // matched before ordinary menu typeahead. It only moves focus, and it does + // not have to appear in the label. + Mnemonic string Shortcut string // Keys, when set, replace Shortcut with one keycap per entry (for example // "⌘", "⌥", "H"), painted with Kbd at the row's trailing edge. @@ -206,7 +221,7 @@ type DropdownMenuItem struct { func (item DropdownMenuItem) common() menuItem { return menuItem{ - ID: item.ID, Label: item.Label, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, + ID: item.ID, Label: item.Label, Mnemonic: item.Mnemonic, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, Value: item.Value, Hint: item.Hint, Description: item.Description, Kind: menuKind(item.Kind), Destructive: item.Variant == DropdownMenuItemDestructive, Checked: item.Checked, Selected: item.Selected, Disabled: item.Disabled, Inset: item.Inset, Expanded: item.Expanded, Icon: item.Icon, } @@ -393,6 +408,7 @@ const ( type menuItem struct { ID gfx.ID Label string + Mnemonic string Description string Shortcut string Keys []string @@ -735,6 +751,9 @@ func menuItemWidth(canvas *gfx.Canvas, theme gfx.Theme, item menuItem, indicator left += menuIconSize + menuIconGap } textWidth := canvas.TextWidth(item.Label, theme.Metrics.FontSizeM) + if item.Mnemonic != "" { + textWidth += canvas.TextWidth(menuMnemonicLabel(item.Mnemonic), theme.Metrics.FontSizeS) + 2*menuMnemonicGap + } if item.Description != "" { textWidth = max(textWidth, canvas.TextWidth(item.Description, theme.Metrics.FontSizeS)) } @@ -829,7 +848,7 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { if paint := menu.options.paintItem; paint != nil { paint(MenuItemPaint{ Canvas: canvas, Theme: theme, Bounds: bounds, - Label: item.Label, Description: item.Description, Shortcut: item.Shortcut, + Label: item.Label, Mnemonic: item.Mnemonic, Description: item.Description, Shortcut: item.Shortcut, Checked: item.Kind == menuCheckbox && item.Checked, Selected: item.Kind == menuRadio && item.Selected, Expanded: item.Kind == menuSubmenu && item.Expanded, @@ -901,14 +920,29 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { } labelWidth := max(0, bounds.Width-left-right) label := item.Label - if canvas.TextWidthWeight(label, theme.Metrics.FontSizeM, gfx.WeightRegular) > labelWidth { - label = canvas.FitLine(label, theme.Metrics.FontSizeM, gfx.WeightRegular, labelWidth) + mnemonic := menuMnemonicLabel(item.Mnemonic) + mnemonicWidth := float32(0) + if mnemonic != "" { + mnemonicWidth = canvas.TextWidth(mnemonic, theme.Metrics.FontSizeS) + 2*menuMnemonicGap + if mnemonicWidth > labelWidth { + mnemonic, mnemonicWidth = "", 0 + } + } + labelAreaWidth := max(0, labelWidth-mnemonicWidth) + if canvas.TextWidthWeight(label, theme.Metrics.FontSizeM, gfx.WeightRegular) > labelAreaWidth { + label = canvas.FitLine(label, theme.Metrics.FontSizeM, gfx.WeightRegular, labelAreaWidth) } - canvas.Label(label, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelWidth, Height: labelHeight}, gfx.TextStyle{ + canvas.Label(label, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelAreaWidth, Height: labelHeight}, gfx.TextStyle{ Size: theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, }) if label != "" && label != item.Label { - canvas.HoverHint(0, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelWidth, Height: labelHeight}, item.Label, item.ID) + canvas.HoverHint(0, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelAreaWidth, Height: labelHeight}, item.Label, item.ID) + } + if mnemonic != "" { + labelUsed := min(labelAreaWidth, canvas.TextWidthWeight(label, theme.Metrics.FontSizeM, gfx.WeightRegular)) + canvas.Label(mnemonic, gfx.Rect{X: bounds.X + left + labelUsed + menuMnemonicGap, Y: labelY, Width: mnemonicWidth - menuMnemonicGap, Height: labelHeight}, gfx.TextStyle{ + Size: theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: dropdownMenuOpacity(theme.MutedForeground, item.Disabled), + }) } if item.Description != "" { color := theme.MutedForeground @@ -917,7 +951,7 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { } color = dropdownMenuOpacity(color, item.Disabled) width := max(0, bounds.Width-left-right-menu.hitInset) - labelEllipsis(canvas, item.Description, gfx.Rect{X: bounds.X + left, Y: descriptionY, Width: width, Height: descriptionHeight}, gfx.TextStyle{ + canvas.LabelEllipsis(item.Description, gfx.Rect{X: bounds.X + left, Y: descriptionY, Width: width, Height: descriptionHeight}, gfx.TextStyle{ Size: theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: color, }, item.ID) } diff --git a/cmd/viva/templates/hierarchy_menu.go.txt b/cmd/viva/templates/hierarchy_menu.go.txt index f64b26668..9461d87ff 100644 --- a/cmd/viva/templates/hierarchy_menu.go.txt +++ b/cmd/viva/templates/hierarchy_menu.go.txt @@ -226,7 +226,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } paintChevron(canvas, &hierarchyLeftIcon, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: 16, Height: bounds.Height}, look.Foreground) text := gfx.Rect{X: bounds.X + 32, Y: bounds.Y, Width: max(bounds.Width-40, 0), Height: bounds.Height} - labelEllipsis(canvas, label, text, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: look.Foreground}, o.OptionIDs.At(hierarchyBackIndex)) + canvas.LabelEllipsis(label, text, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: look.Foreground}, o.OptionIDs.At(hierarchyBackIndex)) canvas.HitWithOptions(o.OptionIDs.At(hierarchyBackIndex), bounds, label, gfx.HitOptions{Role: gfx.RoleButton, Description: m.Nodes[parent].Path, SkipFocus: true}) menu.top += bounds.Height menu.viewHeight = max(menu.viewHeight-bounds.Height, 0) @@ -261,7 +261,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m reserve += 16 } labelWidth := max(rowBounds.Width-reserve, 0) - labelEllipsis(canvas, info.Name, gfx.Rect{X: rowBounds.X + 8, Y: rowBounds.Y, Width: labelWidth, Height: rowBounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) + canvas.LabelEllipsis(info.Name, gfx.Rect{X: rowBounds.X + 8, Y: rowBounds.Y, Width: labelWidth, Height: rowBounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) switch { case info.Count > 0 && rowBounds.Width >= reserve: chevron := &chevronRightIcon @@ -323,7 +323,7 @@ func paintAction(m *HierarchyMenuState, menu *menuSurface, action HierarchyMenuA } color := look.Foreground label := gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-16, 0), Height: row.Height} - labelEllipsis(canvas, action.Label, label, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, action.ID) + canvas.LabelEllipsis(action.Label, label, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, action.ID) row.Width = max(row.Width-menu.hitInset, 0) canvas.HitWithOptions(action.ID, row, action.Label, gfx.HitOptions{Role: gfx.RoleMenuItem, Disabled: action.Disabled, SkipFocus: true}) }) diff --git a/cmd/viva/templates/label.go.txt b/cmd/viva/templates/label.go.txt index d08c7a090..7d965f56a 100644 --- a/cmd/viva/templates/label.go.txt +++ b/cmd/viva/templates/label.go.txt @@ -75,25 +75,3 @@ func (label LabelPainter) Paint(text string) { }) } } - -// labelEllipsis keeps the complete value alongside the fitted label. Its -// control may declare its hit after painting; that hit still owns the pointer. -// The hint is dropped where the page leaves its ellipsis tooltips off. -func labelEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { - shown := canvas.FitLine(value, style.Size, style.Weight, bounds.Width) - canvas.Label(shown, bounds, style) - if shown != "" && shown != value { - canvas.HoverHint(0, bounds, value, target) - } -} - -// labelOrEllipsis draws a value a control has always clipped at the edge of its -// bounds, as Label does. Where the page shows ellipsis tooltips it ends the value -// with an ellipsis instead, as labelEllipsis does, since the hint shows the rest. -func labelOrEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { - if canvas.HoverHintOwner().IsZero() { - canvas.Label(value, bounds, style) - return - } - labelEllipsis(canvas, value, bounds, style, target) -} diff --git a/cmd/viva/templates/menubar.go.txt b/cmd/viva/templates/menubar.go.txt index e63646005..5a2041b15 100644 --- a/cmd/viva/templates/menubar.go.txt +++ b/cmd/viva/templates/menubar.go.txt @@ -165,8 +165,11 @@ type MenubarTrigger struct { // MenubarItem describes one stable action inside an open menubar popup. type MenubarItem struct { - ID gfx.ID - Label string + ID gfx.ID + Label string + // Mnemonic is an optional one-character key shown after the label and + // matched before ordinary menu typeahead. + Mnemonic string Shortcut string // Keys, when set, replace Shortcut with one keycap per entry (for example // "⌘", "⌥", "H"), painted with Kbd at the row's trailing edge. @@ -192,7 +195,7 @@ type MenubarItem struct { func (item MenubarItem) common() menuItem { return menuItem{ - ID: item.ID, Label: item.Label, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, + ID: item.ID, Label: item.Label, Mnemonic: item.Mnemonic, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, Value: item.Value, Hint: item.Hint, Kind: menuKind(item.Kind), Destructive: item.Variant == MenubarItemDestructive, Checked: item.Checked, Selected: item.Selected, Disabled: item.Disabled, Inset: item.Inset, Expanded: item.Expanded, Icon: item.Icon, } diff --git a/cmd/viva/templates/multi_select.go.txt b/cmd/viva/templates/multi_select.go.txt index 7aa2fad40..c4b6648aa 100644 --- a/cmd/viva/templates/multi_select.go.txt +++ b/cmd/viva/templates/multi_select.go.txt @@ -184,7 +184,7 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M } label = text } - labelEllipsis(canvas, label, gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-38, 0), Height: row.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) + canvas.LabelEllipsis(label, gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-38, 0), Height: row.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) if choice.Selected { paintCheck(canvas, gfx.Rect{X: row.X + row.Width - 25, Y: row.Y, Width: 16, Height: row.Height}, 14, color) } diff --git a/cmd/viva/templates/select.go.txt b/cmd/viva/templates/select.go.txt index da9a08b48..366cd7a14 100644 --- a/cmd/viva/templates/select.go.txt +++ b/cmd/viva/templates/select.go.txt @@ -372,7 +372,7 @@ func (selectControl Select) paintTrigger() { if options.Weight > 0 { weight = options.Weight } - labelOrEllipsis(canvas, value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + canvas.LabelOrEllipsis(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: textSize, Weight: weight, Color: foreground, }, options.TriggerID) } @@ -403,7 +403,7 @@ func (selectControl *Select) paintItem(bounds gfx.Rect, item SelectItem) { textX += SelectIconSpan textWidth -= SelectIconSpan } - labelOrEllipsis(selectControl.canvas, item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + selectControl.canvas.LabelOrEllipsis(item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, }, item.ID) if item.Selected { diff --git a/cmd/viva/templates/single_select.go.txt b/cmd/viva/templates/single_select.go.txt index 6d2b5d2ac..80df14c81 100644 --- a/cmd/viva/templates/single_select.go.txt +++ b/cmd/viva/templates/single_select.go.txt @@ -264,18 +264,18 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * func paintLabelAndDetail(canvas *gfx.Canvas, theme gfx.Theme, x, y, width, height float32, label, detail string, color gfx.Color, disabled bool, target gfx.ID) { sizeM, sizeS := theme.Metrics.FontSizeM, theme.Metrics.FontSizeS if detail == "" { - labelEllipsis(canvas, label, gfx.Rect{X: x, Y: y, Width: width, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) + canvas.LabelEllipsis(label, gfx.Rect{X: x, Y: y, Width: width, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) return } labelWidth := min(canvas.TextWidthWeight(label, sizeM, gfx.WeightRegular), max(width-40, 0)) - labelEllipsis(canvas, label, gfx.Rect{X: x, Y: y, Width: labelWidth, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) + canvas.LabelEllipsis(label, gfx.Rect{X: x, Y: y, Width: labelWidth, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) detailX := x + labelWidth + singleSelectDetailGap if detailWidth := max(x+width-detailX, 0); detailWidth > 0 { muted := theme.MutedForeground if disabled { muted.Alpha *= .5 } - labelEllipsis(canvas, detail, gfx.Rect{X: detailX, Y: y, Width: detailWidth, Height: height}, gfx.TextStyle{Size: sizeS, Color: muted}, target) + canvas.LabelEllipsis(detail, gfx.Rect{X: detailX, Y: y, Width: detailWidth, Height: height}, gfx.TextStyle{Size: sizeS, Color: muted}, target) } } diff --git a/components/chart_area.go b/components/chart_area.go index d0d8d2aba..fddd7a983 100644 --- a/components/chart_area.go +++ b/components/chart_area.go @@ -502,7 +502,8 @@ func chartBeginFrame(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, spec // Edge ticks remain anchored to their data, but their labels must // fit inside the chart container rather than spill into a neighbor. x := min(max(plot.X+frac*plot.Width-width/2, area.X), area.X+area.Width-width) - labelEllipsis(canvas, text, gfx.Rect{X: x, Y: plot.Y + plot.Height + chartAxisGap*scale, Width: width, Height: rowHeight}, labelStyle, gfx.ID{}) + text = canvas.FitLine(text, fontSize, gfx.WeightRegular, width) + canvas.Label(text, gfx.Rect{X: x, Y: plot.Y + plot.Height + chartAxisGap*scale, Width: width, Height: rowHeight}, labelStyle) } } return chartFrame{layout: layout, plot: ChartPlot{ChartLayout: layout, Plot: plot, geo: geo}, scale: scale} diff --git a/components/combobox.go b/components/combobox.go index a56d27c42..b6a17e26b 100644 --- a/components/combobox.go +++ b/components/combobox.go @@ -218,7 +218,7 @@ func (combobox *Combobox) AddItem(item ComboboxItem) gfx.Rect { labelWidth = maxLabelWidth } - labelEllipsis(combobox.canvas, item.Label, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ + combobox.canvas.LabelEllipsis(item.Label, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeM, Weight: gfx.WeightRegular, Color: foreground, }, item.ID) @@ -229,7 +229,7 @@ func (combobox *Combobox) AddItem(item ComboboxItem) gfx.Rect { if item.Disabled { detailColor.Alpha *= .5 } - labelEllipsis(combobox.canvas, item.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ + combobox.canvas.LabelEllipsis(item.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeS, Weight: gfx.WeightRegular, Color: detailColor, }, item.ID) } @@ -454,7 +454,7 @@ func (combobox Combobox) paintInput() { if labelWidth > maxLabelWidth { labelWidth = maxLabelWidth } - labelEllipsis(canvas, options.Value, gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ + canvas.LabelEllipsis(options.Value, gfx.Rect{X: bounds.X + inset, Y: bounds.Y, Width: labelWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeM, Weight: gfx.WeightRegular, Color: foreground, }, options.InputID) detailX := bounds.X + inset + labelWidth + 8 @@ -464,12 +464,12 @@ func (combobox Combobox) paintInput() { if options.Disabled { detailColor.Alpha *= 0.50 } - labelEllipsis(canvas, options.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ + canvas.LabelEllipsis(options.Detail, gfx.Rect{X: detailX, Y: bounds.Y, Width: detailWidth, Height: bounds.Height}, gfx.TextStyle{ Size: sizeS, Weight: gfx.WeightRegular, Color: detailColor, }, options.InputID) } } else if options.Query == "" || options.InputID.IsZero() || canvas.Focused() != options.InputID || options.Disabled { - labelEllipsis(canvas, value, textRect, gfx.TextStyle{Size: combobox.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground}, options.InputID) + canvas.LabelEllipsis(value, textRect, gfx.TextStyle{Size: combobox.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground}, options.InputID) } if !options.InputID.IsZero() { canvas.HitWithOptions(options.InputID, bounds, options.Label, gfx.HitOptions{ diff --git a/components/context_menu.go b/components/context_menu.go index 703a25661..2cb86504a 100644 --- a/components/context_menu.go +++ b/components/context_menu.go @@ -84,6 +84,9 @@ type ContextMenuOptions struct { type ContextMenuItem struct { ID gfx.ID Label string + // Mnemonic is an optional one-character key shown after the label and + // matched before ordinary menu typeahead. + Mnemonic string // Description is an optional muted second line. It increases the item height // and is ellipsized to the available width; Hint may carry the full text. Description string @@ -113,7 +116,7 @@ type ContextMenuItem struct { func (item ContextMenuItem) common() menuItem { return menuItem{ Description: item.Description, - ID: item.ID, Label: item.Label, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, + ID: item.ID, Label: item.Label, Mnemonic: item.Mnemonic, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, Value: item.Value, Hint: item.Hint, Kind: menuKind(item.Kind), Destructive: item.Variant == ContextMenuItemDestructive, Checked: item.Checked, Selected: item.Selected, Disabled: item.Disabled, Inset: item.Inset, Expanded: item.Expanded, Icon: item.Icon, } diff --git a/components/context_menu_test.go b/components/context_menu_test.go index e299fe567..05f677ed5 100644 --- a/components/context_menu_test.go +++ b/components/context_menu_test.go @@ -112,6 +112,33 @@ func TestContextMenuKeysPaintKeycapsAtTheTrailingEdge(t *testing.T) { } } +func TestContextMenuMnemonicIsRenderedSeparatelyFromTheLabel(t *testing.T) { + var canvas gfx.Canvas + theme := gfx.DarkTheme() + item := ContextMenuItem{ID: gfx.Item(3), Label: "Copy", Mnemonic: "c", Shortcut: "Ctrl+Shift+C"} + withMnemonic := ContextMenuItemWidth(&canvas, theme, item) + withoutMnemonic := ContextMenuItemWidth(&canvas, theme, ContextMenuItem{ID: item.ID, Label: item.Label, Shortcut: item.Shortcut}) + if withMnemonic <= withoutMnemonic { + t.Fatalf("mnemonic width = %v, without = %v", withMnemonic, withoutMnemonic) + } + menu := BeginContextMenu(&canvas, theme, gfx.Rect{Width: withMnemonic, Height: 80}, ContextMenuOptions{Layer: 5}) + menu.AddItem(item) + if contextMenuTestText(canvas.Texts(), "Copy").Value != "Copy" || contextMenuTestText(canvas.Texts(), "(C)").Value != "(C)" { + t.Fatalf("texts = %+v, want separate label and mnemonic", canvas.Texts()) + } +} + +func TestNarrowContextMenuKeepsMnemonicOutOfKeycaps(t *testing.T) { + var canvas gfx.Canvas + menu := BeginContextMenu(&canvas, gfx.DarkTheme(), gfx.Rect{Width: 80, Height: 80}, ContextMenuOptions{Layer: 5}) + menu.AddItem(ContextMenuItem{ID: gfx.Item(3), Label: "Copy", Mnemonic: "c", Keys: []string{"Ctrl", "Shift", "Alt", "C"}}) + firstKey := contextMenuTestText(canvas.Texts(), "Ctrl") + hint := contextMenuTestText(canvas.Texts(), "(C)") + if firstKey.Value == "" || hint.Value != "" { + t.Fatalf("first keycap = %q at %v, unwanted mnemonic = %q at %v", firstKey.Value, firstKey.Bounds, hint.Value, hint.Bounds) + } +} + func TestContextMenuSlotHoldsCallerContentInsideTheMenu(t *testing.T) { theme := gfx.DarkTheme() var canvas gfx.Canvas diff --git a/components/doc.go b/components/doc.go index 407fa8107..3abe264ff 100644 --- a/components/doc.go +++ b/components/doc.go @@ -151,13 +151,11 @@ // editor's caret turns over on the terminal's rhythm and comes to rest lit // when the window is left alone. The application keeps one next to its text // and passes the result as ShowCaret. -// - Text selection: `TextSelection` follows a pointer drag that begins in one -// painted text and ends in another (a MarkdownView, a table, a plain block): -// `TextSelection.Pointer` begins, extends and ends it, `TextSelection.In` -// gives the part of each text to paint highlighted, and `TextSelection.Text` -// joins what a copy puts on the clipboard. The application numbers its texts -// in reading order and says where each lies; the caller-owned value -// schedules nothing and allocates nothing while the pointer moves. +// - Text selection: a drag that begins in one painted text and ends in another +// (a MarkdownView, a table, a plain block) is followed by ui.TextSelection, +// whose In gives the TextRange of each text to paint highlighted and Text joins +// what a copy puts on the clipboard. Texts the page declares with ui.Text take +// part in a ui.TextSelectionArea instead, without painting. // - Find bar: `PaintFindBar` paints the find and replace bar of an editor over // two InputSnapshot fields, with option toggles, a count and step buttons; // `FindBarCommandForKey` maps Command or Control+F, F3 and Enter to its diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index d20a35ae4..fc1798308 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -19,6 +19,17 @@ const ( DropdownMenuItemDestructive ) +// menuMnemonicGap is the space on each side of the mnemonic shown after a label. +const menuMnemonicGap = 4 + +func menuMnemonicLabel(value string) string { + runeValue, size := utf8.DecodeRuneInString(value) + if size == 0 || runeValue == utf8.RuneError { + return "" + } + return "(" + string(unicode.ToUpper(runeValue)) + ")" +} + // DropdownMenuItemKind selects the item's indicator and semantic state. type DropdownMenuItemKind uint8 @@ -175,8 +186,12 @@ type DropdownMenuOptions struct { // DropdownMenuItem describes one stable menu action. type DropdownMenuItem struct { - ID gfx.ID - Label string + ID gfx.ID + Label string + // Mnemonic is an optional one-character key shown after the label and + // matched before ordinary menu typeahead. It only moves focus, and it does + // not have to appear in the label. + Mnemonic string Shortcut string // Keys, when set, replace Shortcut with one keycap per entry (for example // "⌘", "⌥", "H"), painted with Kbd at the row's trailing edge. @@ -206,7 +221,7 @@ type DropdownMenuItem struct { func (item DropdownMenuItem) common() menuItem { return menuItem{ - ID: item.ID, Label: item.Label, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, + ID: item.ID, Label: item.Label, Mnemonic: item.Mnemonic, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, Value: item.Value, Hint: item.Hint, Description: item.Description, Kind: menuKind(item.Kind), Destructive: item.Variant == DropdownMenuItemDestructive, Checked: item.Checked, Selected: item.Selected, Disabled: item.Disabled, Inset: item.Inset, Expanded: item.Expanded, Icon: item.Icon, } @@ -393,6 +408,7 @@ const ( type menuItem struct { ID gfx.ID Label string + Mnemonic string Description string Shortcut string Keys []string @@ -735,6 +751,9 @@ func menuItemWidth(canvas *gfx.Canvas, theme gfx.Theme, item menuItem, indicator left += menuIconSize + menuIconGap } textWidth := canvas.TextWidth(item.Label, theme.Metrics.FontSizeM) + if item.Mnemonic != "" { + textWidth += canvas.TextWidth(menuMnemonicLabel(item.Mnemonic), theme.Metrics.FontSizeS) + 2*menuMnemonicGap + } if item.Description != "" { textWidth = max(textWidth, canvas.TextWidth(item.Description, theme.Metrics.FontSizeS)) } @@ -829,7 +848,7 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { if paint := menu.options.paintItem; paint != nil { paint(MenuItemPaint{ Canvas: canvas, Theme: theme, Bounds: bounds, - Label: item.Label, Description: item.Description, Shortcut: item.Shortcut, + Label: item.Label, Mnemonic: item.Mnemonic, Description: item.Description, Shortcut: item.Shortcut, Checked: item.Kind == menuCheckbox && item.Checked, Selected: item.Kind == menuRadio && item.Selected, Expanded: item.Kind == menuSubmenu && item.Expanded, @@ -901,14 +920,29 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { } labelWidth := max(0, bounds.Width-left-right) label := item.Label - if canvas.TextWidthWeight(label, theme.Metrics.FontSizeM, gfx.WeightRegular) > labelWidth { - label = canvas.FitLine(label, theme.Metrics.FontSizeM, gfx.WeightRegular, labelWidth) + mnemonic := menuMnemonicLabel(item.Mnemonic) + mnemonicWidth := float32(0) + if mnemonic != "" { + mnemonicWidth = canvas.TextWidth(mnemonic, theme.Metrics.FontSizeS) + 2*menuMnemonicGap + if mnemonicWidth > labelWidth { + mnemonic, mnemonicWidth = "", 0 + } + } + labelAreaWidth := max(0, labelWidth-mnemonicWidth) + if canvas.TextWidthWeight(label, theme.Metrics.FontSizeM, gfx.WeightRegular) > labelAreaWidth { + label = canvas.FitLine(label, theme.Metrics.FontSizeM, gfx.WeightRegular, labelAreaWidth) } - canvas.Label(label, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelWidth, Height: labelHeight}, gfx.TextStyle{ + canvas.Label(label, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelAreaWidth, Height: labelHeight}, gfx.TextStyle{ Size: theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, }) if label != "" && label != item.Label { - canvas.HoverHint(0, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelWidth, Height: labelHeight}, item.Label, item.ID) + canvas.HoverHint(0, gfx.Rect{X: bounds.X + left, Y: labelY, Width: labelAreaWidth, Height: labelHeight}, item.Label, item.ID) + } + if mnemonic != "" { + labelUsed := min(labelAreaWidth, canvas.TextWidthWeight(label, theme.Metrics.FontSizeM, gfx.WeightRegular)) + canvas.Label(mnemonic, gfx.Rect{X: bounds.X + left + labelUsed + menuMnemonicGap, Y: labelY, Width: mnemonicWidth - menuMnemonicGap, Height: labelHeight}, gfx.TextStyle{ + Size: theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: dropdownMenuOpacity(theme.MutedForeground, item.Disabled), + }) } if item.Description != "" { color := theme.MutedForeground @@ -917,7 +951,7 @@ func (menu *menuSurface) paintItem(bounds gfx.Rect, item menuItem) { } color = dropdownMenuOpacity(color, item.Disabled) width := max(0, bounds.Width-left-right-menu.hitInset) - labelEllipsis(canvas, item.Description, gfx.Rect{X: bounds.X + left, Y: descriptionY, Width: width, Height: descriptionHeight}, gfx.TextStyle{ + canvas.LabelEllipsis(item.Description, gfx.Rect{X: bounds.X + left, Y: descriptionY, Width: width, Height: descriptionHeight}, gfx.TextStyle{ Size: theme.Metrics.FontSizeS, Weight: gfx.WeightRegular, Color: color, }, item.ID) } diff --git a/components/hierarchy_menu.go b/components/hierarchy_menu.go index 42e616c89..55ed916c4 100644 --- a/components/hierarchy_menu.go +++ b/components/hierarchy_menu.go @@ -226,7 +226,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } paintChevron(canvas, &hierarchyLeftIcon, gfx.Rect{X: bounds.X + 8, Y: bounds.Y, Width: 16, Height: bounds.Height}, look.Foreground) text := gfx.Rect{X: bounds.X + 32, Y: bounds.Y, Width: max(bounds.Width-40, 0), Height: bounds.Height} - labelEllipsis(canvas, label, text, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: look.Foreground}, o.OptionIDs.At(hierarchyBackIndex)) + canvas.LabelEllipsis(label, text, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: look.Foreground}, o.OptionIDs.At(hierarchyBackIndex)) canvas.HitWithOptions(o.OptionIDs.At(hierarchyBackIndex), bounds, label, gfx.HitOptions{Role: gfx.RoleButton, Description: m.Nodes[parent].Path, SkipFocus: true}) menu.top += bounds.Height menu.viewHeight = max(menu.viewHeight-bounds.Height, 0) @@ -261,7 +261,7 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m reserve += 16 } labelWidth := max(rowBounds.Width-reserve, 0) - labelEllipsis(canvas, info.Name, gfx.Rect{X: rowBounds.X + 8, Y: rowBounds.Y, Width: labelWidth, Height: rowBounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) + canvas.LabelEllipsis(info.Name, gfx.Rect{X: rowBounds.X + 8, Y: rowBounds.Y, Width: labelWidth, Height: rowBounds.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) switch { case info.Count > 0 && rowBounds.Width >= reserve: chevron := &chevronRightIcon @@ -323,7 +323,7 @@ func paintAction(m *HierarchyMenuState, menu *menuSurface, action HierarchyMenuA } color := look.Foreground label := gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-16, 0), Height: row.Height} - labelEllipsis(canvas, action.Label, label, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, action.ID) + canvas.LabelEllipsis(action.Label, label, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, action.ID) row.Width = max(row.Width-menu.hitInset, 0) canvas.HitWithOptions(action.ID, row, action.Label, gfx.HitOptions{Role: gfx.RoleMenuItem, Disabled: action.Disabled, SkipFocus: true}) }) diff --git a/components/label.go b/components/label.go index a7e4fc1f1..560ca6ffb 100644 --- a/components/label.go +++ b/components/label.go @@ -75,25 +75,3 @@ func (label LabelPainter) Paint(text string) { }) } } - -// labelEllipsis keeps the complete value alongside the fitted label. Its -// control may declare its hit after painting; that hit still owns the pointer. -// The hint is dropped where the page leaves its ellipsis tooltips off. -func labelEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { - shown := canvas.FitLine(value, style.Size, style.Weight, bounds.Width) - canvas.Label(shown, bounds, style) - if shown != "" && shown != value { - canvas.HoverHint(0, bounds, value, target) - } -} - -// labelOrEllipsis draws a value a control has always clipped at the edge of its -// bounds, as Label does. Where the page shows ellipsis tooltips it ends the value -// with an ellipsis instead, as labelEllipsis does, since the hint shows the rest. -func labelOrEllipsis(canvas *gfx.Canvas, value string, bounds gfx.Rect, style gfx.TextStyle, target gfx.ID) { - if canvas.HoverHintOwner().IsZero() { - canvas.Label(value, bounds, style) - return - } - labelEllipsis(canvas, value, bounds, style, target) -} diff --git a/components/markdown.go b/components/markdown.go index 4445d099d..2f24d1783 100644 --- a/components/markdown.go +++ b/components/markdown.go @@ -6,6 +6,7 @@ import ( "unicode/utf8" "unsafe" + "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/markdown" ) @@ -100,39 +101,6 @@ func MarkdownLookFor(theme gfx.Theme) MarkdownLook { } } -// MarkdownSelection is a range of the rendered text of a MarkdownView, in byte -// offsets. Anchor is where the user began and Focus is where the pointer is now; -// either may be ahead of the other. Range clamps and orders them against the -// view's text, so a selection that was made before a message changed still -// copies the part that is there. -type MarkdownSelection struct { - Anchor, Focus int -} - -// Range returns the selected bytes, ordered and clamped to text. Clamping snaps -// both ends back to the start of the rune they point into, because a selection -// kept while a streaming message shortened can land inside a multi-byte -// character; without the snap SelectedText would return invalid UTF-8. -func (s MarkdownSelection) Range(text []byte) (start, end int) { - start, end = s.Anchor, s.Focus - if start > end { - start, end = end, start - } - start = snapRune(text, min(max(start, 0), len(text))) - end = snapRune(text, min(max(end, 0), len(text))) - return start, end -} - -// snapRune moves offset back to the leading byte of the rune it points into. -// Offsets that are already at a boundary, including len(text), are returned as -// they are. -func snapRune(text []byte, offset int) int { - for offset > 0 && offset < len(text) && text[offset]&0xC0 == 0x80 { - offset-- - } - return offset -} - // MarkdownCode is a fenced code block of a laid-out document: where it is, so // the application can put a copy button on it, and what it holds. type MarkdownCode struct { @@ -157,7 +125,7 @@ type MarkdownPaint struct { // LinkCount of the views before it. Base int // Selection is highlighted behind its text. The zero range paints nothing. - Selection MarkdownSelection + Selection base.TextRange } var _ gfx.TextPlacement = (*MarkdownView)(nil) @@ -209,7 +177,7 @@ func (v *MarkdownView) TextLen() int { return len(v.plain) } // SelectedText returns the rendered text of sel: what a copy of the selection // puts on the clipboard. Offsets are clamped to the laid-out text, so an empty // view or a selection outside it returns "". -func (v *MarkdownView) SelectedText(sel MarkdownSelection) string { +func (v *MarkdownView) SelectedText(sel base.TextRange) string { start, end := sel.Range(v.plain) return string(v.plain[start:end]) } diff --git a/components/markdown_test.go b/components/markdown_test.go index 525aa7b0c..c475f67c7 100644 --- a/components/markdown_test.go +++ b/components/markdown_test.go @@ -6,6 +6,7 @@ import ( "testing" "unicode/utf8" + "github.com/vivaui/viva/base" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/markdown" ) @@ -54,22 +55,22 @@ func TestMarkdownSelectionRangeClampsAndOrders(t *testing.T) { const digits = "0123456789" // ASCII, so every offset is a rune boundary tests := []struct { name string - sel MarkdownSelection + sel base.TextRange text string start int end int }{ - {name: "empty", sel: MarkdownSelection{Anchor: 4, Focus: 4}, text: digits, start: 4, end: 4}, - {name: "forward", sel: MarkdownSelection{Anchor: 2, Focus: 7}, text: digits, start: 2, end: 7}, - {name: "reversed", sel: MarkdownSelection{Anchor: 7, Focus: 2}, text: digits, start: 2, end: 7}, - {name: "negative", sel: MarkdownSelection{Anchor: -3, Focus: 4}, text: digits, start: 0, end: 4}, - {name: "past the end", sel: MarkdownSelection{Anchor: 4, Focus: 99}, text: digits, start: 4, end: 10}, - {name: "outside both ways", sel: MarkdownSelection{Anchor: -8, Focus: 99}, text: digits, start: 0, end: 10}, - {name: "empty text", sel: MarkdownSelection{Anchor: -1, Focus: 3}, text: "", start: 0, end: 0}, - {name: "start inside a rune", sel: MarkdownSelection{Anchor: 3, Focus: 5}, text: "a 中", start: 2, end: 5}, - {name: "end inside a rune", sel: MarkdownSelection{Anchor: 0, Focus: 4}, text: "a 中", start: 0, end: 2}, - {name: "both inside a rune", sel: MarkdownSelection{Anchor: 4, Focus: 3}, text: "a 中", start: 2, end: 2}, - {name: "clamped into a rune", sel: MarkdownSelection{Anchor: 3, Focus: 6}, text: "a 中", start: 2, end: 5}, + {name: "empty", sel: base.TextRange{Anchor: 4, Focus: 4}, text: digits, start: 4, end: 4}, + {name: "forward", sel: base.TextRange{Anchor: 2, Focus: 7}, text: digits, start: 2, end: 7}, + {name: "reversed", sel: base.TextRange{Anchor: 7, Focus: 2}, text: digits, start: 2, end: 7}, + {name: "negative", sel: base.TextRange{Anchor: -3, Focus: 4}, text: digits, start: 0, end: 4}, + {name: "past the end", sel: base.TextRange{Anchor: 4, Focus: 99}, text: digits, start: 4, end: 10}, + {name: "outside both ways", sel: base.TextRange{Anchor: -8, Focus: 99}, text: digits, start: 0, end: 10}, + {name: "empty text", sel: base.TextRange{Anchor: -1, Focus: 3}, text: "", start: 0, end: 0}, + {name: "start inside a rune", sel: base.TextRange{Anchor: 3, Focus: 5}, text: "a 中", start: 2, end: 5}, + {name: "end inside a rune", sel: base.TextRange{Anchor: 0, Focus: 4}, text: "a 中", start: 0, end: 2}, + {name: "both inside a rune", sel: base.TextRange{Anchor: 4, Focus: 3}, text: "a 中", start: 2, end: 2}, + {name: "clamped into a rune", sel: base.TextRange{Anchor: 3, Focus: 6}, text: "a 中", start: 2, end: 5}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -95,7 +96,7 @@ func TestMarkdownSelectionClampedMidRuneIsValidUTF8(t *testing.T) { view.Layout(canvas, style, &doc, 400) } layout("a `中") - sel := MarkdownSelection{Anchor: 3, Focus: view.TextLen()} + sel := base.TextRange{Anchor: 3, Focus: view.TextLen()} if got := view.SelectedText(sel); got != "中" { t.Fatalf("SelectedText before the change = %q, want %q", got, "中") } @@ -114,7 +115,7 @@ func TestEmptyMarkdownViewHasNoTextToSelect(t *testing.T) { if got := view.TextLen(); got != 0 { t.Fatalf("TextLen = %d, want 0", got) } - if got := view.SelectedText(MarkdownSelection{Anchor: -2, Focus: 5}); got != "" { + if got := view.SelectedText(base.TextRange{Anchor: -2, Focus: 5}); got != "" { t.Fatalf("SelectedText = %q, want empty", got) } } @@ -125,10 +126,10 @@ func TestMarkdownSelectionUsesRenderedTextWithoutSoftWraps(t *testing.T) { t.Fatalf("the paragraph did not wrap: %+v", view.pieces) } const want = "alpha beta gamma delta epsilon" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } - if got := view.SelectedText(MarkdownSelection{Anchor: 11, Focus: 16}); got != "gamma" { + if got := view.SelectedText(base.TextRange{Anchor: 11, Focus: 16}); got != "gamma" { t.Fatalf("selected %q, want gamma", got) } } @@ -136,7 +137,7 @@ func TestMarkdownSelectionUsesRenderedTextWithoutSoftWraps(t *testing.T) { func TestMarkdownSelectionHasOneBreakBetweenBlocks(t *testing.T) { view, _ := layoutMarkdown(t, "first paragraph\n\nsecond paragraph", 200, MarkdownStyle{Size: 12}) const want = "first paragraph\nsecond paragraph" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -145,7 +146,7 @@ func TestMarkdownSelectionUsesVisibleInlineTextAndSpacing(t *testing.T) { src := "before **bold** and `code` and a [link](https://example.com/x) after" view, _ := layoutMarkdown(t, src, 200, MarkdownStyle{Size: 12}) const want = "before bold and code and a link after" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -154,7 +155,7 @@ func TestMarkdownSelectionReadsTableCellsInRenderedOrder(t *testing.T) { src := "| Name | Value |\n|:--|--:|\n| ssh | shell |\n| ftp | old |\n" view, _ := layoutMarkdown(t, src, 300, MarkdownStyle{Size: 12}) const want = "Name Value\nssh shell\nftp old" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -189,7 +190,7 @@ func TestFencedCodeCopiesSourceLinesWithoutVisualWraps(t *testing.T) { t.Fatalf("the long code line did not wrap: %d pieces", mono) } want := line + "\nsecond line" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -197,7 +198,7 @@ func TestFencedCodeCopiesSourceLinesWithoutVisualWraps(t *testing.T) { func TestFencedCodeKeepsTabsAndCopiesThem(t *testing.T) { view, _ := layoutMarkdown(t, "```\n\tfoo\tbar\n```\n", 300, MarkdownStyle{Size: 12}) const want = "\tfoo\tbar" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } tests := []struct { @@ -211,7 +212,7 @@ func TestFencedCodeKeepsTabsAndCopiesThem(t *testing.T) { {start: 5, end: 8, want: "bar"}, } for _, test := range tests { - if got := view.SelectedText(MarkdownSelection{Anchor: test.start, Focus: test.end}); got != test.want { + if got := view.SelectedText(base.TextRange{Anchor: test.start, Focus: test.end}); got != test.want { t.Errorf("select %d..%d = %q, want %q", test.start, test.end, got, test.want) } } @@ -222,7 +223,7 @@ func TestCodeChunkBoundariesDoNotSplitATab(t *testing.T) { // to end before it, and the next one owns the whole tab. view, _ := layoutMarkdown(t, "```\nabcde\tX\n```\n", 56, MarkdownStyle{Size: 12}) const want = "abcde\tX" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } last := int32(0) @@ -387,7 +388,7 @@ func TestMarkdownPaintsPaintedSelection(t *testing.T) { selected := gfx.Color{Red: 1, Alpha: 1} var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ - Look: MarkdownLook{Selection: selected}, X: 10, Y: 20, Selection: MarkdownSelection{Anchor: 0, Focus: 5}, + Look: MarkdownLook{Selection: selected}, X: 10, Y: 20, Selection: base.TextRange{Anchor: 0, Focus: 5}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { @@ -410,7 +411,7 @@ func TestMarkdownPaintsNoSelectionForAnEmptyRange(t *testing.T) { selected := gfx.Color{Red: 1, Alpha: 1} var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ - Look: MarkdownLook{Selection: selected}, Selection: MarkdownSelection{Anchor: 4, Focus: 4}, + Look: MarkdownLook{Selection: selected}, Selection: base.TextRange{Anchor: 4, Focus: 4}, }) if rects := markdownSelectionRects(&painted, selected); len(rects) != 0 { t.Fatalf("empty selection painted %+v", rects) @@ -428,7 +429,7 @@ func TestMarkdownSelectionIsClippedToVisibleLines(t *testing.T) { } second := view.pieces[1] selected := gfx.Color{Red: 1, Alpha: 1} - paint := func(selection MarkdownSelection) *gfx.Canvas { + paint := func(selection base.TextRange) *gfx.Canvas { var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ Look: MarkdownLook{Selection: selected}, Selection: selection, @@ -436,10 +437,10 @@ func TestMarkdownSelectionIsClippedToVisibleLines(t *testing.T) { }) return &painted } - if rects := markdownSelectionRects(paint(MarkdownSelection{Anchor: 0, Focus: 5}), selected); len(rects) != 0 { + if rects := markdownSelectionRects(paint(base.TextRange{Anchor: 0, Focus: 5}), selected); len(rects) != 0 { t.Fatalf("a selection above the clip painted %+v", rects) } - if rects := markdownSelectionRects(paint(MarkdownSelection{Anchor: 0, Focus: 12}), selected); len(rects) != 1 { + if rects := markdownSelectionRects(paint(base.TextRange{Anchor: 0, Focus: 12}), selected); len(rects) != 1 { t.Fatalf("the visible line painted %d selection rectangles, want 1", len(rects)) } } @@ -454,7 +455,7 @@ func TestMarkdownCodeSelectionCoversATabAsCells(t *testing.T) { behind := gfx.Color{Green: 1, Alpha: 1} var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ - Look: MarkdownLook{Selection: selected, CodeFill: behind}, Selection: MarkdownSelection{Anchor: 5, Focus: 6}, + Look: MarkdownLook{Selection: selected, CodeFill: behind}, Selection: base.TextRange{Anchor: 5, Focus: 6}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { @@ -617,7 +618,7 @@ func TestMarkdownLayoutAndPaintDoNotAllocateOnceWarm(t *testing.T) { canvas := markdownCanvas() var view MarkdownView look := MarkdownLookFor(gfx.DarkTheme()) - selection := MarkdownSelection{Anchor: 2, Focus: 40} + selection := base.TextRange{Anchor: 2, Focus: 40} run := func() { canvas.Reset() view.Layout(canvas, MarkdownStyle{Size: 13}, &doc, 400) @@ -661,7 +662,7 @@ func TestMarkdownCandidateLineMeasurementsMatchWhatIsPainted(t *testing.T) { const width = 132 view.Layout(nonlinearMarkdownCanvas(), MarkdownStyle{Size: 12}, &doc, width) want := strings.NewReplacer("**", "", "`", "").Replace(test.src) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != want { t.Fatalf("rendered text = %q, want %q", got, want) } for _, piece := range view.pieces { @@ -704,7 +705,7 @@ func TestMarkdownClosingPunctuationMovesWithThePrecedingText(t *testing.T) { if moved == nil || moved.x != 0 || moved.y == 0 { t.Fatalf("punctuation was not moved with its preceding text: %+v", view.pieces) } - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "abcdef。" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "abcdef。" { t.Fatalf("rendered text = %q", got) } } @@ -717,7 +718,7 @@ func TestMarkdownLongClosingRunKeepsPunctuationInsideTheColumn(t *testing.T) { var view MarkdownView const width = 40 view.Layout(markdownCanvas(), MarkdownStyle{Size: 12}, &doc, width) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "abcdefg。" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "abcdefg。" { t.Fatalf("rendered text = %q", got) } for _, piece := range view.pieces { @@ -740,7 +741,7 @@ func TestMarkdownLongClosingRunKeepsPunctuationInsideTheColumn(t *testing.T) { func TestMarkdownMonoClosingRunMovesItsSuffixWithThePunctuation(t *testing.T) { const width = 40 view, canvas := paintedMarkdown(t, "a`bcdefgh`。", width) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "abcdefgh。" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "abcdefgh。" { t.Fatalf("rendered text = %q, want %q", got, "abcdefgh。") } var code []*mdPiece @@ -791,7 +792,7 @@ func TestMarkdownClosingPunctuationUsesTheJoinedShapedWidth(t *testing.T) { var view MarkdownView const width = 40 view.Layout(nonlinearMarkdownCanvas(), MarkdownStyle{Size: 12}, &doc, width) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "xbcdef。" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "xbcdef。" { t.Fatalf("rendered text = %q", got) } for _, piece := range view.pieces { @@ -847,7 +848,7 @@ func TestMarkdownClosingPunctuationKeepsThePrecedingSpanStyle(t *testing.T) { func TestMarkdownBreakpointRewindPaintsEachPieceBackgroundAndLinkOnce(t *testing.T) { src := "a**bcdef**。 [link](https://example.com)" view, _ := layoutMarkdown(t, src, 40, MarkdownStyle{Size: 12}) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "abcdef。 link" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "abcdef。 link" { t.Fatalf("rendered text = %q", got) } paintedFor := func(label string) map[string]int { @@ -907,7 +908,7 @@ func TestMarkdownReflowKeepsShapedTextInsideTheColumn(t *testing.T) { t.Errorf("at %v wide, piece %q is at %v..%v", width, p.text, p.x, p.x+p.w) } } - if got, want := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}), "端口绑定在 127.0.0.1,外部访问仍要从宿主机转发。"; got != want { + if got, want := view.SelectedText(base.TextRange{Focus: view.TextLen()}), "端口绑定在 127.0.0.1,外部访问仍要从宿主机转发。"; got != want { t.Errorf("at %v wide, rendered text = %q, want %q", width, got, want) } } @@ -920,7 +921,7 @@ func TestLongTokensWrapByCompleteUTF8Characters(t *testing.T) { var view MarkdownView const width = 72 view.Layout(nonlinearMarkdownCanvas(), MarkdownStyle{Size: 12}, &doc, width) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != token { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != token { t.Fatalf("rendered text = %q, want %q", got, token) } for _, p := range view.pieces { @@ -1146,7 +1147,7 @@ func TestMarkdownStrikeOnInlineCodeCoversOnlyTheTextArea(t *testing.T) { func TestInlineCodeCopyDoesNotIncludeVisualPadding(t *testing.T) { src := "端口绑`127.0.0.1`还是" view, _ := layoutMarkdown(t, src, 220, MarkdownStyle{Size: 12}) - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != "端口绑127.0.0.1还是" { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != "端口绑127.0.0.1还是" { t.Errorf("copied text = %q", got) } var piece *mdPiece @@ -1159,7 +1160,7 @@ func TestInlineCodeCopyDoesNotIncludeVisualPadding(t *testing.T) { if piece == nil { t.Fatal("no inline code piece") } - selected := view.SelectedText(MarkdownSelection{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}) + selected := view.SelectedText(base.TextRange{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}) if selected != "127.0.0.1" { t.Errorf("selected inline code = %q", selected) } @@ -1168,7 +1169,7 @@ func TestInlineCodeCopyDoesNotIncludeVisualPadding(t *testing.T) { func TestMarkdownAdjacentInlineCodeAndPunctuationKeepFullFragments(t *testing.T) { view, _ := layoutMarkdown(t, "`a` `bb`,前`127.0.0.1`后", 220, MarkdownStyle{Size: 12}) const want = "a bb,前127.0.0.1后" - if got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Focus: view.TextLen()}); got != want { t.Fatalf("rendered text = %q, want %q", got, want) } for _, text := range []string{"a", "bb", "127.0.0.1"} { @@ -1208,7 +1209,7 @@ func TestMarkdownTinyWidthsTerminateWithValidText(t *testing.T) { doc.Parse(test.src) var view MarkdownView view.Layout(nonlinearMarkdownCanvas(), MarkdownStyle{Size: 12}, &doc, 40) - got := view.SelectedText(MarkdownSelection{Focus: view.TextLen()}) + got := view.SelectedText(base.TextRange{Focus: view.TextLen()}) if got != test.want { t.Fatalf("rendered text = %q, want %q", got, test.want) } @@ -1243,7 +1244,7 @@ func TestInlineCodeSelectionRectsStayInsideThePaddedBackground(t *testing.T) { var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ Look: MarkdownLook{Selection: selected}, - Selection: MarkdownSelection{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}, + Selection: base.TextRange{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { @@ -1287,7 +1288,7 @@ func TestMarkdownPaintNestsItsClipAndRestoresTheCallerStack(t *testing.T) { view.Layout(markdownCanvas(), MarkdownStyle{Size: 12}, &doc, 300) selection := gfx.Color{Red: 1, Alpha: 1} view.Paint(&canvas, MarkdownPaint{ - Look: MarkdownLook{Selection: selection}, Selection: MarkdownSelection{Anchor: 0, Focus: view.TextLen()}, + Look: MarkdownLook{Selection: selection}, Selection: base.TextRange{Anchor: 0, Focus: view.TextLen()}, X: inner.X, Y: inner.Y, Clip: inner, Links: gfx.Scope(1), }) if clips := canvas.Clips(); len(clips) != 1 || clips[0].Bounds != outer { @@ -1503,7 +1504,7 @@ func TestFencedCodeBlankLinesLayOut(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { view, _ := layoutMarkdown(t, test.src, 300, MarkdownStyle{Size: 12}) - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != test.want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != test.want { t.Fatalf("selected %q, want %q", got, test.want) } }) @@ -1513,7 +1514,7 @@ func TestFencedCodeBlankLinesLayOut(t *testing.T) { func TestFencedCodeToleratesInvalidUTF8(t *testing.T) { view, _ := layoutMarkdown(t, "```\n\xff\n```\n", 300, MarkdownStyle{Size: 12}) const want = "\xff" - if got := view.SelectedText(MarkdownSelection{Anchor: 0, Focus: view.TextLen()}); got != want { + if got := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}); got != want { t.Fatalf("selected %q, want %q", got, want) } } @@ -1528,7 +1529,7 @@ func TestInlineCodeSelectionUsesItsOwnCellWidth(t *testing.T) { var painted gfx.Canvas // "alpha " is six bytes, then the four bytes of the inline code. view.Paint(&painted, MarkdownPaint{ - Look: MarkdownLook{Selection: selected}, Selection: MarkdownSelection{Anchor: 6, Focus: 10}, + Look: MarkdownLook{Selection: selected}, Selection: base.TextRange{Anchor: 6, Focus: 10}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { @@ -1757,7 +1758,7 @@ func TestHeadingInlineCodeSelectionUsesItsOwnCellWidth(t *testing.T) { var painted gfx.Canvas view.Paint(&painted, MarkdownPaint{ Look: MarkdownLook{Selection: selected}, - Selection: MarkdownSelection{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}, + Selection: base.TextRange{Anchor: int(piece.plainLo), Focus: int(piece.plainHi)}, }) rects := markdownSelectionRects(&painted, selected) if len(rects) != 1 { diff --git a/components/menubar.go b/components/menubar.go index ce743b33d..68b75ad04 100644 --- a/components/menubar.go +++ b/components/menubar.go @@ -165,8 +165,11 @@ type MenubarTrigger struct { // MenubarItem describes one stable action inside an open menubar popup. type MenubarItem struct { - ID gfx.ID - Label string + ID gfx.ID + Label string + // Mnemonic is an optional one-character key shown after the label and + // matched before ordinary menu typeahead. + Mnemonic string Shortcut string // Keys, when set, replace Shortcut with one keycap per entry (for example // "⌘", "⌥", "H"), painted with Kbd at the row's trailing edge. @@ -192,7 +195,7 @@ type MenubarItem struct { func (item MenubarItem) common() menuItem { return menuItem{ - ID: item.ID, Label: item.Label, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, + ID: item.ID, Label: item.Label, Mnemonic: item.Mnemonic, Shortcut: item.Shortcut, Keys: item.Keys, TrailingWidth: item.TrailingWidth, Value: item.Value, Hint: item.Hint, Kind: menuKind(item.Kind), Destructive: item.Variant == MenubarItemDestructive, Checked: item.Checked, Selected: item.Selected, Disabled: item.Disabled, Inset: item.Inset, Expanded: item.Expanded, Icon: item.Icon, } diff --git a/components/multi_select.go b/components/multi_select.go index bd03e243f..c822c07c1 100644 --- a/components/multi_select.go +++ b/components/multi_select.go @@ -184,7 +184,7 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M } label = text } - labelEllipsis(canvas, label, gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-38, 0), Height: row.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) + canvas.LabelEllipsis(label, gfx.Rect{X: row.X + 8, Y: row.Y, Width: max(row.Width-38, 0), Height: row.Height}, gfx.TextStyle{Size: theme.Metrics.FontSizeM, Color: color}, id) if choice.Selected { paintCheck(canvas, gfx.Rect{X: row.X + row.Width - 25, Y: row.Y, Width: 16, Height: row.Height}, 14, color) } diff --git a/components/select.go b/components/select.go index 995b4fd5d..465546388 100644 --- a/components/select.go +++ b/components/select.go @@ -372,7 +372,7 @@ func (selectControl Select) paintTrigger() { if options.Weight > 0 { weight = options.Weight } - labelOrEllipsis(canvas, value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + canvas.LabelOrEllipsis(value, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: textSize, Weight: weight, Color: foreground, }, options.TriggerID) } @@ -403,7 +403,7 @@ func (selectControl *Select) paintItem(bounds gfx.Rect, item SelectItem) { textX += SelectIconSpan textWidth -= SelectIconSpan } - labelOrEllipsis(selectControl.canvas, item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ + selectControl.canvas.LabelOrEllipsis(item.Label, gfx.Rect{X: textX, Y: bounds.Y, Width: selectMax(0, textWidth), Height: bounds.Height}, gfx.TextStyle{ Size: selectControl.theme.Metrics.FontSizeM, Weight: gfx.WeightRegular, Color: foreground, }, item.ID) if item.Selected { diff --git a/components/single_select.go b/components/single_select.go index f71519751..6e007a313 100644 --- a/components/single_select.go +++ b/components/single_select.go @@ -264,18 +264,18 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * func paintLabelAndDetail(canvas *gfx.Canvas, theme gfx.Theme, x, y, width, height float32, label, detail string, color gfx.Color, disabled bool, target gfx.ID) { sizeM, sizeS := theme.Metrics.FontSizeM, theme.Metrics.FontSizeS if detail == "" { - labelEllipsis(canvas, label, gfx.Rect{X: x, Y: y, Width: width, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) + canvas.LabelEllipsis(label, gfx.Rect{X: x, Y: y, Width: width, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) return } labelWidth := min(canvas.TextWidthWeight(label, sizeM, gfx.WeightRegular), max(width-40, 0)) - labelEllipsis(canvas, label, gfx.Rect{X: x, Y: y, Width: labelWidth, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) + canvas.LabelEllipsis(label, gfx.Rect{X: x, Y: y, Width: labelWidth, Height: height}, gfx.TextStyle{Size: sizeM, Color: color}, target) detailX := x + labelWidth + singleSelectDetailGap if detailWidth := max(x+width-detailX, 0); detailWidth > 0 { muted := theme.MutedForeground if disabled { muted.Alpha *= .5 } - labelEllipsis(canvas, detail, gfx.Rect{X: detailX, Y: y, Width: detailWidth, Height: height}, gfx.TextStyle{Size: sizeS, Color: muted}, target) + canvas.LabelEllipsis(detail, gfx.Rect{X: detailX, Y: y, Width: detailWidth, Height: height}, gfx.TextStyle{Size: sizeS, Color: muted}, target) } } diff --git a/docs/conformance.md b/docs/conformance.md index 4317bb6fb..a8a7d435e 100644 --- a/docs/conformance.md +++ b/docs/conformance.md @@ -32,6 +32,7 @@ desktop session. | A panel opens, paints and closes from another goroutine | `WindowPanel` is a window kind of its own on each backend | | A notification paints without pointer input and returns to idle | a notification may open while the pointer stays on another window | | A status item can be added, changed and removed (SKIP where the desktop has no status area) | `AddStatusItem` and its setters on three different APIs | +| A status preview opens without activation and closes after leaving both surfaces. A host without paired pointer events keeps normal activation and menu behavior. | `TestStatusPreviewCrossesGapAndClosesOnce`, `TestStatusPreviewWithoutHoverControlLeavesIconUsable` | | `Quit` ends the loop though windows refuse to close, even as the last-used window closes | the loop must end whatever the windows say | It was written after the status-icon work, and each check is something a real @@ -87,6 +88,33 @@ Not failures; the API reports what the platform can say. | Corner radius of a panel | the layer's | the system's on Windows 11 (`DWMWA_WINDOW_CORNER_PREFERENCE`, set in the code, not yet checked on screen), square on Windows 10 | square | | Shadow and round corners of a custom-titlebar window | the system's | the system's | drawn by Viva where the desktop composites ("Window frame on Linux"). GNOME/Mutter does not advertise synchronized resize, so on a drag the inset margin can lag at the dragged edge there; otherwise flat and square | +### Status previews + +`examples/guides/status-preview` uses `SetHoverPreview`, handles an opening error, +keeps click activation as a fallback, and calls `RefreshMenu` after its state +changes. Optional host methods are discovered structurally; applications do not +need to name a separate hover or menu control interface. + +- Windows clears the native tooltip with `NIF_TIP` and an empty `szTip` while a + preview is enabled, and restores the latest text when disabled. Visible taskbar + icons support paired Shell events; the Explorer overflow area keeps click and + menu activation. The tooltip transition and overflow still need real-taskbar + checks; native message tests alone do not prove what Explorer draws. +- macOS reports entry and exit through the status button's `NSTrackingArea`. +- Linux StatusNotifier has no paired hover events. The host owns its tooltip; + applications can open a panel from activation or a menu. X11 uses the host's + activation point unchanged, including zero and negative coordinates. The + protocol gives no scale or input-source flag, so pointer proximity must not + be used to guess device pixels or rewrite keyboard activation. A host sending + logical coordinates on a scaled X11 desktop may place the panel incorrectly. + Kylin/UKUI, UOS, mixed-DPI physical monitors, and native Wayland need desktop + verification; single-screen Xvfb does not validate those hosts. On native + Wayland the compositor controls top-level placement. + +`BenchmarkStatusPreview` measures registration, duplicate entry, open/close and +menu refresh with an in-memory host. These numbers include app bookkeeping, not +native window creation or compositor latency. + ## Not done, and why What the Windows and Linux backends do not have yet, recorded so that nobody diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index a429bd060..e53520591 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -53,7 +53,7 @@ Opt-in page packages live under `ui/` (`ui/codeeditor`, `ui/textview`, `ui `ui/metriccard`, `ui/marker`, `ui/sidebar`, `ui/buttongroup`, `ui/togglegroup`, `ui/multiselect`, `ui/hierarchypicker`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, -`ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`). +`ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`). They import only the public `base`, `components`, `gfx`, `ui` and `window` packages, plus the focused `text` editor for editor-like controls and the root `markdown` parser for the Markdown view. They own stable handlers, and are never diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index fe48896de..c09092bdf 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -89,7 +89,8 @@ func (m *model) page(c ui.C) { ### Optional page packages and custom surfaces - A heavy or stateful page control lives in an opt-in package under `ui/`; import it only when the page uses it. -- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`. +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. +- Read-only words the user may copy (an error, a fingerprint, a detail page) go in `ui.TextSelectionArea(c, &m.details).Children(...)`: the `Text`, `Paragraph` and `Wrap` inside can be dragged across, double-clicked and copied, while buttons and fields inside keep their presses. `Box.Unselectable()` takes a decorative text out. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. - The package name is the capability, never a `view` suffix. Name its state type by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`, `hovercard.Card`. Keep locals out of the package name (`cal`, `msg`, `pic`); a model field may keep the domain noun (`m.calendar`). - Some packages expose `pkg.View(c, label, &state)` (`calendar.View`, `markdown.View`); others expose a method on the state (`avatar.New().View(c, label)`, `questionnaire.New().View(c, label)`). `go doc github.com/vivaui/viva/ui/` shows which. @@ -107,7 +108,7 @@ func (m *model) page(c ui.C) { - A control you paint is `ui.Control(c, label, &m.handlers).Grow(1).Draw(m.draw)`. `ui.Handlers` receives keys, pointer, wheel and, with `gfx.RoleTextField` or `gfx.RoleTerminal`, typing and IME through `Text`. Its parts are declared in `Draw` with `d.Canvas.Hit(part, r)`; an event on a part reaches the same handlers with the part as its target. - Custom layout: `ui.CustomLayout(c, &m.layout).Children(...)` with `ui.Layout`'s `MeasureWidth`, `PlaceWidth`, `MeasureHeight`, `PlaceHeight`. The page keeps identity, focus and hits; the layout owns the children's geometry. - Drag and drop: a `ui.DragState` in the model, `.DragSource(&m.drag)` and `.DropTarget(&m.drag, accept, drop)` on `Hit` boxes, or `d.DragSource`/`d.DropTarget` inside a `Draw`. The page routes the pointer; `Dragging()`, `Source()`, `Target()`, `At()` paint the gesture. A press that does not move is still a click. A split pane is `ui.Splitter(c, &m.split)` with a `ui.SplitterState`, not a drag. -- Files from the system: `.DropFiles(&m.drop)` with a `ui.FileDropState` makes a box take files dragged onto it (`Over()` for the highlight, `Dropped()` for the files, once); `ui.OpenFiles(c, options, done)` is the system's picker and `ui.FilePath(file)` a file's path where it has one. `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour` is the whole area with its file list. +- Files from the system: `.DropFiles(&m.drop)` with a `ui.FileDropState` makes a box take files dragged onto it (`Over()` for the highlight, `Dropped()` for the files, once); `ui.OpenFiles(c, options, done)` is the system's picker and `ui.FilePath(file)` a file's path where it has one. `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` is the whole area with its file list. - Painting your own thing: `ui.Slot(c).Draw(func(d *ui.DrawContext) { ... })`, with `d.Canvas.Fill`, `Rounded`, `Border`, `RoundedBorder`, `Elevate`, `DrawPath`, `Label`, `LabelCenter`, `d.Fade`, `d.DashedBorder`. A circle is a `Rounded` square. `Box.Rect()` is only valid in the paint that declared it. - A shortcut is declared where it acts: `if ui.Shortcut(c, ui.Primary, "s") { m.save() }`; `box.Shortcut(0, "delete")` acts while the focus is inside that element. Plain keys stay with a field being typed in. diff --git a/examples/guides/status-preview/main.go b/examples/guides/status-preview/main.go new file mode 100644 index 000000000..4863ff5e0 --- /dev/null +++ b/examples/guides/status-preview/main.go @@ -0,0 +1,98 @@ +package main + +import ( + "fmt" + "log" + "runtime" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +// AppKit must start on the process's main thread. +func init() { runtime.LockOSThread() } + +func main() { + if err := app.RunApplication(run); err != nil { + log.Fatal(err) + } +} + +func run(application *app.Application) error { + var main, preview *app.Window + var tray *app.StatusItem + var wake, previewWake app.Invalidator + unread := 1 + show := func() { + if preview != nil { + preview.Close() + } + main.Show() + } + build := func() app.StatusPreview { + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(8).Children(func() { + ui.Text(c, fmt.Sprintf("%d unread messages", unread)) + if ui.Button(c, "Open application").Clicked() { + c.Canvas().AfterPaint(show) + } + }) + }}) + config := ui.Configure(page, app.Config{ + Title: "Unread messages", Width: 240, Height: 96, Invalidator: &previewWake, + OnClosed: func() { preview = nil }, + }) + return app.StatusPreview{Config: config, Opened: func(window *app.Window, err error) { + if err != nil { + page.Close() + log.Printf("open status preview: %v", err) + return + } + preview = window + }} + } + var err error + main, err = ui.OpenWindow(application, app.Config{Title: "Status preview", Width: 400, Height: 180, Invalidator: &wake}, ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + ui.Text(c, fmt.Sprintf("%d unread messages", unread)) + if ui.Button(c, "Add a message").Clicked() { + unread++ + previewWake.Invalidate() + if tray != nil { + // Linux hosts cache their menu. Notify them when its text changes. + tray.RefreshMenu() + } + } + }) + }, + }) + if err != nil { + return err + } + tray, err = application.AddStatusItem(app.StatusItemConfig{ + Tooltip: "Status preview", Icon: app.StatusIcon{Size: 1, RGBA: []byte{70, 130, 210, 255}, Template: true}, + OnClick: func(click app.StatusClick) { + if click.PanelDismissed { + return + } + // Click remains available on hosts without paired hover events. + spec := build() + spec.Config.WindowMode, spec.Config.Anchor = app.WindowPanel, click.Anchor + window, err := application.OpenWindow(spec.Config, nil) + spec.Opened(window, err) + }, + Menu: func() []app.MenuItem { + return []app.MenuItem{ + {Title: fmt.Sprintf("%d unread messages", unread), ID: "unread", OnSelect: show}, + {Title: "Quit", OnSelect: application.Quit}, + } + }, + }) + if err != nil { + log.Printf("status area unavailable; main window remains usable: %v", err) + return nil + } + tray.SetHoverPreview(build) + return nil +} diff --git a/gfx/canvas.go b/gfx/canvas.go index cd38363b4..13718b2de 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -527,6 +527,12 @@ type HitOptions struct { PassPrimary bool // label makes the hit a label of its ID's control (see Canvas.HitLabel). label bool + // Presentational makes the hit a region that only takes the pointer: a part of a + // control over content that assistive technology already reads, such as the + // painted words of a selectable text, which shows the text cursor over the + // words. It has no accessibility node of its own and is never focused; a press + // on it reaches its control as a press on any part does. + Presentational bool // Autofocus gives the hit the keyboard in the paint where it first // appears, that is, when the previous paint did not declare its ID. Use it // for a page that should be ready to type into as soon as it is shown, @@ -653,6 +659,8 @@ type Hit struct { // Container marks a semantic region with no target: a menu, listbox, grid, // heading or status area. It is not hit-testable and declares no control. Container bool + // Presentational is HitOptions.Presentational. + Presentational bool // IsLabel marks a label of the control the ID names (see Canvas.HitLabel): // a press on it is a press on the control, it is no tab stop and no node of // its own, and its Label text names the control for assistive technology. @@ -1734,7 +1742,7 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H if role == 0 { role = RoleButton } - focusable := (!options.Disabled || options.FocusableWhenDisabled) && !options.SkipFocus + focusable := (!options.Disabled || options.FocusableWhenDisabled) && !options.SkipFocus && !options.Presentational if options.Secure { options.Value = "" } @@ -1761,7 +1769,7 @@ func (canvas *Canvas) HitWithOptions(id ID, bounds Rect, label string, options H Multiline: options.Multiline, ReadOnly: options.ReadOnly, Invalid: options.Invalid, Secure: options.Secure, Description: options.Description, Level: options.Level, PosInSet: options.PosInSet, SetSize: options.SetSize, Live: options.Live, Range: options.Range, - Focusable: focusable, SkipTab: focusable && options.SkipTab, Autofocus: options.Autofocus && focusable, IsLabel: options.label, Backdrop: options.Backdrop, + Focusable: focusable, SkipTab: focusable && options.SkipTab, Autofocus: options.Autofocus && focusable, IsLabel: options.label, Presentational: options.Presentational, Backdrop: options.Backdrop, PassSecondary: options.Backdrop && options.PassSecondary, PassPrimary: options.Backdrop && options.PassPrimary, HideNativeOverlays: options.HideNativeOverlays, NavigationKeys: options.NavigationKeys, diff --git a/gfx/hover_hint.go b/gfx/hover_hint.go index a5b270f7a..b463cf9ad 100644 --- a/gfx/hover_hint.go +++ b/gfx/hover_hint.go @@ -41,6 +41,29 @@ func (canvas *Canvas) HoverHint(owner Scope, bounds Rect, text string, target .. canvas.hoverHints = append(canvas.hoverHints, hint) } +// LabelEllipsis draws value fitted to bounds.Width with an ellipsis and keeps +// the complete value as a hover hint when shortened. The hint is dropped where +// the page leaves its ellipsis tooltips off. +func (canvas *Canvas) LabelEllipsis(value string, bounds Rect, style TextStyle, target ...ID) { + shown := canvas.FitLine(value, style.Size, style.Weight, bounds.Width) + canvas.Label(shown, bounds, style) + if shown != "" && shown != value { + canvas.HoverHint(0, bounds, value, target...) + } +} + +// LabelOrEllipsis draws a value a control has always clipped at the edge of its +// bounds, as Label does. Where the page shows ellipsis tooltips it ends the +// value with an ellipsis instead, as LabelEllipsis does, since the hint shows +// the rest. +func (canvas *Canvas) LabelOrEllipsis(value string, bounds Rect, style TextStyle, target ...ID) { + if canvas.hoverHintOwner.IsZero() { + canvas.Label(value, bounds, style) + return + } + canvas.LabelEllipsis(value, bounds, style, target...) +} + // SetHoverHintOwner sets the page whose text components are painting and returns // the previous owner, to restore after a nested page. A zero owner disables // automatic hints: for components painted outside a Page, and where the page diff --git a/headless/layout.go b/headless/layout.go index 0041e87a9..84e8f3ac4 100644 --- a/headless/layout.go +++ b/headless/layout.go @@ -160,14 +160,15 @@ func lineExtent(text gfx.Text, width float32) gfx.Rect { // innermostControl is the smallest control on text's layer that holds the middle // of the line. A line that runs out of its control by more than half of itself // belongs to no control and is not found. Opaque panels count; labels of a -// control, which are the text's own extent, and backdrops do not. +// control and the pointer regions of a selectable text, which are the text's own +// extent, and backdrops do not. func innermostControl(hits []gfx.Hit, text gfx.Text, width float32) (gfx.Hit, bool) { line := lineExtent(text, width) middleY := line.Y + line.Height/2 var best gfx.Hit found := false for _, hit := range hits { - if hit.Layer != text.Layer || hit.IsLabel || hit.Backdrop || hit.MovesWindow || hit.Disabled && !hit.Block { + if hit.Layer != text.Layer || hit.IsLabel || hit.Presentational || hit.Backdrop || hit.MovesWindow || hit.Disabled && !hit.Block { continue } bounds := hit.Bounds diff --git a/headless/session.go b/headless/session.go index c4326d824..cb4cbe90e 100644 --- a/headless/session.go +++ b/headless/session.go @@ -407,7 +407,7 @@ func (session *Session) CheckStrict() error { ids := map[gfx.ID]bool{} labels := map[string]bool{} for _, hit := range hits { - if hit.ID.IsZero() || hit.IsLabel || hit.Backdrop || hit.Block { + if hit.ID.IsZero() || hit.IsLabel || hit.Presentational || hit.Backdrop || hit.Block { continue } if ids[hit.ID] { diff --git a/internal/bidi/bidi.go b/internal/bidi/bidi.go index ec23a721d..e521a096b 100644 --- a/internal/bidi/bidi.go +++ b/internal/bidi/bidi.go @@ -96,8 +96,7 @@ func NeedsBidi(text string) bool { i += 3 // U+3000..U+AFFF likewise default: r, w := utf8.DecodeRuneInString(text[i:]) - switch uniprops.Bidi(r) { - case cR, cAL, cAN, cLRE, cLRO, cRLE, cRLO, cPDF, cLRI, cRLI, cFSI, cPDI: + if NeedsBidiRune(r) { return true } i += w @@ -106,6 +105,20 @@ func NeedsBidi(text string) bool { return false } +// NeedsBidiRune reports whether r is one of the characters NeedsBidi looks for: +// text holding none of them needs no bidirectional processing. Text kept in +// pieces counts them as it changes instead of scanning for them. +func NeedsBidiRune(r rune) bool { + if r < 0x0580 || r >= 0x3000 && r < 0xB000 { + return false // see NeedsBidi: no relevant class below U+0580 or in U+3000..U+AFFF + } + switch uniprops.Bidi(r) { + case cR, cAL, cAN, cLRE, cLRO, cRLE, cRLO, cPDF, cLRI, cRLI, cFSI, cPDI: + return true + } + return false +} + // Mirrored returns the character whose glyph is the mirror image of r (rule L4), or r // itself. Apply it to characters at odd levels. func Mirrored(r rune) rune { return uniprops.Mirror(r) } diff --git a/internal/bidi/bidi_test.go b/internal/bidi/bidi_test.go index fcabcff51..408c15797 100644 --- a/internal/bidi/bidi_test.go +++ b/internal/bidi/bidi_test.go @@ -8,6 +8,8 @@ import ( "strings" "testing" "unicode/utf8" + + "github.com/vivaui/viva/internal/uniprops" ) type conformCase struct { @@ -223,6 +225,24 @@ func TestNeedsBidiAgrees(t *testing.T) { } } +// NeedsBidiRune skips whole ranges without a table lookup; every character it +// answers must agree with its bidi class, and a string of it with NeedsBidi. +func TestNeedsBidiRuneMatchesTheClasses(t *testing.T) { + for r := rune(0); r <= utf8.MaxRune; r++ { + want := false + switch uniprops.Bidi(r) { + case cR, cAL, cAN, cLRE, cLRO, cRLE, cRLO, cPDF, cLRI, cRLI, cFSI, cPDI: + want = true + } + if got := NeedsBidiRune(r); got != want { + t.Fatalf("NeedsBidiRune(%U) = %v, want %v", r, got, want) + } + if utf8.ValidRune(r) && NeedsBidi(string(r)) != want { + t.Fatalf("NeedsBidi(%U) = %v, want %v", r, !want, want) + } + } +} + func TestLineL1(t *testing.T) { var r Resolver text := "אב abc " diff --git a/internal/componentdemo/autocomplete.go b/internal/componentdemo/autocomplete.go new file mode 100644 index 000000000..25b25cf81 --- /dev/null +++ b/internal/componentdemo/autocomplete.go @@ -0,0 +1,67 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/autocomplete" +) + +var autocompleteComponent = Component{ + ID: "autocomplete", Title: "Autocomplete", Category: "Forms", Summary: "自动补全:输入时提示包含所输文字的候选,值仍是自由文本。", + Source: "ui/autocomplete/autocomplete.go", paint: (*State).paintAutocomplete, initialize: (*State).initializeAutocomplete, + editable: func(string) (editableField, bool) { + return editableField{ID: autocompleteField, Initial: ""}, true + }, + Examples: []Example{ + {ID: "default", Title: "候选与自由输入", Description: "上下键移动,回车或 Tab 选中,Esc 关闭;没有高亮候选时回车留给页面,输入候选之外的文字也会保留。与 Combobox 不同,值不限于候选。", Snippet: `m.host = autocomplete.New() +m.host.View(c, &m.hostField, "Host", "Hostname", autocomplete.Spec{Options: m.known}) +if option, ok := m.host.Chosen(); ok { + // the field already holds option +}`, PageSnippet: `m.host = autocomplete.New() +m.host.View(c, &m.hostField, "Host", "Hostname", autocomplete.Spec{Options: m.known}) +if option, ok := m.host.Chosen(); ok { + // the field already holds option +}`, PageSnippetZh: `m.host = autocomplete.New() +m.host.View(c, &m.hostField, "Host", "Hostname", autocomplete.Spec{Options: m.known}) +if option, ok := m.host.Chosen(); ok { + // 输入框里已经是 option +}`}, + }, +} + +var ( + autocompleteUI = tree.Feature("autocomplete") + autocompleteField = tree.ID(autocompleteUI, "field") +) + +var autocompleteOptions = []string{"build-01", "build-02", "db-primary", "db-replica", "staging", "bastion"} + +type autocompleteDemo struct { + a *autocomplete.Autocomplete + field ui.Field + bound bool +} + +var autocompleteDemos = map[*State]*autocompleteDemo{} + +func autocompleteDemoFor(state *State) *autocompleteDemo { + if demo := autocompleteDemos[state]; demo != nil { + return demo + } + demo := &autocompleteDemo{a: autocomplete.New().FieldID(autocompleteField)} + autocompleteDemos[state] = demo + return demo +} + +func (state *State) initializeAutocomplete() { autocompleteDemoFor(state) } + +func (state *State) paintAutocomplete(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := autocompleteDemoFor(state) + if state.editing && state.editor != nil && !demo.bound { + demo.bound = true + demo.field.Bind(state.editor) + } + state.drawPage(canvas, theme, size, 360, state.Text("Autocomplete · 自动补全", "Autocomplete"), func(c ui.C) { + demo.a.View(c, &demo.field, state.Text("主机", "Host"), state.Text("主机名", "Hostname"), autocomplete.Spec{Options: autocompleteOptions}).FillWidth() + }) +} diff --git a/internal/componentdemo/catalog_d.go b/internal/componentdemo/catalog_d.go index d804d5ed0..38fcc80af 100644 --- a/internal/componentdemo/catalog_d.go +++ b/internal/componentdemo/catalog_d.go @@ -27,4 +27,9 @@ var groupDComponents = []Component{ imagePreviewComponent, mentionsComponent, tourComponent, + overflowListComponent, + statisticComponent, + inputTagComponent, + autocompleteComponent, + indicatorComponent, } diff --git a/internal/componentdemo/indicator.go b/internal/componentdemo/indicator.go new file mode 100644 index 000000000..4fdef7dc1 --- /dev/null +++ b/internal/componentdemo/indicator.go @@ -0,0 +1,59 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/indicator" +) + +var indicatorComponent = Component{ + ID: "indicator", Title: "Indicator", Category: "Data Display", Summary: "角标:贴在控件右上角的数字或小圆点,如未读数。", + Source: "ui/indicator/indicator.go", paint: (*State).paintIndicator, + Examples: []Example{ + {ID: "default", Title: "数字与圆点", Description: "Count 超过 Max 显示“Max+”,为 0 时不显示(ShowZero 除外);Dot 改用小圆点。角标不占位,加上它控件不会移动。", Snippet: `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread, Max: 99}, func() { + ui.Button(c, "Inbox").Icon(m.inboxIcon).IconOnly().Ghost() +})`, PageSnippet: `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread, Max: 99}, func() { + ui.Button(c, "Inbox").Icon(m.inboxIcon).IconOnly().Ghost() +})`, PageSnippetZh: `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread, Max: 99}, func() { + ui.Button(c, "Inbox").Icon(m.inboxIcon).IconOnly().Ghost() +})`}, + }, +} + +// indicatorDemo keeps the closures that declare the marked buttons, made once, so a +// warm paint allocates nothing. +type indicatorDemo struct { + c ui.C + state *State + kids [4]func() + row func() +} + +var indicatorDemos = map[*State]*indicatorDemo{} + +func indicatorDemoFor(state *State) *indicatorDemo { + if demo := indicatorDemos[state]; demo != nil { + return demo + } + demo := &indicatorDemo{state: state} + for i, words := range [4][2]string{{"消息", "Messages"}, {"通知", "Alerts"}, {"更新", "Updates"}, {"完成", "Done"}} { + demo.kids[i] = func() { ui.Button(demo.c, state.Text(words[0], words[1])).Outline() } + } + demo.row = func() { + c := demo.c + indicator.View(c, state.Text("消息", "Messages"), indicator.Spec{Count: 5}, demo.kids[0]) + indicator.View(c, state.Text("通知", "Alerts"), indicator.Spec{Count: 128}, demo.kids[1]) + indicator.View(c, state.Text("更新", "Updates"), indicator.Spec{Count: 1, Dot: true}, demo.kids[2]) + indicator.View(c, state.Text("完成", "Done"), indicator.Spec{Count: 3, Status: ui.StatusSuccess}, demo.kids[3]) + } + indicatorDemos[state] = demo + return demo +} + +func (state *State) paintIndicator(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := indicatorDemoFor(state) + state.drawPage(canvas, theme, size, 420, state.Text("Indicator · 角标", "Indicator"), func(c ui.C) { + demo.c = c + ui.Row(c).Gap(32).Pad(8).Children(demo.row) + }) +} diff --git a/internal/componentdemo/input_tag.go b/internal/componentdemo/input_tag.go new file mode 100644 index 000000000..6d3ef2388 --- /dev/null +++ b/internal/componentdemo/input_tag.go @@ -0,0 +1,84 @@ +package componentdemo + +import ( + "slices" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputtag" +) + +var inputTagComponent = Component{ + ID: "input-tag", Title: "Input Tag", Category: "Forms", Summary: "标签输入:回车或逗号添加标签,空输入框按退格删除最后一个。", + Source: "ui/inputtag/inputtag.go", paint: (*State).paintInputTag, initialize: (*State).initializeInputTag, + editable: func(string) (editableField, bool) { + return editableField{ID: inputTagField, Initial: ""}, true + }, + Examples: []Example{ + {ID: "default", Title: "输入多个值", Description: "控件只报告添加与删除,标签列表由页面持有;重复、空白与超出上限的值被拒绝并让输入框显示无效外观。", Snippet: `m.hosts = inputtag.New() +m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{Placeholder: "Add a host"}).FillWidth() +if value, ok := m.hosts.Added(); ok { + m.allowed = append(m.allowed, value) +} +if i, ok := m.hosts.Removed(); ok { + m.allowed = slices.Delete(m.allowed, i, i+1) +}`, PageSnippet: `m.hosts = inputtag.New() +m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{Placeholder: "Add a host"}).FillWidth() +if value, ok := m.hosts.Added(); ok { + m.allowed = append(m.allowed, value) +} +if i, ok := m.hosts.Removed(); ok { + m.allowed = slices.Delete(m.allowed, i, i+1) +}`, PageSnippetZh: `m.hosts = inputtag.New() +m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{Placeholder: "Add a host"}).FillWidth() +if value, ok := m.hosts.Added(); ok { + m.allowed = append(m.allowed, value) +} +if i, ok := m.hosts.Removed(); ok { + m.allowed = slices.Delete(m.allowed, i, i+1) +}`}, + }, +} + +var ( + inputTagUI = tree.Feature("input-tag") + inputTagField = tree.ID(inputTagUI, "field") +) + +type inputTagDemo struct { + t *inputtag.InputTag + tags []string + bound bool +} + +var inputTagDemos = map[*State]*inputTagDemo{} + +func inputTagDemoFor(state *State) *inputTagDemo { + if demo := inputTagDemos[state]; demo != nil { + return demo + } + demo := &inputTagDemo{t: inputtag.New().FieldID(inputTagField), tags: []string{"build-01", "db-primary"}} + inputTagDemos[state] = demo + return demo +} + +func (state *State) initializeInputTag() { inputTagDemoFor(state) } + +func (state *State) paintInputTag(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := inputTagDemoFor(state) + if state.editing && state.editor != nil && !demo.bound { + demo.bound = true + demo.t.Field().Bind(state.editor) + } + state.drawPage(canvas, theme, size, 440, state.Text("Input Tag · 标签输入", "Input Tag"), func(c ui.C) { + demo.t.View(c, state.Text("允许的主机", "Allowed hosts"), demo.tags, inputtag.Spec{ + Placeholder: state.Text("添加主机", "Add a host"), MaxTags: 6, RemoveLabel: state.Text("移除", "Remove"), + }).FillWidth() + if value, ok := demo.t.Added(); ok { + demo.tags = append(demo.tags, value) + } + if i, ok := demo.t.Removed(); ok { + demo.tags = slices.Delete(demo.tags, i, i+1) + } + }) +} diff --git a/internal/componentdemo/overflow_list.go b/internal/componentdemo/overflow_list.go new file mode 100644 index 000000000..f6caf3842 --- /dev/null +++ b/internal/componentdemo/overflow_list.go @@ -0,0 +1,60 @@ +package componentdemo + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/overflowlist" +) + +var overflowListComponent = Component{ + ID: "overflow-list", Title: "Overflow List", Category: "Navigation", Summary: "折叠列表:工具栏放不下时,末尾的操作自动收进「更多」菜单。", + Source: "ui/overflowlist/overflowlist.go", paint: (*State).paintOverflowList, + Examples: []Example{ + {ID: "default", Title: "随宽度折叠", Description: "同一组操作放在三种宽度里:放得下的留在行内,放不下的从末尾起进「更多」菜单,禁用状态保持;Min 保证至少留几个。", Snippet: `m.tools = overflowlist.New() +m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth() +if i, ok := m.tools.Clicked(); ok { + m.run(m.actions[i]) +}`, PageSnippet: `m.tools = overflowlist.New() +m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth() +if i, ok := m.tools.Clicked(); ok { + m.run(m.actions[i]) +}`, PageSnippetZh: `m.tools = overflowlist.New() +m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth() +if i, ok := m.tools.Clicked(); ok { + m.run(m.actions[i]) +}`}, + }, +} + +type overflowListDemo struct { + rows [3]*overflowlist.OverflowList + items []overflowlist.Item +} + +var overflowListDemos = map[*State]*overflowListDemo{} + +func overflowListDemoFor(state *State) *overflowListDemo { + if demo := overflowListDemos[state]; demo != nil { + return demo + } + icon := gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(12, 5), gfx.LineTo(12, 19), gfx.MoveTo(5, 12), gfx.LineTo(19, 12), + }} + demo := &overflowListDemo{rows: [3]*overflowlist.OverflowList{overflowlist.New(), overflowlist.New(), overflowlist.New()}} + for _, name := range []string{"Upload", "New file", "New folder", "Refresh", "Follow", "Download", "Delete"} { + demo.items = append(demo.items, overflowlist.Item{Label: name, Icon: icon, Disabled: name == "Delete"}) + } + overflowListDemos[state] = demo + return demo +} + +func (state *State) paintOverflowList(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := overflowListDemoFor(state) + state.drawPage(canvas, theme, size, 440, state.Text("Overflow List · 折叠列表", "Overflow List"), func(c ui.C) { + ui.Column(c).Gap(14).Children(func() { + for i, width := range [3]float32{340, 220, 130} { + demo.rows[i].View(c.KeyInt(i), state.Text("操作", "Actions"), overflowlist.Spec{Items: demo.items, MoreLabel: state.Text("更多", "More")}).Width(width) + } + }) + }) +} diff --git a/internal/componentdemo/page_usage.go b/internal/componentdemo/page_usage.go index ca262e22a..95ee77c0a 100644 --- a/internal/componentdemo/page_usage.go +++ b/internal/componentdemo/page_usage.go @@ -26,6 +26,11 @@ var pageUsage = map[string]string{ "image-preview": `m.preview.View(c, imagepreview.Spec{Bitmap: m.bitmap, Title: "Screenshot"})`, "mentions": `m.mentions.View(c, &m.message, "Message", "", mentions.Spec{Options: m.people}).FillWidth()`, "tour": `m.tour.View(c, tour.Spec{Steps: m.steps})`, + "statistic": `m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true})`, + "input-tag": `m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{}).FillWidth()`, + "autocomplete": `m.host.View(c, &m.hostField, "Host", "", autocomplete.Spec{Options: m.known})`, + "indicator": `indicator.View(c, "Inbox", indicator.Spec{Count: m.unread}, func() { ui.Button(c, "Inbox") })`, + "overflow-list": `m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth()`, "upload": `m.upload.View(c, "Attachments", upload.Spec{Items: m.files, Multiple: true})`, "toggle-group": `m.toggleGroup.View(c, "Text alignment")`, "empty": `empty.View(c, empty.Spec{Title: "No projects yet"}, nil).Fill()`, diff --git a/internal/componentdemo/statistic.go b/internal/componentdemo/statistic.go new file mode 100644 index 000000000..e80966add --- /dev/null +++ b/internal/componentdemo/statistic.go @@ -0,0 +1,48 @@ +package componentdemo + +import ( + "math" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/statistic" +) + +var statisticComponent = Component{ + ID: "statistic", Title: "Statistic", Category: "Data Display", Summary: "统计数值:标题、大号数字,可设小数位、千分位、前后缀与状态色。", + Source: "ui/statistic/statistic.go", paint: (*State).paintStatistic, + Examples: []Example{ + {ID: "default", Title: "数值读数", Description: "只显示数字本身;Precision 定小数位,Group 加千分位,Status 着状态色,NaN 与无穷显示为破折号。", Snippet: `m.sessions = statistic.New() +m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true}) +m.latency.View(c, statistic.Spec{Title: "Latency", Value: m.ms, Precision: 1, Suffix: "ms"})`, PageSnippet: `m.sessions = statistic.New() +m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true}) +m.latency.View(c, statistic.Spec{Title: "Latency", Value: m.ms, Precision: 1, Suffix: "ms"})`, PageSnippetZh: `m.sessions = statistic.New() +m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true}) +m.latency.View(c, statistic.Spec{Title: "Latency", Value: m.ms, Precision: 1, Suffix: "ms"})`}, + }, +} + +type statisticDemo struct{ sessions, latency, errors, missing *statistic.Statistic } + +var statisticDemos = map[*State]*statisticDemo{} + +func statisticDemoFor(state *State) *statisticDemo { + if demo := statisticDemos[state]; demo != nil { + return demo + } + demo := &statisticDemo{statistic.New(), statistic.New(), statistic.New(), statistic.New()} + statisticDemos[state] = demo + return demo +} + +func (state *State) paintStatistic(canvas *gfx.Canvas, theme gfx.Theme, size gfx.Size) { + demo := statisticDemoFor(state) + state.drawPage(canvas, theme, size, 520, state.Text("Statistic · 统计数值", "Statistic"), func(c ui.C) { + ui.Row(c).Gap(40).Children(func() { + demo.sessions.View(c, statistic.Spec{Title: state.Text("活跃会话", "Active sessions"), Value: 12840, Group: true}) + demo.latency.View(c, statistic.Spec{Title: state.Text("延迟", "Latency"), Value: 23.46, Precision: 1, Suffix: " ms", Status: ui.StatusSuccess}) + demo.errors.View(c, statistic.Spec{Title: state.Text("错误率", "Error rate"), Value: 4.2, Precision: 1, Suffix: "%", Status: ui.StatusDanger}) + demo.missing.View(c, statistic.Spec{Title: state.Text("无数据", "No data"), Value: math.NaN()}) + }) + }) +} diff --git a/internal/dbusmenu/dbusmenu.go b/internal/dbusmenu/dbusmenu.go index dcf551f64..689e4e6be 100644 --- a/internal/dbusmenu/dbusmenu.go +++ b/internal/dbusmenu/dbusmenu.go @@ -183,6 +183,16 @@ func (object *Object) refresh() change { return difference } +// Refresh rebuilds a menu after an application update and returns the +// signals needed by hosts that keep a layout between opens. +func (object *Object) Refresh() Result { + change := object.refresh() + if change.layout { + return Result{LayoutUpdated: object.revision} + } + return Result{ItemsUpdated: change.items} +} + // writeItemsUpdated writes the body of ItemsPropertiesUpdated for the entries // these ids name: every property of each as it is now, and no removals. func (object *Object) writeItemsUpdated(e *dbus.Encoder, byWire map[int32]int, entries []platform.MenuEntry, ids []int32) { diff --git a/internal/dbusmenu/dbusmenu_test.go b/internal/dbusmenu/dbusmenu_test.go index 19e2f3191..0fbc8a46b 100644 --- a/internal/dbusmenu/dbusmenu_test.go +++ b/internal/dbusmenu/dbusmenu_test.go @@ -766,3 +766,22 @@ func TestAReadThatRebuildsAChangedMenuAnnouncesIt(t *testing.T) { t.Fatalf("the answering read announced revision %d", again.LayoutUpdated) } } + +func TestRefreshPublishesChangedMenuWithoutWaitingForAHostRequest(t *testing.T) { + var chosen []string + sessions := []string{"alpha"} + object := newSessionMenu(&chosen, &sessions) + layoutIDs(t, object) + sessions = append(sessions, "beta") + update := object.Refresh() + if update.LayoutUpdated == 0 { + t.Fatal("a new entry must invalidate the host's menu") + } + layout := object.Call(layoutCall(0, -1)) + if revision := dbus.NewDecoder(succeeded(t, layout)).Uint32(); revision != update.LayoutUpdated { + t.Fatalf("layout revision %d, announced %d", revision, update.LayoutUpdated) + } + if update := object.Refresh(); update.LayoutUpdated != 0 || len(update.ItemsUpdated) != 0 { + t.Fatal("an unchanged menu must not send another signal") + } +} diff --git a/internal/gallery/gallery_drive_test.go b/internal/gallery/gallery_drive_test.go index 2eded0c9a..94c224ac2 100644 --- a/internal/gallery/gallery_drive_test.go +++ b/internal/gallery/gallery_drive_test.go @@ -408,7 +408,7 @@ func TestEveryComponentPageSurvivesBeingOperated(t *testing.T) { // through the platform text service. The rest of the text-entry family is a // fixed snapshot; this list failing means one of them stopped (or started) // being editable and the gallery page should say so. -var editableComponents = []string{"code-diff", "code-editor", "code-merge", "field", "form", "input", "input-group", "input-number", "input-otp", "mentions", "pagination", "textarea"} +var editableComponents = []string{"code-diff", "code-editor", "code-merge", "field", "form", "input", "input-group", "input-number", "input-otp", "mentions", "autocomplete", "input-tag", "pagination", "textarea"} func editableHits(driver *app.Driver) []gfx.Hit { var fields []gfx.Hit diff --git a/internal/grapheme/grapheme.go b/internal/grapheme/grapheme.go index 31683b968..9ed190988 100644 --- a/internal/grapheme/grapheme.go +++ b/internal/grapheme/grapheme.go @@ -47,19 +47,23 @@ func propOf(r rune) prop { return prop{gb: gb, incb: incb, pict: pict} } -// text abstracts a string or a rune slice; at and before return the rune -// starting at or ending at an index and its width. -type text interface { - size() int - at(i int) (rune, int) - before(i int) (rune, int) +// Source is text the rules read a rune at a time: a string, a rune slice, or +// text held in pieces that NextIn and PrevIn read in place. Offsets are whatever +// the source counts (bytes, runes) from 0 to Len. At is the rune starting at +// offset i and its width, Before the rune ending at i; a rune that is not a +// scalar value, such as a byte that is not UTF-8 reported as -1, is a cluster of +// its own and behaves like a Control character. +type Source interface { + Len() int + At(i int) (rune, int) + Before(i int) (rune, int) } type strText string -func (s strText) size() int { return len(s) } +func (s strText) Len() int { return len(s) } -func (s strText) at(i int) (rune, int) { +func (s strText) At(i int) (rune, int) { if c := s[i]; c < utf8.RuneSelf { return rune(c), 1 } @@ -70,7 +74,7 @@ func (s strText) at(i int) (rune, int) { return r, n } -func (s strText) before(i int) (rune, int) { +func (s strText) Before(i int) (rune, int) { if c := s[i-1]; c < utf8.RuneSelf { return rune(c), 1 } @@ -83,11 +87,11 @@ func (s strText) before(i int) (rune, int) { type runeText []rune -func (s runeText) size() int { return len(s) } +func (s runeText) Len() int { return len(s) } -func (s runeText) at(i int) (rune, int) { return s[i], 1 } +func (s runeText) At(i int) (rune, int) { return s[i], 1 } -func (s runeText) before(i int) (rune, int) { return s[i-1], 1 } +func (s runeText) Before(i int) (rune, int) { return s[i-1], 1 } // Context states of the forward scan. const ( @@ -177,15 +181,15 @@ func (s *scan) joins(p prop) bool { return false } -func next[T text](t T, from int) int { - n := t.size() +func next[T Source](t T, from int) int { + n := t.Len() if from >= n { return n } if from < 0 { from = 0 } - r, w := t.at(from) + r, w := t.At(from) i := from + w if i >= n { return n @@ -193,7 +197,7 @@ func next[T text](t T, from int) int { var s scan s.start(propOf(r)) for i < n { - r, w = t.at(i) + r, w = t.At(i) p := propOf(r) if !s.joins(p) { return i @@ -206,9 +210,9 @@ func next[T text](t T, from int) int { // breakBefore reports whether there is a boundary at i, 0 < i < size, which // must be on a character boundary; it reads only what precedes and follows i. -func breakBefore[T text](t T, i int) bool { - ar, aw := t.before(i) - br, _ := t.at(i) +func breakBefore[T Source](t T, i int) bool { + ar, aw := t.Before(i) + br, _ := t.At(i) a, b := propOf(ar), propOf(br) var s scan // Reconstruct the context the forward scan would hold after a. @@ -217,7 +221,7 @@ func breakBefore[T text](t T, i int) bool { case a.gb == uniprops.GBRegionalIndicator && b.gb == uniprops.GBRegionalIndicator: s.ri = 1 for j := i - aw; j > 0; { - r, w := t.before(j) + r, w := t.Before(j) if propOf(r).gb != uniprops.GBRegionalIndicator { break } @@ -227,7 +231,7 @@ func breakBefore[T text](t T, i int) bool { case a.gb == uniprops.GBZWJ && b.pict: s.pict = pictNone for j := i - aw; j > 0; { - r, w := t.before(j) + r, w := t.Before(j) q := propOf(r) if q.pict { s.pict = pictZWJ @@ -243,7 +247,7 @@ func breakBefore[T text](t T, i int) bool { j := i - aw if a.incb != uniprops.InCBConsonant { for j > 0 { - r, w := t.before(j) + r, w := t.Before(j) q := propOf(r) if q.incb == uniprops.InCBLinker { linked = true @@ -260,28 +264,28 @@ func breakBefore[T text](t T, i int) bool { return !s.joins(b) } -func boundary[T text](t T, i int) bool { - n := t.size() +func boundary[T Source](t T, i int) bool { + n := t.Len() if i <= 0 || i >= n { return i == 0 || i == n } return breakBefore(t, i) } -func prev[T text](t T, end int) int { - n := t.size() +func prev[T Source](t T, end int) int { + n := t.Len() if end > n { end = n } if end <= 0 { return 0 } - _, w := t.before(end) + _, w := t.Before(end) for i := end - w; i > 0; i -= w { if breakBefore(t, i) { return i } - _, w = t.before(i) + _, w = t.Before(i) } return 0 } @@ -344,5 +348,13 @@ func NextRunes(r []rune, from int) int { // PrevRunes is Prev for a rune slice. func PrevRunes(r []rune, end int) int { return prev(runeText(r), end) } +// NextIn is Next for a Source, for text that is not one string or rune slice. +// It reads only the runes the rules need around from, so a source held in +// pieces is read where it is, with every rune of context the rules ask for. +func NextIn[S Source](s S, from int) int { return next(s, from) } + +// PrevIn is Prev for a Source (see NextIn). +func PrevIn[S Source](s S, end int) int { return prev(s, end) } + // BoundaryRunes is Boundary for a rune slice. func BoundaryRunes(r []rune, i int) bool { return boundary(runeText(r), i) } diff --git a/internal/platform/contract.go b/internal/platform/contract.go index f5b451655..6004a6987 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -292,6 +292,9 @@ var ErrFullscreenUnsupported = errors.New("platform: fullscreen is unsupported") // above others. var ErrAlwaysOnTopUnsupported = errors.New("platform: always-on-top is unsupported") +// ErrWindowDecorationUnsupported means the host cannot change native decorations. +var ErrWindowDecorationUnsupported = errors.New("platform: live window decorations are unsupported") + // ErrWindowSizeUnsupported means this window kind cannot be resized by the // application. var ErrWindowSizeUnsupported = errors.New("platform: programmatic window size is unsupported") @@ -311,6 +314,11 @@ type StatusItem interface { SetIcon(StatusIcon) error // SetTooltip replaces the text shown while the pointer rests on the icon. SetTooltip(string) + // SetHover observes native status item entry and exit. A nil handler + // restores normal hover behavior. Unsupported hosts return false. + SetHover(func(StatusHover)) bool + // RefreshMenu publishes changed menu entries to a host that caches them. + RefreshMenu() // Remove takes the icon away. It is idempotent and thread-safe. Remove() } @@ -352,6 +360,12 @@ type StatusClick struct { PanelDismissed bool } +// StatusHover is a native pointer transition at a status item. +type StatusHover struct { + Anchor ScreenRect + Entered bool +} + // StatusItemConfig describes a status item. OnClick and Menu run on the native // event-loop thread. With a Menu the system shows it for a press of the item. // OnClick then runs only for a press the system does not turn into the menu: a diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index c1badb1ae..e948c923b 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -570,6 +570,10 @@ func vivaCloseRequested(handle C.uintptr_t, view unsafe.Pointer) { func vivaWindowClosed(handle C.uintptr_t) { state := cgo.Handle(handle).Value().(*runState) state.closed = true + if window := state.window; window != nil { + window.closed.Store(true) + window.finishDecoration(nil, fmt.Errorf("darwin: window closed before its decoration change completed")) + } if state.web != nil { state.web.closeAll() } diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 57dc234fd..9e3e6fdaa 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -408,6 +408,7 @@ int viva_application_set_fullscreen(void *window, int fullscreen); int viva_application_set_title(void *window, const char *title); int viva_application_fullscreen(void *window); int viva_application_set_always_on_top(void *window, int enabled); +int viva_application_change_decoration(void *window, int decorated); int viva_application_run(void); void viva_application_close_all(void); void viva_application_close_window(void *window); diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 0de80c57b..1d412af9e 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -3540,15 +3540,15 @@ int viva_start_file_promise_drag(intptr_t drag, const viva_drag_item *items, siz /* A frameless workspace still owns keyboard focus and the application's main * window role. A plain borderless NSWindow declines both by default. */ -@interface VivaFramelessWindow : NSWindow +@interface VivaWorkspaceWindow : NSWindow @end -@implementation VivaFramelessWindow +@implementation VivaWorkspaceWindow - (BOOL)canBecomeKeyWindow { - return YES; + return (self.styleMask & NSWindowStyleMaskTitled) == 0 || [super canBecomeKeyWindow]; } - (BOOL)canBecomeMainWindow { - return YES; + return (self.styleMask & NSWindowStyleMaskTitled) == 0 || [super canBecomeMainWindow]; } @end @@ -3620,6 +3620,10 @@ @interface VivaAppDelegate : NSObject NSMutableArray *_titlebarWatched; /* views whose frame changes re-center the traffic lights */ BOOL _fullscreenTarget; BOOL _fullscreenTransition; + BOOL _changingDecoration; + NSWindowStyleMask _decoratedStyle; + BOOL _decoratedTitlebarTransparent; + NSWindowTitleVisibility _decoratedTitleVisibility; BOOL _alwaysOnTop; BOOL _closeInterceptEnabled; BOOL _fileDropEnabled; @@ -3660,6 +3664,7 @@ - (void)confirmClose; - (void)hideWindow; - (void)showWindow; - (void)setFullscreen:(BOOL)fullscreen; +- (int)changeDecoration:(BOOL)decorated; - (void)setWindowTitle:(NSString *)title; - (void)setAlwaysOnTop:(BOOL)enabled; - (BOOL)isFullscreen; @@ -3786,13 +3791,10 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification { style |= NSWindowStyleMaskFullSizeContentView; } - Class windowClass = _windowMode == VIVA_WINDOW_PANEL ? [VivaPanel class] : [NSWindow class]; + Class windowClass = _windowMode == VIVA_WINDOW_PANEL ? [VivaPanel class] : [VivaWorkspaceWindow class]; if (_windowMode == VIVA_WINDOW_PREVIEW || _windowMode == VIVA_WINDOW_NOTIFICATION) { windowClass = [VivaPreview class]; } - if (_windowMode == VIVA_WINDOW_FRAMELESS) { - windowClass = [VivaFramelessWindow class]; - } _window = [[windowClass alloc] initWithContentRect:frame styleMask:style backing:NSBackingStoreBuffered @@ -4176,7 +4178,7 @@ - (void)screenParametersChanged:(NSNotification *)notification { * pixels. A live drag reports every intermediate position. */ - (void)reportFrameChange { if (!_frameEventsEnabled || !_running || _callbackHandle == 0 || _window == nil || - _fullscreenTransition || [self isFullscreen]) { + _changingDecoration || _fullscreenTransition || [self isFullscreen]) { return; } double frame[4]; @@ -4218,6 +4220,79 @@ - (BOOL)isFullscreen { return (_window.styleMask & NSWindowStyleMaskFullScreen) != 0; } +- (int)changeDecoration:(BOOL)decorated { + if (!_running || !_window.isVisible || _window.isMiniaturized) { + return 0; + } + if ((_windowMode != VIVA_WINDOW_TITLED && _windowMode != VIVA_WINDOW_CUSTOM_TITLEBAR) || + _fullscreenTransition || [self isFullscreen]) { + return -1; + } + if (_changingDecoration || _window.inLiveResize) { + return 0; + } + NSWindowStyleMask before = _window.styleMask; + if (((before & NSWindowStyleMaskTitled) != 0) == decorated) { + return 1; + } + NSWindowStyleMask after = decorated ? _decoratedStyle : + before & ~(NSWindowStyleMaskTitled | NSWindowStyleMaskFullSizeContentView); + if (decorated && (after & NSWindowStyleMaskTitled) == 0) { + return -1; + } + + NSRect frame = _window.frame; + NSRect content = [_window contentRectForFrameRect:frame]; + NSView *view = _window.contentView; + NSResponder *responder = [_window.firstResponder retain]; + NSInteger number = _window.windowNumber; + NSInteger level = _window.level; + BOOL key = _window.isKeyWindow; + BOOL main = _window.isMainWindow; + BOOL transparent = _window.titlebarAppearsTransparent; + NSWindowTitleVisibility title = _window.titleVisibility; + + // AppKit sends intermediate move/resize notices when rebuilding the chrome. + // The application should never persist those rectangles as its placement. + _changingDecoration = YES; + _window.styleMask = after; + if (decorated) { + _window.titlebarAppearsTransparent = _decoratedTitlebarTransparent; + _window.titleVisibility = _decoratedTitleVisibility; + if (_title != nil) _window.title = _title; + } + if (!NSEqualRects([_window contentRectForFrameRect:_window.frame], content)) { + [_window setFrame:[_window frameRectForContentRect:content] display:NO]; + } + if (_window.firstResponder != responder) [_window makeFirstResponder:responder]; + BOOL applied = _running && _window.isVisible && _window.styleMask == after && + _window.windowNumber == number && _window.level == level && + _window.contentView == view && _window.firstResponder == responder && + _window.isKeyWindow == key && _window.isMainWindow == main && + NSEqualRects([_window contentRectForFrameRect:_window.frame], content); + if (applied && !decorated) { + _decoratedStyle = before; + _decoratedTitlebarTransparent = transparent; + _decoratedTitleVisibility = title; + } else if (!applied && _running) { + _window.styleMask = before; + _window.titlebarAppearsTransparent = transparent; + _window.titleVisibility = title; + if (_title != nil) _window.title = _title; + if (_window.level != level) _window.level = level; + if (!NSEqualRects(_window.frame, frame)) [_window setFrame:frame display:NO]; + if (key && !_window.isKeyWindow) [_window makeKeyWindow]; + if (main && !_window.isMainWindow) [_window makeMainWindow]; + if (_window.firstResponder != responder) [_window makeFirstResponder:responder]; + } + if (_windowMode == VIVA_WINDOW_CUSTOM_TITLEBAR && _running) { + [self keepTrafficLightsCentered]; + } + _changingDecoration = NO; + [responder release]; + return applied ? 1 : -2; +} + - (void)setWindowTitle:(NSString *)title { [_title release]; _title = [title copy]; @@ -4481,7 +4556,7 @@ - (BOOL)contentFrame:(double *)out { * the menu bar at the top of the screen, and kept inside the visible part of the * screen the anchor is on. Without an anchor it is centered on the screen. */ - (void)placePanel { - if (_windowMode == VIVA_WINDOW_NOTIFICATION) { + if (_windowMode == VIVA_WINDOW_NOTIFICATION && !_hasAnchor) { if (_hasOrigin) { [self placeAtOrigin]; return; @@ -5023,6 +5098,11 @@ int viva_application_set_always_on_top(void *window, int enabled) { return found; } +// Only called by the Go main-queue callback. +int viva_application_change_decoration(void *window, int decorated) { + return [viva_find_window(window) changeDecoration:decorated != 0]; +} + void viva_application_show_window(void *window) { viva_post_window_event(VIVA_SHOW_EVENT, window); } diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index fe1e96450..964d7397a 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -15,6 +15,7 @@ import "C" import ( "fmt" "runtime/cgo" + "sync" "sync/atomic" "unicode/utf8" "unsafe" @@ -149,6 +150,7 @@ func (window *nativeWindow) SetAlwaysOnTop(enabled bool) error { type runState struct { application *nativeApplication + window *nativeWindow callbackHandle cgo.Handle onClosed func() waker *platform.Waker @@ -206,8 +208,33 @@ type nativeApplication struct { } type nativeWindow struct { - token unsafe.Pointer - closed atomic.Bool + token unsafe.Pointer + closed atomic.Bool + mode WindowMode + decorationMu sync.Mutex + decoration *decorationRequest +} + +type decorationRequest struct { + done func(error) +} + +func (window *nativeWindow) finishDecoration(request *decorationRequest, err error) { + window.decorationMu.Lock() + pending := window.decoration + if request != nil && pending != request { + window.decorationMu.Unlock() + return + } + window.decoration = nil + var done func(error) + if pending != nil { + done, pending.done = pending.done, nil + } + window.decorationMu.Unlock() + if done != nil { + done(err) + } } func (window *nativeWindow) Close() { @@ -483,7 +510,8 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window C.viva_web_ready_later(C.uintptr_t(state.callbackHandle)) } } - return &nativeWindow{token: token}, nil + state.window = &nativeWindow{token: token, mode: config.WindowMode} + return state.window, nil } func nativeStatusError(status C.int) error { diff --git a/internal/platform/darwin/status_item_darwin.go b/internal/platform/darwin/status_item_darwin.go index f22d0aa04..3652379c5 100644 --- a/internal/platform/darwin/status_item_darwin.go +++ b/internal/platform/darwin/status_item_darwin.go @@ -25,6 +25,7 @@ type nativeStatusItem struct { handle cgo.Handle removed atomic.Bool onClick func(platform.StatusClick) + hover func(platform.StatusHover) menu func() []platform.MenuItem currentEntries []platform.MenuEntry } @@ -85,6 +86,27 @@ func (item *nativeStatusItem) Remove() { } } +func (item *nativeStatusItem) SetHover(handler func(platform.StatusHover)) bool { + if item.removed.Load() { + return false + } + item.hover = handler + C.viva_status_item_track_hover(item.token, C.int(boolInt(handler != nil))) + return true +} + +func (item *nativeStatusItem) RefreshMenu() {} + +//export vivaStatusItemHovered +func vivaStatusItemHovered(handle C.uintptr_t, entered C.int, x, y, width, height C.float) { + item := cgo.Handle(handle).Value().(*nativeStatusItem) + if !item.removed.Load() && item.hover != nil { + item.hover(platform.StatusHover{ + Entered: entered != 0, Anchor: platform.ScreenRect{X: float32(x), Y: float32(y), Width: float32(width), Height: float32(height)}, + }) + } +} + //export vivaStatusItemClicked func vivaStatusItemClicked(handle C.uintptr_t, button C.int, x, y, width, height C.float, dismissed C.int) { item := cgo.Handle(handle).Value().(*nativeStatusItem) diff --git a/internal/platform/darwin/status_item_darwin.h b/internal/platform/darwin/status_item_darwin.h index 499ed9b7d..c978b716b 100644 --- a/internal/platform/darwin/status_item_darwin.h +++ b/internal/platform/darwin/status_item_darwin.h @@ -33,6 +33,7 @@ double viva_dock_icon_points(viva_status_icon icon); void *viva_status_item_create(const char *tooltip, viva_status_icon icon, uintptr_t callback_handle, int has_menu); int viva_status_item_set_icon(void *item, viva_status_icon icon); void viva_status_item_set_tooltip(void *item, const char *tooltip); +void viva_status_item_track_hover(void *item, int enabled); /* Replaces the entries of the item's menu. The menu is attached when the item * is created with one; NULL or a count of zero leaves it empty. Main thread * only. */ diff --git a/internal/platform/darwin/status_item_darwin.m b/internal/platform/darwin/status_item_darwin.m index eae46fb5f..ee96a10a3 100644 --- a/internal/platform/darwin/status_item_darwin.m +++ b/internal/platform/darwin/status_item_darwin.m @@ -32,6 +32,7 @@ extern void vivaStatusItemClicked( ); extern void vivaStatusItemUpdateMenu(uintptr_t callbackHandle); extern void vivaStatusItemMenuChosen(uintptr_t callbackHandle, int id); +extern void vivaStatusItemHovered(uintptr_t callbackHandle, int entered, float x, float y, float width, float height); enum { VIVA_STATUS_BUTTON_PRIMARY = 1, @@ -75,10 +76,13 @@ @interface VivaStatusItem : NSObject { NSStatusItem *_item; uintptr_t _callbackHandle; NSMenu *_menu; + NSTrackingArea *_tracking; + NSString *_tooltip; } - (instancetype)initWithTooltip:(NSString *)tooltip icon:(viva_status_icon)icon callbackHandle:(uintptr_t)callbackHandle hasMenu:(BOOL)hasMenu; - (BOOL)setIcon:(viva_status_icon)icon; - (void)setTooltip:(NSString *)tooltip; +- (void)trackHover:(BOOL)enabled; - (void)remove; - (void)setMenuEntries:(const viva_menu_entry *)entries count:(int)count; - (void)menuChosen:(NSMenuItem *)sender; @@ -99,7 +103,7 @@ - (instancetype)initWithTooltip:(NSString *)tooltip icon:(viva_status_icon)icon _callbackHandle = callbackHandle; _item = [[[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength] retain]; _item.button.image = image; - _item.button.toolTip = tooltip; + [self setTooltip:tooltip]; if (hasMenu) { _menu = [[NSMenu alloc] initWithTitle:@""]; _menu.autoenablesItems = NO; @@ -115,6 +119,7 @@ - (instancetype)initWithTooltip:(NSString *)tooltip icon:(viva_status_icon)icon - (void)dealloc { [self remove]; + [_tooltip release]; [super dealloc]; } @@ -128,10 +133,49 @@ - (BOOL)setIcon:(viva_status_icon)icon { } - (void)setTooltip:(NSString *)tooltip { - _item.button.toolTip = tooltip; + NSString *text = [tooltip copy]; + [_tooltip release]; + _tooltip = text; + if (_tracking == nil) { + _item.button.toolTip = _tooltip; + } +} + +- (void)trackHover:(BOOL)enabled { + if ((_tracking != nil) == enabled) { + return; + } + NSStatusBarButton *button = _item.button; + if (enabled) { + _tracking = [[NSTrackingArea alloc] initWithRect:NSZeroRect + options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect + owner:self userInfo:nil]; + [button addTrackingArea:_tracking]; + } else { + [button removeTrackingArea:_tracking]; + [_tracking release]; + _tracking = nil; + } + button.toolTip = enabled ? nil : _tooltip; +} + +- (void)mouseEntered:(NSEvent *)event { + if (_tracking == nil || event.trackingArea != _tracking || _callbackHandle == 0) { + return; + } + NSStatusBarButton *button = _item.button; + NSRect anchor = [button.window convertRectToScreen:[button convertRect:button.bounds toView:nil]]; + vivaStatusItemHovered(_callbackHandle, 1, anchor.origin.x, anchor.origin.y, anchor.size.width, anchor.size.height); +} + +- (void)mouseExited:(NSEvent *)event { + if (_tracking != nil && event.trackingArea == _tracking && _callbackHandle != 0) { + vivaStatusItemHovered(_callbackHandle, 0, 0, 0, 0, 0); + } } - (void)remove { + [self trackHover:NO]; if (_item != nil) { _item.menu = nil; if (_menu != nil) { @@ -288,6 +332,10 @@ void viva_status_item_set_tooltip(void *item, const char *tooltip) { } } +void viva_status_item_track_hover(void *item, int enabled) { + [(VivaStatusItem *)item trackHover:enabled != 0]; +} + /* Takes the item off the bar and forgets it. Called on the event-loop thread. */ static void viva_status_item_remove_now(void *item) { @autoreleasepool { diff --git a/internal/platform/darwin/testdata/dock_reopen.m b/internal/platform/darwin/testdata/dock_reopen.m index ce24e5dba..09dab38ce 100644 --- a/internal/platform/darwin/testdata/dock_reopen.m +++ b/internal/platform/darwin/testdata/dock_reopen.m @@ -97,7 +97,7 @@ int vivaWindowReopenRequested(uintptr_t handle, void *view) { int main(void) { @autoreleasepool { [DockTestApplication sharedApplication]; - NSWindow *frameless = [[VivaFramelessWindow alloc] + NSWindow *frameless = [[VivaWorkspaceWindow alloc] initWithContentRect:NSMakeRect(0, 0, 320, 200) styleMask:NSWindowStyleMaskBorderless backing:NSBackingStoreBuffered diff --git a/internal/platform/darwin/testdata/status_item.m b/internal/platform/darwin/testdata/status_item.m index 8d69a4521..4c34002be 100644 --- a/internal/platform/darwin/testdata/status_item.m +++ b/internal/platform/darwin/testdata/status_item.m @@ -19,6 +19,10 @@ void vivaStatusItemClicked(uintptr_t callbackHandle, int button, float x, float (void)callbackHandle; (void)button; (void)x; (void)y; (void)width; (void)height; (void)panelDismissed; } +void vivaStatusItemHovered(uintptr_t callbackHandle, int entered, float x, float y, float width, float height) { + (void)callbackHandle; (void)entered; (void)x; (void)y; (void)width; (void)height; +} + void vivaStatusItemUpdateMenu(uintptr_t callbackHandle) { (void)callbackHandle; update_menu_called++; diff --git a/internal/platform/darwin/testdata/window_decoration.m b/internal/platform/darwin/testdata/window_decoration.m new file mode 100644 index 000000000..d942aff61 --- /dev/null +++ b/internal/platform/darwin/testdata/window_decoration.m @@ -0,0 +1,137 @@ +#include "../core_text.m" +#include "../core_render.m" +#include "../native.m" +#include "../main_menu_darwin.m" +#include + +void vivaPointerEvent(uintptr_t handle, void *view, int kind, int button, int modifiers, int clickCount, double x, double y, double screenX, double screenY) {} +#include "window_test_callbacks.h" + +// CI can exercise the AppKit transition without opening a desktop window. +// The same fixture can be run with --visible to observe a key window locally. +@interface DecorationWindow : VivaWorkspaceWindow +@property BOOL reportsMapped; +@end + +@implementation DecorationWindow +- (BOOL)isVisible { return self.reportsMapped || [super isVisible]; } +@end + +static NSRect contentRect(NSWindow *window) { + return [window contentRectForFrameRect:window.frame]; +} + +static void pumpEvents(void) { + NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny + untilDate:[NSDate dateWithTimeIntervalSinceNow:0.04] inMode:NSDefaultRunLoopMode dequeue:YES]; + if (event != nil) [NSApp sendEvent:event]; + [NSApp updateWindows]; +} + +static void verify(NSWindow *window, NSInteger number, NSView *content, NSResponder *responder, + NSRect geometry, NSWindowStyleMask style, NSInteger level, BOOL key) { + assert(window.windowNumber == number); + assert(window.contentView == content && window.firstResponder == responder); + assert(NSEqualRects(contentRect(window), geometry)); + assert(window.styleMask == style && window.level == level); + assert(window.isVisible && window.isKeyWindow == key); +} + +static void check(BOOL custom, BOOL visible, NSRect area, CGFloat width, CGFloat height) { + NSWindowStyleMask style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | + NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable; + if (custom) style |= NSWindowStyleMaskFullSizeContentView; + NSRect geometry = NSMakeRect(NSMidX(area) - width / 2, NSMidY(area) - height / 2, width, height); + DecorationWindow *window = [[DecorationWindow alloc] + initWithContentRect:geometry + styleMask:style backing:NSBackingStoreBuffered defer:NO]; + window.releasedWhenClosed = NO; + NSInteger level = custom ? NSFloatingWindowLevel : NSNormalWindowLevel; + window.level = level; + window.titlebarAppearsTransparent = custom; + window.titleVisibility = custom ? NSWindowTitleHidden : NSWindowTitleVisible; + NSView *content = window.contentView; + NSTextView *editor = [[NSTextView alloc] initWithFrame:NSMakeRect(8, 8, 180, 100)]; + editor.string = @"alpha bravo"; + [editor setSelectedRange:NSMakeRange(6, 5)]; + [content addSubview:editor]; + assert([window makeFirstResponder:editor]); + + VivaAppDelegate *delegate = [VivaAppDelegate alloc]; + [delegate setValue:window forKey:@"_window"]; + [delegate setValue:@YES forKey:@"_running"]; + [delegate setValue:@(custom ? VIVA_WINDOW_CUSTOM_TITLEBAR : VIVA_WINDOW_TITLED) forKey:@"_windowMode"]; + assert([delegate changeDecoration:NO] == 0); + assert(window.styleMask == style); + + if (visible) { + [window makeKeyAndOrderFront:nil]; + [NSApp activateIgnoringOtherApps:YES]; + NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:2.0]; + do { + pumpEvents(); + } while (!window.isKeyWindow && [deadline timeIntervalSinceNow] > 0); + assert(window.isKeyWindow); + } else { + window.reportsMapped = YES; + } + NSInteger number = window.windowNumber; + geometry = contentRect(window); + // The operation may legitimately refuse if AppKit constrains the new frame + // to the display. Keep the success fixture inside the available screen. + assert(NSContainsRect(area, window.frame)); + [delegate setValue:@YES forKey:@"_fullscreenTransition"]; + assert([delegate changeDecoration:NO] == -1); + verify(window, number, content, editor, geometry, style, level, visible); + [delegate setValue:@NO forKey:@"_fullscreenTransition"]; + int result = [delegate changeDecoration:NO]; + if (result != 1) { + fprintf(stderr, "could not remove chrome: result=%d custom=%d frame=%s client=%s screen=%s\n", + result, custom, NSStringFromRect(window.frame).UTF8String, + NSStringFromRect(geometry).UTF8String, NSStringFromRect(area).UTF8String); + } + assert(result == 1); + if (visible) pumpEvents(); + verify(window, number, content, editor, geometry, + style & ~(NSWindowStyleMaskTitled | NSWindowStyleMaskFullSizeContentView), level, visible); + assert(NSEqualRanges(editor.selectedRange, NSMakeRange(6, 5))); + assert([delegate changeDecoration:YES] == 1); + if (visible) pumpEvents(); + verify(window, number, content, editor, geometry, style, level, visible); + assert(window.titlebarAppearsTransparent == custom); + assert(window.titleVisibility == (custom ? NSWindowTitleHidden : NSWindowTitleVisible)); + if (visible) { + NSEvent *event = [NSEvent keyEventWithType:NSEventTypeKeyDown location:NSZeroPoint + modifierFlags:0 timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:number + context:nil characters:@"x" charactersIgnoringModifiers:@"x" isARepeat:NO keyCode:7]; + [window sendEvent:event]; + } else { + [editor insertText:@"x" replacementRange:NSMakeRange(NSNotFound, 0)]; + } + assert([editor.string isEqualToString:@"alpha x"]); + printf("PASS %.0fx%.0f custom=%d visible=%d\n", width, height, custom, visible); + [window close]; + [editor release]; + [delegate release]; + [window release]; +} + +int main(int argc, const char *argv[]) { + @autoreleasepool { + [NSApplication sharedApplication]; + BOOL visible = argc == 2 && strcmp(argv[1], "--visible") == 0; + [NSApp setActivationPolicy:visible ? NSApplicationActivationPolicyRegular : NSApplicationActivationPolicyProhibited]; + if (visible) [NSApp finishLaunching]; + NSScreen *screen = NSScreen.mainScreen ?: NSScreen.screens.firstObject; + assert(screen != nil); + NSRect area = screen.visibleFrame; + // Leave space for the titlebar even on smaller virtual displays. + CGFloat width = MIN(NSWidth(area) - 64, 1280); + CGFloat height = MIN(NSHeight(area) - 64, 800); + check(NO, visible, area, MIN(width, 640), MIN(height, 400)); + check(YES, visible, area, MIN(width, 640), MIN(height, 400)); + check(NO, visible, area, width, height); + check(YES, visible, area, width, height); + } + return 0; +} diff --git a/internal/platform/darwin/window_decoration_darwin.go b/internal/platform/darwin/window_decoration_darwin.go new file mode 100644 index 000000000..1e715ac07 --- /dev/null +++ b/internal/platform/darwin/window_decoration_darwin.go @@ -0,0 +1,56 @@ +//go:build !ios + +package darwin + +/* +#include "native.h" +*/ +import "C" + +import ( + "fmt" + + "github.com/vivaui/viva/internal/platform" +) + +func (window *nativeWindow) SetDecorated(decorated bool, done func(error)) error { + if window == nil { + return fmt.Errorf("darwin: window is closed") + } + if done == nil { + return fmt.Errorf("darwin: window decoration completion callback is required") + } + if window.mode != WindowTitled && window.mode != WindowCustomTitlebar { + return platform.ErrWindowDecorationUnsupported + } + window.decorationMu.Lock() + if window.closed.Load() { + window.decorationMu.Unlock() + return fmt.Errorf("darwin: window is closed") + } + if window.decoration != nil { + window.decorationMu.Unlock() + return fmt.Errorf("darwin: a decoration change is already pending") + } + request := &decorationRequest{done: done} + window.decoration = request + window.decorationMu.Unlock() + Post(func() { + if window.closed.Load() { + window.finishDecoration(request, fmt.Errorf("darwin: window is closed")) + return + } + var err error + switch C.viva_application_change_decoration(window.token, C.int(boolInt(decorated))) { + case 1: + case -1: + err = platform.ErrWindowDecorationUnsupported + case -2: + err = fmt.Errorf("darwin: AppKit did not preserve the window while changing its decorations") + default: + err = fmt.Errorf("darwin: window is not available for a decoration change") + } + window.finishDecoration(request, err) + }) + return nil +} diff --git a/internal/platform/darwin/window_decoration_darwin_test.go b/internal/platform/darwin/window_decoration_darwin_test.go new file mode 100644 index 000000000..10e4b4aa2 --- /dev/null +++ b/internal/platform/darwin/window_decoration_darwin_test.go @@ -0,0 +1,47 @@ +//go:build !ios + +package darwin + +import ( + "os/exec" + "path/filepath" + "testing" +) + +func TestWindowDecorationRequestsCompleteOnceWhenClosing(t *testing.T) { + seen := postedDrainResult(t, func() []int { + window := &nativeWindow{mode: WindowTitled} + var seen []int + if err := window.SetDecorated(false, func(err error) { + if err != nil { + seen = append(seen, 1) + } else { + seen = append(seen, -1) + } + }); err != nil || len(seen) != 0 { + return nil + } + if err := window.SetDecorated(true, func(error) { seen = append(seen, -2) }); err == nil { + return nil + } + window.Close() + vivaApplicationDrain() + return seen + }) + if len(seen) != 1 || seen[0] != 1 { + t.Fatalf("completion sequence = %v, want one error for the accepted request", seen) + } +} + +func TestNativeWindowDecorationPreservesContent(t *testing.T) { + executable := filepath.Join(t.TempDir(), "window-decoration") + command := exec.Command("xcrun", "clang", "-fno-objc-arc", "-Werror", + "-Wno-deprecated-declarations", "testdata/window_decoration.m", "-o", executable, + "-framework", "Cocoa", "-framework", "CoreText", "-framework", "Metal", "-framework", "QuartzCore") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native window decoration test: %v\n%s", err, output) + } + if output, err := exec.Command(executable).CombinedOutput(); err != nil { + t.Fatalf("native window decoration: %v\n%s", err, output) + } +} diff --git a/internal/platform/linux/gtk_decoration_linux.go b/internal/platform/linux/gtk_decoration_linux.go new file mode 100644 index 000000000..ffa16a6c4 --- /dev/null +++ b/internal/platform/linux/gtk_decoration_linux.go @@ -0,0 +1,240 @@ +//go:build linux && vivagtk + +package linux + +import ( + "fmt" + "sync" + + "github.com/vivaui/viva/internal/platform" +) + +type gtkDecorationState struct { + mu sync.Mutex + closed bool + pending *gtkDecorationRequest + // changing is only read and written on the GTK thread. + changing bool +} + +type gtkDecorationRequest struct { + decorated bool + done func(error) + task uintptr + source uint32 + api *xcbAPI + conn uintptr + xid uint32 + native uintptr + extents uint32 + gdkExtents uintptr + before [4]uint32 + geometry x11DecorationGeometry + focused bool + rollback bool +} + +func (w *gtkWindow) SetDecorated(decorated bool, done func(error)) error { + if w == nil || w.app == nil { + return fmt.Errorf("linux: window is closed") + } + if done == nil { + return fmt.Errorf("linux: window decoration completion callback is required") + } + if w.app.wayland || w.config.WindowMode != platform.WindowTitled { + return platform.ErrWindowDecorationUnsupported + } + state := &w.decoration + state.mu.Lock() + defer state.mu.Unlock() + if state.closed { + return fmt.Errorf("linux: window is closed") + } + if state.pending != nil { + return fmt.Errorf("linux: a decoration change is already pending") + } + r := >kDecorationRequest{decorated: decorated, done: done} + state.pending = r + w.queueDecoration(r, 0, func() { w.beginDecoration(r) }) + return nil +} + +// queueDecoration runs with the submission lock held. A tracked GLib source +// lets close discard queued work even when the last window exits the loop. +func (w *gtkWindow) queueDecoration(r *gtkDecorationRequest, delay uint32, run func()) { + r.task = w.app.tasks.add(func() { + state := &w.decoration + state.mu.Lock() + r.task, r.source = 0, 0 + pending := state.pending == r + state.mu.Unlock() + if pending { + run() + } + }) + if delay == 0 { + r.source = w.g.idleAdd(callbacks().task, r.task) + } else { + r.source = w.g.timeoutAdd(delay, callbacks().task, r.task) + } +} + +func (w *gtkWindow) beginDecoration(r *gtkDecorationRequest) { + if w.g.widgetGetMapped(w.toplevel) == 0 || w.minimized || w.maximized || w.Fullscreen() { + w.finishDecoration(r, fmt.Errorf("linux: decorations can change only on a mapped normal window")) + return + } + r.native = w.g.widgetGetWindow(w.toplevel) + var xid func(uintptr) uintptr + if r.native == 0 || !w.g.lookup(&xid, "gdk_x11_window_get_xid") { + w.finishDecoration(r, platform.ErrWindowDecorationUnsupported) + return + } + r.xid = uint32(xid(r.native)) + api, err := loadXCB() + if err != nil { + w.finishDecoration(r, err) + return + } + // A separate connection reads server state without sharing GDK's event queue. + r.api = api + r.conn = api.connect(w.g.gdkDisplayName(w.g.gdkDisplayDefault()), nil) + if r.conn == 0 || api.connectionHasError(r.conn) != 0 || r.xid == 0 { + w.finishDecoration(r, fmt.Errorf("linux: could not inspect the GTK X11 window")) + return + } + r.extents, err = api.atom(r.conn, "_NET_FRAME_EXTENTS") + if err != nil { + w.finishDecoration(r, err) + return + } + atomName := cString("_NET_FRAME_EXTENTS") + r.gdkExtents = w.g.atomIntern(&atomName[0], 0) + before, ok := r.frameExtents() + current := w.g.windowGetDecorated(w.toplevel) != 0 + if !ok || current != (before != [4]uint32{}) { + w.finishDecoration(r, fmt.Errorf("%w: the X11 window manager does not report the GTK frame", platform.ErrWindowDecorationUnsupported)) + return + } + if current == r.decorated { + w.finishDecoration(r, nil) + return + } + r.before = before + r.geometry = api.decorationGeometry(r.conn, r.xid) + r.focused = w.focused + if r.geometry.width == 0 || r.geometry.height == 0 { + w.finishDecoration(r, fmt.Errorf("linux: could not read the GTK client rectangle")) + return + } + w.decoration.changing = true + w.armDecorationDeadline(r) + w.setDecorationHint(r.decorated) + w.observeDecoration(r) +} + +func (w *gtkWindow) setDecorationHint(decorated bool) { + var hint int32 + if decorated { + hint = 1 + } + w.g.windowSetDecorated(w.toplevel, hint) +} + +func (r *gtkDecorationRequest) frameExtents() ([4]uint32, bool) { + var frame [4]uint32 + var present bool + ok := r.api.readDecorationProperty(r.conn, r.xid, r.extents, xcbAtomCardinal, frame[:], &present) + return frame, ok && present +} + +func (w *gtkWindow) pendingDecorationObservation() *gtkDecorationRequest { + if w.closed || !w.decoration.changing { + return nil + } + w.decoration.mu.Lock() + defer w.decoration.mu.Unlock() + return w.decoration.pending +} + +func (w *gtkWindow) observeDecorationEvent(property *gdkEventProperty) { + if r := w.pendingDecorationObservation(); r != nil && + (property == nil || property.Window == r.native && property.Atom == r.gdkExtents) { + w.observeDecoration(r) + } +} + +func (w *gtkWindow) observeDecoration(r *gtkDecorationRequest) bool { + w.decoration.mu.Lock() + pending := w.decoration.pending == r + w.decoration.mu.Unlock() + if !pending { + return true + } + frame, ok := r.frameExtents() + if ok && w.g.widgetGetMapped(w.toplevel) != 0 && w.g.widgetGetWindow(w.toplevel) == r.native && + r.api.decorationGeometry(r.conn, r.xid) == r.geometry { + if r.rollback && frame == r.before { + w.finishDecoration(r, fmt.Errorf("linux: decoration change was not confirmed; previous frame restored")) + return true + } + if !r.rollback && r.decorated == (frame != [4]uint32{}) && w.focused == r.focused && + !w.minimized && !w.maximized && !w.Fullscreen() { + w.finishDecoration(r, nil) + return true + } + } + return false +} + +func (w *gtkWindow) armDecorationDeadline(r *gtkDecorationRequest) { + w.decoration.mu.Lock() + defer w.decoration.mu.Unlock() + w.queueDecoration(r, uint32(decorationDeadline.Milliseconds()), func() { w.decorationTimedOut(r) }) +} + +func (w *gtkWindow) decorationTimedOut(r *gtkDecorationRequest) { + if w.observeDecoration(r) { + return + } + if r.rollback { + w.finishDecoration(r, fmt.Errorf("linux: decoration change and restoration were not confirmed")) + return + } + r.rollback = true + w.armDecorationDeadline(r) + w.setDecorationHint(!r.decorated) + w.observeDecoration(r) +} + +func (w *gtkWindow) closeDecoration() { + state := &w.decoration + state.mu.Lock() + state.closed = true + r := state.pending + state.mu.Unlock() + if r != nil { + w.finishDecoration(r, fmt.Errorf("linux: window closed before its decoration change completed")) + } +} + +func (w *gtkWindow) finishDecoration(r *gtkDecorationRequest, err error) { + state := &w.decoration + state.mu.Lock() + if state.pending != r { + state.mu.Unlock() + return + } + state.pending = nil + if r.task != 0 { + w.app.tasks.take(r.task) + w.g.sourceRemove(r.source) + r.task, r.source = 0, 0 + } + state.mu.Unlock() + state.changing = false + if r.conn != 0 { + r.api.disconnect(r.conn) + } + r.done(err) +} diff --git a/internal/platform/linux/gtk_decoration_linux_test.go b/internal/platform/linux/gtk_decoration_linux_test.go new file mode 100644 index 000000000..acd5efba3 --- /dev/null +++ b/internal/platform/linux/gtk_decoration_linux_test.go @@ -0,0 +1,278 @@ +//go:build linux && vivagtk && !android + +package linux + +import ( + "errors" + "fmt" + "os" + "os/exec" + "strconv" + "strings" + "syscall" + "testing" + "time" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +func TestGTKDecorationObservationDoesNotScheduleAPoll(t *testing.T) { + w := >kWindow{app: >kApplication{}, g: >kLibrary{}} + w.g.timeoutAdd = func(interval uint32, _, _ uintptr) uint32 { + t.Errorf("observation scheduled another timer after %d ms", interval) + return 1 + } + r := >kDecorationRequest{ + api: &xcbAPI{ + getProperty: func(uintptr, uint8, uint32, uint32, uint32, uint32, uint32) xcbPropertyCookie { + return xcbPropertyCookie{} + }, + getPropertyReply: func(uintptr, xcbPropertyCookie, *unsafe.Pointer) *xcbPropertyReply { return nil }, + }, + } + w.decoration.pending = r + w.observeDecoration(r) +} + +func TestNativeGTKDecorationRoundTrip(t *testing.T) { + if os.Getenv("VIVA_GTK_DECORATION_NATIVE") != "1" { + t.Skip("requires a private X11 session with a window manager") + } + for _, size := range [][2]int{{640, 400}, {1280, 800}} { + t.Run(fmt.Sprintf("%dx%d", size[0], size[1]), func(t *testing.T) { + var outcome error + completed := false + err := RunGTKApplication(func(application platform.Application) error { + a := application.(*gtkApplication) + above := size[0] == 1280 + control, err := a.OpenWindow(platform.Config{ + Title: "Viva GTK decoration probe", Width: size[0], Height: size[1], ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + w := control.(*gtkWindow) + aboveRequested := false + var xid func(uintptr) uintptr + if a.wayland || !a.g.lookup(&xid, "gdk_x11_window_get_xid") { + return fmt.Errorf("this test requires GTK on X11") + } + api, err := loadXCB() + if err != nil { + return err + } + connection := api.connect(nil, nil) + if connection == 0 || api.connectionHasError(connection) != 0 { + if connection != 0 { + api.disconnect(connection) + } + return fmt.Errorf("could not open the X11 test connection") + } + atom, err := api.atom(connection, "_NET_FRAME_EXTENTS") + if err != nil { + api.disconnect(connection) + return err + } + finish := func(err error) { + if !completed { + completed, outcome = true, err + api.disconnect(connection) + w.destroy() + } + } + deadline := time.Now().Add(5 * time.Second) + var observed string + var start func() + start = func() { + if time.Now().After(deadline) { + finish(fmt.Errorf("window manager did not settle: %s", observed)) + return + } + native := w.g.widgetGetWindow(w.toplevel) + if native == 0 { + a.g.timeoutAdd(20, callbacks().task, a.tasks.add(start)) + return + } + initialID := uint32(xid(native)) + var initial [4]uint32 + var present bool + frame, placed := w.Frame() + hasFrame := api.readDecorationProperty(connection, initialID, atom, xcbAtomCardinal, initial[:], &present) && present && initial != [4]uint32{} + observed = fmt.Sprintf("placed=%t focused=%t extents=%v wantAbove=%t", placed, w.focused, initial, above) + if !placed || !w.focused || !hasFrame { + a.g.timeoutAdd(20, callbacks().task, a.tasks.add(start)) + return + } + if above && !aboveRequested { + aboveRequested = true + if err := w.SetAlwaysOnTop(true); err != nil { + finish(err) + return + } + } + readAbove := func() (bool, error) { + output, err := exec.Command("xprop", "-id", fmt.Sprintf("0x%x", initialID), "_NET_WM_STATE").Output() + return strings.Contains(string(output), "_NET_WM_STATE_ABOVE"), err + } + initialAbove, err := readAbove() + if err != nil { + finish(err) + return + } + observed += fmt.Sprintf(" gotAbove=%t", initialAbove) + if initialAbove != above { + a.g.timeoutAdd(20, callbacks().task, a.tasks.add(start)) + return + } + geometry := api.decorationGeometry(connection, initialID) + verify := func(extents [4]uint32) error { + var got [4]uint32 + current, placed := w.Frame() + currentAbove, err := readAbove() + if err != nil { + return err + } + if !api.readDecorationProperty(connection, initialID, atom, xcbAtomCardinal, got[:], &present) || !present || got != extents || + api.decorationGeometry(connection, initialID) != geometry || + !placed || current != frame || w.g.widgetGetWindow(w.toplevel) != native || !w.focused || currentAbove != above { + return fmt.Errorf("expected extents %v and unchanged focused window %v, got extents %v, client %v, focused=%t", extents, frame, got, current, w.focused) + } + return nil + } + if err := w.SetDecorated(false, func(err error) { + if err == nil { + err = verify([4]uint32{}) + } + if err != nil { + finish(fmt.Errorf("remove decorations: %w", err)) + return + } + if err := w.SetDecorated(true, func(err error) { + if err == nil { + err = verify(initial) + } + if err != nil { + finish(fmt.Errorf("restore decorations: %w", err)) + return + } + checkHidden := func(err error) { + if err != nil { + finish(err) + return + } + w.g.widgetHide(w.toplevel) + if err := w.SetDecorated(false, func(err error) { + if err == nil { + finish(fmt.Errorf("accepted a decoration change on a hidden window")) + } else { + finish(nil) + } + }); err != nil { + finish(err) + } + } + if above { + checkHidden(nil) + } else { + checkGTKDecorationRollback(w, func() error { return verify(initial) }, checkHidden) + } + }); err != nil { + finish(err) + } + }); err != nil { + finish(err) + return + } + if err := w.SetDecorated(false, func(error) { + finish(fmt.Errorf("rejected duplicate called its completion")) + }); err == nil { + finish(fmt.Errorf("accepted two concurrent decoration changes")) + } + } + a.enqueue(start) + return nil + }) + if err != nil || outcome != nil || !completed { + t.Fatalf("GTK transition: completed=%t, loop=%v, request=%v", completed, err, outcome) + } + }) + } +} + +func checkGTKDecorationRollback(w *gtkWindow, verify func() error, done func(error)) { + pid, err := strconv.Atoi(os.Getenv("VIVA_X11_DECORATION_WM_PID")) + if err != nil || pid <= 1 { + done(fmt.Errorf("invalid private window manager pid")) + return + } + name, err := os.ReadFile(fmt.Sprintf("/proc/%d/comm", pid)) + if err != nil || strings.TrimSpace(string(name)) != "xfwm4" { + done(fmt.Errorf("private window manager is not Xfwm4")) + return + } + if err := syscall.Kill(pid, syscall.SIGSTOP); err != nil { + done(err) + return + } + statusPath := fmt.Sprintf("/proc/%d/status", pid) + for deadline := time.Now().Add(time.Second); ; time.Sleep(5 * time.Millisecond) { + status, err := os.ReadFile(statusPath) + if err == nil && strings.Contains(string(status), "\nState:\tT") { + break + } + if err != nil || time.Now().After(deadline) { + _ = syscall.Kill(pid, syscall.SIGCONT) + done(fmt.Errorf("private window manager did not stop: %v", err)) + return + } + } + if err := w.SetDecorated(false, func(err error) { + // Check the callback's postcondition before the WM can handle the queued hints. + verified := verify() + resumed := syscall.Kill(pid, syscall.SIGCONT) + if err == nil || !strings.Contains(err.Error(), "previous frame restored") || resumed != nil || w.g.windowGetDecorated(w.toplevel) == 0 { + done(fmt.Errorf("ignored decoration request = %v; resume = %v", err, resumed)) + return + } + done(verified) + }); err != nil { + _ = syscall.Kill(pid, syscall.SIGCONT) + done(err) + } +} + +func TestGTKDecorationRefusesWayland(t *testing.T) { + w := >kWindow{app: >kApplication{wayland: true}} + if err := w.SetDecorated(false, func(error) { t.Error("rejected request completed") }); !errors.Is(err, platform.ErrWindowDecorationUnsupported) { + t.Fatalf("Wayland request = %v, want unsupported", err) + } +} + +func TestNativeGTKDecorationCompletesWhenQueuedWindowCloses(t *testing.T) { + if os.Getenv("VIVA_GTK_DECORATION_NATIVE") != "1" { + t.Skip("requires a private X11 session") + } + var outcomes []error + if err := RunGTKApplication(func(application platform.Application) error { + control, err := application.OpenWindow(platform.Config{Title: "Viva GTK decoration close probe", Width: 640, Height: 400}) + if err != nil { + return err + } + w := control.(*gtkWindow) + if err := w.SetDecorated(false, func(err error) { outcomes = append(outcomes, err) }); err != nil { + return err + } + // Synchronous destruction overtakes the accepted GLib idle submission. + w.destroy() + if err := w.SetDecorated(true, func(error) { outcomes = append(outcomes, nil) }); err == nil { + return fmt.Errorf("accepted a request on a closed window") + } + return nil + }); err != nil { + t.Fatal(err) + } + if len(outcomes) != 1 || outcomes[0] == nil { + t.Fatalf("completions = %v, want one error", outcomes) + } +} diff --git a/internal/platform/linux/gtk_events_linux.go b/internal/platform/linux/gtk_events_linux.go index f5280d6bf..3091d5fe2 100644 --- a/internal/platform/linux/gtk_events_linux.go +++ b/internal/platform/linux/gtk_events_linux.go @@ -16,37 +16,39 @@ import ( type gdkEventType int32 const ( - gdkMotionNotify gdkEventType = 3 - gdkButtonPress gdkEventType = 4 - gdk2ButtonPress gdkEventType = 5 - gdk3ButtonPress gdkEventType = 6 - gdkButtonRelease gdkEventType = 7 - gdkKeyPress gdkEventType = 8 - gdkKeyRelease gdkEventType = 9 - gdkEnterNotify gdkEventType = 10 - gdkLeaveNotify gdkEventType = 11 - gdkFocusChange gdkEventType = 12 - gdkConfigure gdkEventType = 13 - gdkMap gdkEventType = 14 - gdkUnmap gdkEventType = 15 - gdkScroll gdkEventType = 31 - gdkWindowState gdkEventType = 32 + gdkMotionNotify gdkEventType = 3 + gdkButtonPress gdkEventType = 4 + gdk2ButtonPress gdkEventType = 5 + gdk3ButtonPress gdkEventType = 6 + gdkButtonRelease gdkEventType = 7 + gdkKeyPress gdkEventType = 8 + gdkKeyRelease gdkEventType = 9 + gdkEnterNotify gdkEventType = 10 + gdkLeaveNotify gdkEventType = 11 + gdkFocusChange gdkEventType = 12 + gdkConfigure gdkEventType = 13 + gdkMap gdkEventType = 14 + gdkUnmap gdkEventType = 15 + gdkPropertyNotify gdkEventType = 16 + gdkScroll gdkEventType = 31 + gdkWindowState gdkEventType = 32 ) // Event masks of gtk_widget_add_events. const ( - gdkExposureMask = 1 << 1 - gdkPointerMotionMask = 1 << 2 - gdkButtonPressMask = 1 << 8 - gdkButtonReleaseMask = 1 << 9 - gdkKeyPressMask = 1 << 10 - gdkKeyReleaseMask = 1 << 11 - gdkEnterNotifyMask = 1 << 12 - gdkLeaveNotifyMask = 1 << 13 - gdkFocusChangeMask = 1 << 14 - gdkStructureMask = 1 << 15 - gdkScrollMask = 1 << 21 - gdkSmoothScrollMask = 1 << 23 + gdkExposureMask = 1 << 1 + gdkPointerMotionMask = 1 << 2 + gdkButtonPressMask = 1 << 8 + gdkButtonReleaseMask = 1 << 9 + gdkKeyPressMask = 1 << 10 + gdkKeyReleaseMask = 1 << 11 + gdkEnterNotifyMask = 1 << 12 + gdkLeaveNotifyMask = 1 << 13 + gdkFocusChangeMask = 1 << 14 + gdkStructureMask = 1 << 15 + gdkPropertyChangeMask = 1 << 16 + gdkScrollMask = 1 << 21 + gdkSmoothScrollMask = 1 << 23 ) // GdkModifierType bits. @@ -99,6 +101,15 @@ type gdkEventButton struct { YRoot float64 } +type gdkEventProperty struct { + Type gdkEventType + _ [4]byte + Window uintptr + SendEvent int8 + _ [7]byte + Atom uintptr +} + type gdkEventMotion struct { Type gdkEventType _ [4]byte diff --git a/internal/platform/linux/gtk_events_linux_test.go b/internal/platform/linux/gtk_events_linux_test.go index f6be796ac..b62071f68 100644 --- a/internal/platform/linux/gtk_events_linux_test.go +++ b/internal/platform/linux/gtk_events_linux_test.go @@ -32,6 +32,8 @@ func TestGDKEventLayoutsMatchGTK3(t *testing.T) { {"crossing.Mode", unsafe.Offsetof(gdkEventCrossing{}.Mode), 72}, {"focus.In", unsafe.Offsetof(gdkEventFocus{}.In), 18}, {"configure.X", unsafe.Offsetof(gdkEventConfigure{}.X), 20}, + {"property.Window", unsafe.Offsetof(gdkEventProperty{}.Window), 8}, + {"property.Atom", unsafe.Offsetof(gdkEventProperty{}.Atom), 24}, {"windowState.Changed", unsafe.Offsetof(gdkEventWindowState{}.Changed), 20}, {"windowState.New", unsafe.Offsetof(gdkEventWindowState{}.New), 24}, } { diff --git a/internal/platform/linux/gtk_input_linux.go b/internal/platform/linux/gtk_input_linux.go index 1ca769e58..39bda0ca1 100644 --- a/internal/platform/linux/gtk_input_linux.go +++ b/internal/platform/linux/gtk_input_linux.go @@ -102,10 +102,15 @@ func (w *gtkWindow) handleEvent(widget, event uintptr) uintptr { return 0 } w.focusChanged(in) + w.observeDecorationEvent(nil) case gdkWindowState: w.stateChanged((*gdkEventWindowState)(unsafePointer(event))) + w.observeDecorationEvent(nil) case gdkConfigure: w.reportFrame() + w.observeDecorationEvent(nil) + case gdkPropertyNotify: + w.observeDecorationEvent((*gdkEventProperty)(unsafePointer(event))) } return 0 } diff --git a/internal/platform/linux/gtk_library_linux.go b/internal/platform/linux/gtk_library_linux.go index c3ab18a44..d6ad83e9e 100644 --- a/internal/platform/linux/gtk_library_linux.go +++ b/internal/platform/linux/gtk_library_linux.go @@ -49,6 +49,7 @@ type gtkLibrary struct { windowResize func(window uintptr, width, height int32) windowMove func(window uintptr, x, y int32) windowSetDecorated func(window uintptr, decorated int32) + windowGetDecorated func(window uintptr) int32 windowSetGeometry func(window, widget uintptr, geometry *gdkGeometry, mask uint32) windowSetTypeHint func(window uintptr, hint int32) windowSkipTaskbar func(window uintptr, skip int32) @@ -86,6 +87,7 @@ type gtkLibrary struct { widgetQueueDraw func(widget uintptr) widgetQueueDrawArea func(widget uintptr, x, y, width, height int32) widgetGetWindow func(widget uintptr) uintptr + widgetGetMapped func(widget uintptr) int32 widgetAddEvents func(widget uintptr, events int32) widgetSetEvents func(widget uintptr, events int32) widgetSetSize func(widget uintptr, width, height int32) @@ -157,7 +159,7 @@ type gtkLibrary struct { gdkEventSourceDevice func(event uintptr) uintptr gdkDeviceSource func(device uintptr) int32 gdkScreenDefault func() uintptr - gdkDisplayName func(display uintptr) uintptr + gdkDisplayName func(display uintptr) *byte gdkDisplaySeat func(display uintptr) uintptr gdkMonitorAtPoint func(display uintptr, x, y int32) uintptr gdkMonitorAtIndex func(display uintptr, index int32) uintptr @@ -355,6 +357,7 @@ func (g *gtkLibrary) bindAll() { b(&g.windowResize, "gtk_window_resize") b(&g.windowMove, "gtk_window_move") b(&g.windowSetDecorated, "gtk_window_set_decorated") + b(&g.windowGetDecorated, "gtk_window_get_decorated") b(&g.windowSetGeometry, "gtk_window_set_geometry_hints") b(&g.windowSetTypeHint, "gtk_window_set_type_hint") b(&g.windowSkipTaskbar, "gtk_window_set_skip_taskbar_hint") @@ -389,6 +392,7 @@ func (g *gtkLibrary) bindAll() { b(&g.widgetQueueDraw, "gtk_widget_queue_draw") b(&g.widgetQueueDrawArea, "gtk_widget_queue_draw_area") b(&g.widgetGetWindow, "gtk_widget_get_window") + b(&g.widgetGetMapped, "gtk_widget_get_mapped") b(&g.widgetAddEvents, "gtk_widget_add_events") b(&g.widgetSetEvents, "gtk_widget_set_events") b(&g.widgetSetSize, "gtk_widget_set_size_request") diff --git a/internal/platform/linux/gtk_window_linux.go b/internal/platform/linux/gtk_window_linux.go index 6e408ea76..75c3a9488 100644 --- a/internal/platform/linux/gtk_window_linux.go +++ b/internal/platform/linux/gtk_window_linux.go @@ -48,6 +48,7 @@ type gtkWindow struct { cairoSurface uintptr frame atomic.Pointer[gfx.Rect] + decoration gtkDecorationState maximized bool fullscreen atomic.Bool minimized bool @@ -205,6 +206,10 @@ func (a *gtkApplication) OpenWindow(config platform.Config) (platform.Window, er 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) } + if !a.wayland && config.WindowMode == platform.WindowTitled { + g.widgetAddEvents(w.toplevel, gdkPropertyChangeMask) + g.connect(w.toplevel, "property-notify-event", cb.event, data) + } if config.OnFileDrop != nil { const actionCopy = 1 << 1 g.dragDestSet(w.area, 0, 0, 0, actionCopy) @@ -476,6 +481,7 @@ func (w *gtkWindow) cleanup() { return } w.closed = true + w.closeDecoration() for _, v := range w.views { v.release() } @@ -772,6 +778,9 @@ func (w *gtkWindow) reportFrame() { return } w.syncFullscreen() + if w.decoration.changing { + return + } window := w.g.widgetGetWindow(w.area) if window == 0 { diff --git a/internal/platform/linux/status_item_linux.go b/internal/platform/linux/status_item_linux.go index c750b27a7..3c5674a09 100644 --- a/internal/platform/linux/status_item_linux.go +++ b/internal/platform/linux/status_item_linux.go @@ -688,6 +688,21 @@ func (item *linuxStatusItem) handleMenu(call *dbus.Message) { return } conn.Reply(call, result.Signature, result.Body) + item.publishMenu(result) +} + +func (item *linuxStatusItem) SetHover(handler func(platform.StatusHover)) bool { + return handler == nil && !item.removed.Load() +} + +func (item *linuxStatusItem) RefreshMenu() { + if !item.removed.Load() && item.menu != nil { + item.publishMenu(item.menu.Refresh()) + } +} + +func (item *linuxStatusItem) publishMenu(result dbusmenu.Result) { + conn := item.notifier.conn if result.LayoutUpdated != 0 { // A host that kept the ids of the last layout is told, the way the // interface says, that the menu it is showing was rebuilt and that its @@ -732,10 +747,13 @@ func (item *linuxStatusItem) handleMethod(call *dbus.Message) { return } dismissed := time.Duration(monotonicNow()-panelDismissedAt.Load()) < panelDismissWindow - // The host reports where the click was, not the icon's rectangle. + // Use the host's point unchanged. Activate does not identify a coordinate + // scale or input device: proximity to the pointer cannot distinguish a + // keyboard activation from a host using logical pixels. + anchor := platform.ScreenRect{X: float32(x), Y: float32(y)} item.onClick(platform.StatusClick{ Button: button, - Anchor: platform.ScreenRect{X: float32(x), Y: float32(y)}, + Anchor: anchor, PanelDismissed: dismissed, }) } diff --git a/internal/platform/linux/status_item_linux_test.go b/internal/platform/linux/status_item_linux_test.go index 409c64eda..7643a9653 100644 --- a/internal/platform/linux/status_item_linux_test.go +++ b/internal/platform/linux/status_item_linux_test.go @@ -3,8 +3,10 @@ package linux import ( + "os" "testing" + "github.com/ebitengine/purego" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/dbus" "github.com/vivaui/viva/internal/platform" @@ -18,6 +20,20 @@ func testItem() *linuxStatusItem { return &linuxStatusItem{name: "org.kde.StatusNotifierItem-1-1", tooltip: "Sessions", icon: platform.StatusIcon{Size: 4, RGBA: pixels}} } +func TestStatusPreviewDisableWithoutLinuxHoverEvents(t *testing.T) { + item := testItem() + if item.SetHover(func(platform.StatusHover) {}) { + t.Fatal("StatusNotifier unexpectedly supplies paired hover events") + } + if !item.SetHover(nil) || !item.SetHover(nil) { + t.Fatal("disabling unsupported hover must still succeed") + } + item.removed.Store(true) + if item.SetHover(nil) { + t.Fatal("a removed item unexpectedly accepted a setter") + } +} + func TestStatusItemPropertiesDecodeAsTheirDeclaredTypes(t *testing.T) { item := testItem() signatures := map[string]string{ @@ -103,3 +119,70 @@ func TestPanelAndOriginAreScaledToDevicePixels(t *testing.T) { t.Fatalf("origin 100,50.5 at 2x is %d,%d, want 200,101", x, y) } } + +func TestTrayPanelPreservesHostAnchorAtScale(t *testing.T) { + if os.Getenv("VIVA_TEST_NOTIFICATION_XVFB") != "1" { + t.Skip("requires a private Xvfb server") + } + t.Setenv("VIVA_SCALE", "1.5") + t.Setenv("VIVA_SOFTWARE_RENDERING", "1") + services, _ := statusTestServices(t, watcherNames[0]) + a := &linuxApplication{} + defer a.closeAll() + services.host = a + main, err := a.OpenWindow(platform.Config{Width: 180, Height: 100}) + if err != nil { + t.Fatal(err) + } + win := main.(*nativeWindow).state.win + pointer := platform.ScreenRect{X: 900, Y: 990} + var warp func(uintptr, uint32, uint32, int16, int16, uint16, uint16, int16, int16) xcbVoidCookie + purego.RegisterLibFunc(&warp, win.api.library, "xcb_warp_pointer") + warp(win.connection, xcbAtomNone, win.screen.Root, 0, 0, 0, 0, int16(pointer.X), int16(pointer.Y)) + + for _, test := range []struct { + name string + x, y int32 + }{ + {"keyboard near pointer after scaling", 600, 660}, + {"nearby host point", 590, 650}, + {"pointer point", 900, 990}, + {"screen origin", 0, 0}, + {"other monitor", -600, 660}, + {"distinct", 200, 20}, + } { + t.Run(test.name, func(t *testing.T) { + var anchor platform.ScreenRect + item, err := services.AddStatusItem(platform.StatusItemConfig{ + Icon: statusTestIcon(), OnClick: func(click platform.StatusClick) { anchor = click.Anchor }, + }) + if err != nil { + t.Fatal(err) + } + defer item.Remove() + var args dbus.Encoder + args.Int32(test.x) + args.Int32(test.y) + item.(*linuxStatusItem).handleMethod(&dbus.Message{Member: "Activate", Signature: "ii", Body: args.Bytes()}) + want := platform.ScreenRect{X: float32(test.x), Y: float32(test.y)} + if anchor != want { + t.Fatalf("activation anchor = %+v, want the host's point %+v", anchor, want) + } + if test.name != "keyboard near pointer after scaling" { + return + } + panel, err := a.OpenWindow(platform.Config{ + Width: 180, Height: 66, WindowMode: platform.WindowPanel, HasAnchor: true, Anchor: anchor, + }) + if err != nil { + t.Fatal(err) + } + defer panel.Close() + popup := panel.(*nativeWindow).state.win + x, y := popup.contentOrigin() + if int(x)+int(popup.width)/2 != int(want.X) || int(y)+int(popup.height) != int(want.Y)-platform.PanelGap { + t.Fatalf("panel at %d,%d (%dx%d) does not sit above the host anchor %+v", x, y, popup.width, popup.height, want) + } + }) + } +} diff --git a/internal/platform/linux/window_decoration_linux.go b/internal/platform/linux/window_decoration_linux.go new file mode 100644 index 000000000..28e633912 --- /dev/null +++ b/internal/platform/linux/window_decoration_linux.go @@ -0,0 +1,283 @@ +//go:build !android + +package linux + +import ( + "fmt" + "time" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +const decorationDeadline = 750 * time.Millisecond + +type x11DecorationHints struct { + present bool + words [5]uint32 +} + +type x11DecorationGeometry struct { + x, y int32 + width, height uint32 +} + +type x11DecorationChange struct { + decorated bool + before, after x11DecorationHints + oldFrame [4]uint32 + geometry x11DecorationGeometry + motif, extents uint32 + done func(error) + timer *time.Timer + rollingBack bool +} + +type x11DecorationRequest struct { + done func(error) +} + +func (window *nativeWindow) SetDecorated(decorated bool, done func(error)) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("linux: window is closed") + } + if done == nil { + return fmt.Errorf("linux: window decoration completion callback is required") + } + state := window.state + if state.config.WindowMode != platform.WindowTitled { + return platform.ErrWindowDecorationUnsupported + } + win := state.win + request := &x11DecorationRequest{done: done} + win.mu.Lock() + if win.connection == 0 || window.closed.Load() { + win.mu.Unlock() + return fmt.Errorf("linux: window is closed") + } + if win.decorationRequest != nil { + win.mu.Unlock() + return fmt.Errorf("linux: a decoration change is already pending") + } + win.decorationRequest = request + win.mu.Unlock() + state.application.Post(func() { + win.mu.Lock() + pending := win.decorationRequest == request + win.mu.Unlock() + if pending { + state.requestDecoration(decorated, func(err error) { win.finishDecorationRequest(request, err) }) + } + }) + return nil +} + +// On close, request is nil and any accepted submission must complete, even +// if the window loop closed before taking its queued work. +func (win *window) finishDecorationRequest(request *x11DecorationRequest, err error) { + win.mu.Lock() + pending := win.decorationRequest + if request != nil && request != pending { + win.mu.Unlock() + return + } + win.decorationRequest = nil + win.mu.Unlock() + if pending != nil { + pending.done(err) + } +} + +// requestDecoration runs on the window thread. Completion reports a matching +// frame observed from the window manager, not merely a queued X11 request. +func (state *linuxWindowState) requestDecoration(decorated bool, done func(error)) { + win := state.win + if state.hidden || !state.exposed || win.minimized || win.frame.maximized || win.fullscreen.Load() || + state.config.WindowMode != platform.WindowTitled { + done(fmt.Errorf("linux: decorations can change only on a mapped normal window")) + return + } + if state.decorationChange != nil { + done(fmt.Errorf("linux: a decoration change is already pending")) + return + } + extents, err := win.api.atom(win.connection, "_NET_FRAME_EXTENTS") + if err != nil { + done(err) + return + } + frame, ok := state.decorationExtents(extents) + if !ok { + done(fmt.Errorf("%w: the X11 window manager does not report frame extents", platform.ErrWindowDecorationUnsupported)) + return + } + if decorated == (frame != [4]uint32{}) { + done(nil) + return + } + motif, err := win.api.atom(win.connection, "_MOTIF_WM_HINTS") + if err != nil { + done(err) + return + } + var before x11DecorationHints + if !win.readDecorationProperty(motif, motif, before.words[:], &before.present) { + done(fmt.Errorf("linux: could not read existing window decoration hints")) + return + } + after := before + if decorated { + if state.normalDecoration == nil { + done(fmt.Errorf("linux: no original window decorations to restore")) + return + } + after = *state.normalDecoration + } else { + after.present = true + after.words[0] |= 2 // MWM_HINTS_DECORATIONS + after.words[2] = 0 + } + geometry := state.decorationGeometry() + if geometry.width == 0 || geometry.height == 0 { + done(fmt.Errorf("linux: could not read the client rectangle")) + return + } + change := &x11DecorationChange{decorated: decorated, before: before, after: after, oldFrame: frame, + geometry: geometry, motif: motif, extents: extents, done: done} + state.decorationChange = change + win.requestDecorationHints(motif, after) + state.armDecorationDeadline(change) +} + +func (state *linuxWindowState) decorationGeometry() x11DecorationGeometry { + win := state.win + return win.api.decorationGeometry(win.connection, win.id) +} + +func (api *xcbAPI) decorationGeometry(connection uintptr, id uint32) x11DecorationGeometry { + geometry := api.getGeometryReply(connection, api.getGeometry(connection, id), nil) + if geometry == nil { + return x11DecorationGeometry{} + } + defer api.free(unsafe.Pointer(geometry)) + origin := api.translateCoordinatesReply(connection, api.translateCoordinates(connection, id, geometry.Root, 0, 0), nil) + if origin == nil { + return x11DecorationGeometry{} + } + defer api.free(unsafe.Pointer(origin)) + return x11DecorationGeometry{x: int32(origin.DstX), y: int32(origin.DstY), + width: uint32(geometry.Width), height: uint32(geometry.Height)} +} + +func (state *linuxWindowState) decorationExtents(atom uint32) ([4]uint32, bool) { + var frame [4]uint32 + var present bool + ok := state.win.readDecorationProperty(atom, xcbAtomCardinal, frame[:], &present) + return frame, ok && present +} + +func (win *window) readDecorationProperty(atom, kind uint32, words []uint32, present *bool) bool { + return win.api.readDecorationProperty(win.connection, win.id, atom, kind, words, present) +} + +func (api *xcbAPI) readDecorationProperty(connection uintptr, id, atom, kind uint32, words []uint32, present *bool) bool { + cookie := api.getProperty(connection, 0, id, atom, kind, 0, uint32(len(words))) + var nativeError unsafe.Pointer + reply := api.getPropertyReply(connection, cookie, &nativeError) + if reply != nil { + defer api.free(unsafe.Pointer(reply)) + } + if nativeError != nil { + api.free(nativeError) + return false + } + if reply == nil { + return false + } + *present = reply.Type != 0 + if !*present { + return true + } + if reply.Type != kind || reply.Format != 32 || reply.BytesAfter != 0 || reply.ValueLength != uint32(len(words)) { + return false + } + copy(words, unsafe.Slice((*uint32)(api.getPropertyValue(reply)), len(words))) + return true +} + +func (win *window) writeDecorationHints(atom uint32, hints x11DecorationHints) { + if hints.present { + win.api.changeProperty(win.connection, xcbPropertyReplace, win.id, atom, atom, 32, + uint32(len(hints.words)), unsafe.Pointer(&hints.words[0])) + } else { + win.api.deleteProperty(win.connection, win.id, atom) + } + win.api.flush(win.connection) +} + +func (win *window) requestDecorationHints(atom uint32, hints x11DecorationHints) { + // Xfwm does not restore decorations in response to a deleted property. + // Explicitly restore them, then remove the temporary hint once observed. + if !hints.present { + hints = x11DecorationHints{present: true, words: [5]uint32{2, 0, 1, 0, 0}} + } + win.writeDecorationHints(atom, hints) +} + +func (state *linuxWindowState) observeDecorationChange() { + change := state.decorationChange + if change == nil { + return + } + frame, ok := state.decorationExtents(change.extents) + if !ok || state.decorationGeometry() != change.geometry { + return + } + if change.rollingBack { + if frame == change.oldFrame { + if !change.before.present { + state.win.writeDecorationHints(change.motif, change.before) + } + state.finishDecorationChange(fmt.Errorf("linux: decoration change was not confirmed; previous frame restored")) + } + return + } + if change.decorated == (frame != [4]uint32{}) { + if change.decorated { + if !change.after.present { + state.win.writeDecorationHints(change.motif, change.after) + } + state.normalDecoration = nil + } else { + before := change.before + state.normalDecoration = &before + } + state.finishDecorationChange(nil) + } +} + +func (state *linuxWindowState) armDecorationDeadline(change *x11DecorationChange) { + change.timer = time.AfterFunc(decorationDeadline, func() { + state.application.Post(func() { + if state.decorationChange != change { + return + } + if change.rollingBack { + state.finishDecorationChange(fmt.Errorf("linux: decoration change and restoration were not confirmed")) + return + } + change.rollingBack = true + state.win.requestDecorationHints(change.motif, change.before) + state.armDecorationDeadline(change) + state.observeDecorationChange() + }) + }) +} + +func (state *linuxWindowState) finishDecorationChange(err error) { + if change := state.decorationChange; change != nil { + state.decorationChange = nil + change.timer.Stop() + change.done(err) + } +} diff --git a/internal/platform/linux/window_decoration_linux_test.go b/internal/platform/linux/window_decoration_linux_test.go new file mode 100644 index 000000000..846b33d0c --- /dev/null +++ b/internal/platform/linux/window_decoration_linux_test.go @@ -0,0 +1,194 @@ +//go:build !android + +package linux + +import ( + "fmt" + "os" + "strconv" + "strings" + "syscall" + "testing" + "time" + + "github.com/vivaui/viva/internal/platform" +) + +func TestX11DecorationRefusesHiddenWindow(t *testing.T) { + state := &linuxWindowState{win: &window{}, hidden: true} + called := false + state.requestDecoration(false, func(err error) { + called = true + if err == nil { + t.Error("accepted a decoration change on a hidden window") + } + }) + if !called || state.decorationChange != nil { + t.Fatal("hidden-window refusal left a pending request") + } +} + +func TestNativeX11DecorationPreservesClient(t *testing.T) { + if os.Getenv("VIVA_X11_DECORATION_NATIVE") != "1" { + t.Skip("requires a private X11 session with a window manager") + } + t.Setenv("VIVA_SOFTWARE_RENDERING", "1") + t.Setenv("VIVA_SCALE", "1") + for _, size := range [][2]int{{640, 400}, {1280, 800}} { + t.Run(fmt.Sprintf("%dx%d", size[0], size[1]), func(t *testing.T) { + var outcome error + err := RunApplication(func(application platform.Application) error { + control, err := application.OpenWindow(platform.Config{ + Title: fmt.Sprintf("Viva live window decoration %dx%d", size[0], size[1]), Width: size[0], Height: size[1], + ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + native := control.(*nativeWindow) + state := native.state + win := state.win + extentAtom, err := win.api.atom(win.connection, "_NET_FRAME_EXTENTS") + if err != nil { + return err + } + motifAtom, err := win.api.atom(win.connection, "_MOTIF_WM_HINTS") + if err != nil { + return err + } + var guard *time.Timer + finished := false + finish := func(err error) { + if !finished { + finished, outcome = true, err + guard.Stop() + application.Quit() + } + } + guard = time.AfterFunc(8*time.Second, func() { application.Post(func() { finish(fmt.Errorf("decoration test did not complete")) }) }) + originalID := win.id + var start func() + start = func() { + if finished { + return + } + extents, ok := state.decorationExtents(extentAtom) + if !state.exposed || !ok || extents == [4]uint32{} || win.width != uint32(size[0]) || win.height != uint32(size[1]) { + time.AfterFunc(25*time.Millisecond, func() { application.Post(start) }) + return + } + geometry := state.decorationGeometry() + var initial x11DecorationHints + if !win.readDecorationProperty(motifAtom, motifAtom, initial.words[:], &initial.present) { + finish(fmt.Errorf("could not read original Motif hints")) + return + } + if err := native.SetDecorated(false, func(err error) { + if err != nil { + finish(fmt.Errorf("hide decorations: %w", err)) + return + } + if frame, ok := state.decorationExtents(extentAtom); !ok || frame != [4]uint32{} || win.id != originalID || state.decorationGeometry() != geometry { + finish(fmt.Errorf("borderless window did not preserve its client rectangle or id: %v", frame)) + return + } + if err := native.SetDecorated(true, func(err error) { + if err != nil { + finish(fmt.Errorf("restore decorations: %w", err)) + return + } + if frame, ok := state.decorationExtents(extentAtom); !ok || frame != extents || win.id != originalID || state.decorationGeometry() != geometry { + finish(fmt.Errorf("restored window did not preserve its frame and client rectangle: %v", frame)) + return + } + var restored x11DecorationHints + if !win.readDecorationProperty(motifAtom, motifAtom, restored.words[:], &restored.present) || restored != initial { + finish(fmt.Errorf("original Motif hints were not restored: %+v != %+v", restored, initial)) + return + } + if size[0] == 640 && os.Getenv("VIVA_X11_DECORATION_WM_PID") != "" { + checkIgnoredDecoration(native, motifAtom, initial, finish) + } else { + finish(nil) + } + }); err != nil { + finish(fmt.Errorf("submit restore: %w", err)) + } + }); err != nil { + finish(fmt.Errorf("submit hide: %w", err)) + return + } + if err := native.SetDecorated(false, func(error) { finish(fmt.Errorf("duplicate request completed")) }); err == nil { + finish(fmt.Errorf("accepted a second decoration request before the first completed")) + } + } + application.Post(start) + return nil + }) + if err != nil || outcome != nil { + t.Fatalf("native transition: %v; loop: %v", outcome, err) + } + }) + } +} + +func checkIgnoredDecoration(native *nativeWindow, motif uint32, initial x11DecorationHints, finish func(error)) { + pid, err := strconv.Atoi(os.Getenv("VIVA_X11_DECORATION_WM_PID")) + if err != nil || pid <= 1 { + finish(fmt.Errorf("invalid private window manager pid")) + return + } + name, err := os.ReadFile(fmt.Sprintf("/proc/%d/comm", pid)) + if err != nil || strings.TrimSpace(string(name)) != "xfwm4" { + finish(fmt.Errorf("private window manager is not Xfwm4")) + return + } + if err := syscall.Kill(pid, syscall.SIGSTOP); err != nil { + finish(err) + return + } + if err := native.SetDecorated(false, func(err error) { + resumeErr := syscall.Kill(pid, syscall.SIGCONT) + if err == nil || !strings.Contains(err.Error(), "previous frame restored") || resumeErr != nil { + finish(fmt.Errorf("ignored request: %v; resume: %v", err, resumeErr)) + return + } + var rolledBack x11DecorationHints + if !native.state.win.readDecorationProperty(motif, motif, rolledBack.words[:], &rolledBack.present) || rolledBack != initial { + finish(fmt.Errorf("ignored request did not restore original hints: %+v", rolledBack)) + return + } + finish(nil) + }); err != nil { + _ = syscall.Kill(pid, syscall.SIGCONT) + finish(err) + } +} + +func TestNativeX11DecorationCompletesWhenQueuedWindowCloses(t *testing.T) { + if os.Getenv("VIVA_X11_DECORATION_NATIVE") != "1" { + t.Skip("requires a private X11 session with a window manager") + } + t.Setenv("VIVA_SOFTWARE_RENDERING", "1") + var outcomes []error + if err := RunApplication(func(application platform.Application) error { + control, err := application.OpenWindow(platform.Config{ + Title: "Viva decoration close regression", Width: 640, Height: 400, ClearColor: platform.Color{Alpha: 1}, + }) + if err != nil { + return err + } + native := control.(*nativeWindow) + if err := native.SetDecorated(false, func(err error) { outcomes = append(outcomes, err) }); err != nil { + return err + } + // Close on the loop before it can drain the queued submission. + application.(*linuxApplication).closeWindow(native.state) + return nil + }); err != nil { + t.Fatal(err) + } + if len(outcomes) != 1 || outcomes[0] == nil || !strings.Contains(outcomes[0].Error(), "window closed") { + t.Fatalf("closed request outcomes = %v", outcomes) + } +} diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index fde5c284d..500489b6b 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -31,6 +31,7 @@ type window struct { fullscreenHandler func(bool) minimumSize *minimumSizeCache mu sync.Mutex + decorationRequest *x11DecorationRequest // guarded by mu api *xcbAPI connection uintptr screen *xcbScreen @@ -178,6 +179,8 @@ type linuxWindowState struct { // frameGeometryDirty means a maximization property changed the client-side // margin before its matching ConfigureNotify supplied the final dimensions. frameGeometryDirty bool + decorationChange *x11DecorationChange + normalDecoration *x11DecorationHints // hidden records the application's request, independently of the asynchronous // MapNotify/UnmapNotify events. exposed records that a mapped frame was shown; // it must not suppress later server requests to restore lost pixels. @@ -852,6 +855,8 @@ func (application *linuxApplication) closeWindow(target *linuxWindowState) { target.renderer.close() target.text.close() target.win.close() + target.finishDecorationChange(fmt.Errorf("linux: window closed during decoration change")) + target.win.finishDecorationRequest(nil, fmt.Errorf("linux: window closed during decoration change")) application.rebuildPoll() if len(application.windows) == 0 { activeWindow.CompareAndSwap(target.win, nil) @@ -1026,6 +1031,12 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { return true, nil } case xcbPropertyNotify: + if change := state.decorationChange; change != nil { + property := (*xcbPropertyEvent)(event) + if property.Window == win.id && property.Atom == change.extents { + state.observeDecorationChange() + } + } if win.incrEvent((*xcbPropertyEvent)(event)) { return false, nil } @@ -1128,6 +1139,9 @@ func (state *linuxWindowState) handleEvent(event unsafe.Pointer) (bool, error) { } else { win.updateMinimumSize(config) } + if configure.Window == win.id { + state.observeDecorationChange() + } case xcbButtonPress: inputEvent := (*xcbInputEvent)(event) win.noteInputEvent(inputEvent) diff --git a/internal/platform/linux/xcb_linux.go b/internal/platform/linux/xcb_linux.go index 3af3cd765..58215273c 100644 --- a/internal/platform/linux/xcb_linux.go +++ b/internal/platform/linux/xcb_linux.go @@ -168,6 +168,14 @@ type xcbPropertyReply struct { ValueLength uint32 Pad [12]byte } +type xcbGeometryReply struct { + ResponseType, Depth uint8 + Sequence uint16 + Length, Root uint32 + X, Y int16 + Width, Height, BorderWidth uint16 + Pad [10]byte +} // xcbQueryTreeReply is the fixed part of a QueryTree reply; the children, when // any, follow it. Only the parent is read: it is how a drag source walks from @@ -326,10 +334,13 @@ type xcbAPI struct { atomNameValue func(*xcbAtomNameReply) *byte atomNameLength func(*xcbAtomNameReply) int32 changeProperty func(uintptr, uint8, uint32, uint32, uint32, uint8, uint32, unsafe.Pointer) xcbVoidCookie + deleteProperty func(uintptr, uint32, uint32) xcbVoidCookie getProperty func(uintptr, uint8, uint32, uint32, uint32, uint32, uint32) xcbPropertyCookie getPropertyReply func(uintptr, xcbPropertyCookie, *unsafe.Pointer) *xcbPropertyReply getPropertyValue func(*xcbPropertyReply) unsafe.Pointer getPropertyLength func(*xcbPropertyReply) int32 + getGeometry func(uintptr, uint32) xcbVoidCookie + getGeometryReply func(uintptr, xcbVoidCookie, *unsafe.Pointer) *xcbGeometryReply getKeyboardMapping func(uintptr, uint8, uint8) xcbKeyboardMappingCookie keyboardMappingReply func(uintptr, xcbKeyboardMappingCookie, *unsafe.Pointer) *xcbKeyboardMappingReply keyboardMappingKeysyms func(*xcbKeyboardMappingReply) *uint32 @@ -422,10 +433,13 @@ func openXCB() (*xcbAPI, error) { purego.RegisterLibFunc(&api.atomNameValue, library, "xcb_get_atom_name_name") purego.RegisterLibFunc(&api.atomNameLength, library, "xcb_get_atom_name_name_length") purego.RegisterLibFunc(&api.changeProperty, library, "xcb_change_property") + purego.RegisterLibFunc(&api.deleteProperty, library, "xcb_delete_property") purego.RegisterLibFunc(&api.getProperty, library, "xcb_get_property") purego.RegisterLibFunc(&api.getPropertyReply, library, "xcb_get_property_reply") purego.RegisterLibFunc(&api.getPropertyValue, library, "xcb_get_property_value") purego.RegisterLibFunc(&api.getPropertyLength, library, "xcb_get_property_value_length") + purego.RegisterLibFunc(&api.getGeometry, library, "xcb_get_geometry") + purego.RegisterLibFunc(&api.getGeometryReply, library, "xcb_get_geometry_reply") purego.RegisterLibFunc(&api.getKeyboardMapping, library, "xcb_get_keyboard_mapping") purego.RegisterLibFunc(&api.keyboardMappingReply, library, "xcb_get_keyboard_mapping_reply") purego.RegisterLibFunc(&api.keyboardMappingKeysyms, library, "xcb_get_keyboard_mapping_keysyms") diff --git a/internal/platform/web/accessibility.go b/internal/platform/web/accessibility.go index 702209130..19255da7e 100644 --- a/internal/platform/web/accessibility.go +++ b/internal/platform/web/accessibility.go @@ -57,8 +57,8 @@ func describeAccessibility(destination []accessibilityDescription, hits []gfx.Hi } } for _, hit := range hits { - if hit.Block || hit.MovesWindow || hit.IsLabel { - continue // an occluder, a move region, or a label of another node + if hit.Block || hit.MovesWindow || hit.IsLabel || hit.Presentational { + continue // an occluder, a move region, a label of another node, or a pointer region } label := hit.Label if name, ok := names[hit.ID]; ok { diff --git a/internal/platform/windows/font_fallback_registered_windows_test.go b/internal/platform/windows/font_fallback_registered_windows_test.go new file mode 100644 index 000000000..4078337e4 --- /dev/null +++ b/internal/platform/windows/font_fallback_registered_windows_test.go @@ -0,0 +1,62 @@ +package windows + +import ( + "bytes" + "runtime" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +// A font registered at run time is not in DirectWrite's system collection. A face +// that names it as a fallback therefore used to draw .notdef, as if the family +// were not installed, while the same family as the primary drew its glyphs. The +// fallback has to search the collection the text format is made from. +func TestRegisteredFontDrawsFallbackCharacters(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + engine, err := theTextEngine() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + family, unregister, err := engine.RegisterFont(testIconsFont) + if err != nil { + t.Fatalf("register the test font: %v", err) + } + defer unregister() + rasterizer, err := newDirectRasterizer() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + defer rasterizer.close() + + white := gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1} + draw := func(face gfx.MonoFace, value string, cells int32) []byte { + runs := []gfx.TextRun{{Bytes: int32(len(value)), Cells: cells, Color: white}} + label := platform.TextLabel{Value: value, Width: 48, Height: 32, FontSize: 20, CellWidth: 12, Mono: true, MonoFace: face, Runs: runs} + pixels, _, err := rasterizer.rasterize(label, 1, 48, 32, false, 0) + if err != nil { + t.Fatal(err) + } + return append([]byte(nil), pixels...) + } + base := gfx.MonoFamily("Consolas") + // A code point in a private-use plane the test font does not map: every + // family in the test draws it as the last-resort box. + boxed := draw(base, "\U0010FFFE", 1) + if bytes.Equal(draw(gfx.MonoFamily(family), testIcon, 1), boxed) { + t.Fatal("the registered family as the primary drew the box") + } + stacked := draw(gfx.MonoStack(base, family), testIcon, 1) + if bytes.Equal(stacked, boxed) { + t.Fatal("the registered family as a fallback drew the box") + } + if bytes.Equal(stacked, draw(base, testIcon, 1)) { + t.Fatal("the registered fallback changed no pixels") + } + // What the primary draws must not change because of the fallback. + if !bytes.Equal(draw(gfx.MonoStack(base, family), "abc", 3), draw(base, "abc", 3)) { + t.Fatal("the fallback changed how the primary draws the characters it has") + } +} diff --git a/internal/platform/windows/font_fallback_windows.go b/internal/platform/windows/font_fallback_windows.go index 0664ce5d0..ff193f312 100644 --- a/internal/platform/windows/font_fallback_windows.go +++ b/internal/platform/windows/font_fallback_windows.go @@ -15,6 +15,7 @@ type unicodeRange struct{ first, last uint32 } // faceFallback is the font fallback a face draws the characters its family lacks with. type faceFallback struct { face gfx.MonoFace + fonts uint32 // customFonts.revision the fallback was built against fallback uintptr // an IDWriteFontFallback; 0 when it could not be made } @@ -28,13 +29,18 @@ func (rasterizer *directRasterizer) fontFallback(face gfx.MonoFace) uintptr { if len(names) == 0 { return 0 } + customFonts.RLock() + fonts := customFonts.revision + customFonts.RUnlock() for _, known := range rasterizer.fallbacks { - if known.face == face { + if known.face == face && known.fonts == fonts { return known.fallback } } fallback := rasterizer.buildFontFallback(names) - rasterizer.fallbacks = append(rasterizer.fallbacks, faceFallback{face: face, fallback: fallback}) + // An older revision stays until the rasterizer closes: a text format made + // earlier may hold it, and fonts are registered before the first paint. + rasterizer.fallbacks = append(rasterizer.fallbacks, faceFallback{face: face, fonts: fonts, fallback: fallback}) return fallback } @@ -68,7 +74,14 @@ func (rasterizer *directRasterizer) buildFontFallback(names []string) uintptr { // of its own kind. var addMapping func(this uintptr, ranges *unicodeRange, rangesCount uint32, names **uint16, namesCount uint32, collection uintptr, locale, base *uint16, scale float32) uintptr purego.RegisterFunc(&addMapping, vtable(builder, writeBuilderAddMapping)) - status := addMapping(builder, &everything, 1, &targets[0], uint32(len(targets)), 0, nil, nil, 1) + // The collection a text format is made from, the system's and the fonts the + // application registered, or the system's alone. A registered family is not + // in the system collection, so the fallback has to search this one or it is + // skipped as if it were not installed. + customFonts.RLock() + defer customFonts.RUnlock() + collection := customFonts.collection + status := addMapping(builder, &everything, 1, &targets[0], uint32(len(targets)), collection, nil, nil, 1) runtime.KeepAlive(targets) if hresult(status) != nil { return 0 diff --git a/internal/platform/windows/offscreen_update_windows_test.go b/internal/platform/windows/offscreen_update_windows_test.go new file mode 100644 index 000000000..7c4d3de3a --- /dev/null +++ b/internal/platform/windows/offscreen_update_windows_test.go @@ -0,0 +1,85 @@ +package windows + +import ( + "bytes" + "math/rand" + "testing" + + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +// A renderer that is sent only the store's updates (a range that may grow the +// list, be cut short with Shrink, or a rebuild) draws exactly what a renderer +// given the whole list draws, through batches that delete, insert in the +// middle and recolor shapes together. +func TestOffscreenIncrementalUpdatesDrawWhatARebuildDraws(t *testing.T) { + incremental := newOffscreen(t, 160, 120, 1) + random := rand.New(rand.NewSource(3)) + graph := scene.New() + var store render.Store + var shapes []scene.ID + place := func() (scene.Rect, scene.Color) { + bounds := scene.Rect{X: float32(random.Intn(140)), Y: float32(random.Intn(100)), Width: float32(8 + random.Intn(20)), Height: float32(8 + random.Intn(20))} + return bounds, scene.Color{Red: random.Float32(), Green: random.Float32(), Blue: random.Float32(), Alpha: 1} + } + for range 40 { + bounds, color := place() + id, _ := graph.AddRectangle(graph.Root(), bounds, color) + shapes = append(shapes, id) + } + shrinks, grows := 0, 0 + for batch := 0; batch < 120; batch++ { + if batch > 0 { + for operations := 1 + random.Intn(6); operations > 0; operations-- { + switch operation := random.Intn(3); { + case operation == 0 && len(shapes) > 1: + at := random.Intn(len(shapes)) + graph.Remove(shapes[at]) + shapes = append(shapes[:at], shapes[at+1:]...) + case operation == 1: + at := random.Intn(len(shapes) + 1) + previous := scene.ID(0) + if at > 0 { + previous = shapes[at-1] + } + bounds, color := place() + id, ok := graph.InsertRoundedRectangle(graph.Root(), previous, bounds, color, 0) + if !ok { + t.Fatal("insert failed") + } + shapes = append(shapes[:at], append([]scene.ID{id}, shapes[at:]...)...) + case len(shapes) > 0: + bounds, color := place() + graph.SetRectangle(shapes[random.Intn(len(shapes))], bounds, color) + } + } + } + update, err := store.Apply(graph.DrainChanges(nil)) + if err != nil { + t.Fatalf("batch %d: %v", batch, err) + } + rectangles := store.Rectangles() + if !update.Rebuild && update.Shrink { + shrinks++ + } + if !update.Rebuild && !update.Shrink && update.First+update.Count > len(incremental.renderer.instances) { + grows++ + } + if err := incremental.renderer.apply(platform.Frame{Update: update, Rectangles: rectangles}); err != nil { + t.Fatalf("batch %d: update %+v: %v", batch, update, err) + } + got, err := incremental.Image() + if err != nil { + t.Fatal(err) + } + want := renderScene(t, newOffscreen(t, 160, 120, 1), append([]render.Rectangle(nil), rectangles...), nil) + if !bytes.Equal(got.Pix, want.Pix) { + t.Fatalf("batch %d: update %+v drew other pixels than a rebuild of %d instances", batch, update, len(rectangles)) + } + } + if shrinks == 0 || grows == 0 { + t.Fatalf("the batches sent %d shrinking and %d growing ranges; the test needs both", shrinks, grows) + } +} diff --git a/internal/platform/windows/status_hover_windows.go b/internal/platform/windows/status_hover_windows.go new file mode 100644 index 000000000..27677ce1a --- /dev/null +++ b/internal/platform/windows/status_hover_windows.go @@ -0,0 +1,85 @@ +package windows + +import ( + "syscall" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +var statusRootWindow = user.NewProc("GetAncestor") +var statusWindowClass = user.NewProc("GetClassNameW") + +func (item *statusItem) setVersion() { + data := item.data() + data.Version = notifyVersion4 + ok, _, _ := shellNotifyIcon.Call(notifySetVersion, uintptr(unsafe.Pointer(&data))) + item.version4 = ok != 0 +} + +func (item *statusItem) SetHover(handler func(platform.StatusHover)) bool { + if item.removed.Load() { + return false + } + if handler != nil { + if !item.version4 { + return false + } + if _, ok := item.visibleTrayAnchor(item.application.status.window); !ok { + return false + } + } else if item.hover == nil { + // Disabling is idempotent even on shells without paired hover events. + return true + } + item.endHover() + previous := item.hover + item.hover = handler + if err := item.notify(notifyModify); err != nil { + item.hover = previous + return false + } + return true +} + +func (item *statusItem) RefreshMenu() {} + +func (item *statusItem) beginHover(window uintptr) { + if item.hover == nil || item.hovering { + return + } + anchor, ok := item.visibleTrayAnchor(window) + if ok { + item.hovering = true + item.hover(platform.StatusHover{Anchor: anchor, Entered: true}) + } +} + +func (item *statusItem) endHover() { + if item.hovering { + item.hovering = false + item.hover(platform.StatusHover{}) + } +} + +func (item *statusItem) visibleTrayAnchor(window uintptr) (platform.ScreenRect, bool) { + anchor, ok := item.iconRect(window) + if !ok { + return anchor, false + } + // Only the visible taskbar supplies paired notifications. Shell overflow + // hosts can report a rectangle but omit the matching close notification. + x, y := int32(anchor.X+anchor.Width/2), int32(anchor.Y+anchor.Height/2) + target, _, _ := windowFromPoint.Call(uintptr(uint32(x)) | uintptr(uint32(y))<<32) + root, _, _ := statusRootWindow.Call(target, 2) // GA_ROOT + var name [64]uint16 + count, _, _ := statusWindowClass.Call(root, uintptr(unsafe.Pointer(&name[0])), uintptr(len(name))) + if count == 0 { + return anchor, false + } + switch syscall.UTF16ToString(name[:count]) { + case "Shell_TrayWnd", "Shell_SecondaryTrayWnd": + return anchor, true + } + return anchor, false +} diff --git a/internal/platform/windows/status_item_windows.go b/internal/platform/windows/status_item_windows.go index 6b1460cff..1192aac28 100644 --- a/internal/platform/windows/status_item_windows.go +++ b/internal/platform/windows/status_item_windows.go @@ -32,6 +32,8 @@ const ( wmContextMenu = 0x007b ninSelect = 0x0400 ninKeySelect = 0x0401 + ninPopupOpen = 0x0406 + ninPopupClose = 0x0407 notifySetVersion = 4 notifyVersion4 = 4 @@ -148,6 +150,9 @@ type statusItem struct { tooltip string onClick func(platform.StatusClick) menu func() []platform.MenuItem + hover func(platform.StatusHover) + hovering bool + version4 bool removed atomic.Bool } @@ -176,9 +181,7 @@ func (application *windowsApplication) AddStatusItem(config platform.StatusItemC destroyIcon.Call(icon) return nil, err } - version := item.data() - version.Version = notifyVersion4 - shellNotifyIcon.Call(notifySetVersion, uintptr(unsafe.Pointer(&version))) + item.setVersion() status.items[item.id] = item return item, nil } @@ -241,7 +244,13 @@ func (item *statusItem) data() notifyIconData { CallbackMessage: wmStatusNotify, Icon: item.icon, } - copyUTF16(data.Tip[:], item.tooltip) + if item.hover != nil { + data.Flags &^= notifyShowTip + // NIF_TIP must remain set: an empty szTip replaces the shell's cached + // text, including when SetTooltip runs while a preview is enabled. + } else { + copyUTF16(data.Tip[:], item.tooltip) + } return data } @@ -276,10 +285,12 @@ func (item *statusItem) SetIcon(icon platform.StatusIcon) error { } previous := item.icon item.icon = handle - if err := item.notify(notifyModify); err != nil { + data := item.data() + data.Flags = notifyIcon + if ok, _, callErr := shellNotifyIcon.Call(notifyModify, uintptr(unsafe.Pointer(&data))); ok == 0 { item.icon = previous destroyIcon.Call(handle) - return err + return windowsCallError("update the status item icon", callErr) } destroyIcon.Call(previous) return nil @@ -375,9 +386,8 @@ func statusProc(window, kind, first, second uintptr) (result uintptr) { for _, item := range status.items { if !item.removed.Load() { item.notify(notifyAdd) - version := item.data() - version.Version = notifyVersion4 - shellNotifyIcon.Call(notifySetVersion, uintptr(unsafe.Pointer(&version))) + item.endHover() + item.setVersion() } } return 0 @@ -391,7 +401,18 @@ func (status *statusState) notified(window, anchor, packed uintptr) { event := uint32(packed) & 0xffff id := uint32(packed>>16) & 0xffff item := status.items[id] - if item == nil || item.removed.Load() || item.onClick == nil && item.menu == nil { + if item == nil || item.removed.Load() { + return + } + switch event { + case ninPopupOpen: + item.beginHover(window) + return + case ninPopupClose: + item.endHover() + return + } + if item.onClick == nil && item.menu == nil { return } button, ok := statusButton(event) @@ -427,12 +448,19 @@ func statusButton(event uint32) (gfx.PointerButton, bool) { // anchor is the icon's rectangle on the screen, in pixels. When the shell cannot // say, the click position it reported stands in for it. func (item *statusItem) anchor(window, click uintptr) platform.ScreenRect { + if anchor, ok := item.iconRect(window); ok { + return anchor + } + return platform.ScreenRect{X: float32(int16(click)), Y: float32(int16(click >> 16))} +} + +func (item *statusItem) iconRect(window uintptr) (platform.ScreenRect, bool) { identifier := notifyIconIdentifier{Size: uint32(unsafe.Sizeof(notifyIconIdentifier{})), Window: window, ID: item.id} var bounds rect - if status, _, _ := notifyIconGetRect.Call(uintptr(unsafe.Pointer(&identifier)), uintptr(unsafe.Pointer(&bounds))); int32(uint32(status)) >= 0 && bounds.Right > bounds.Left { - return platform.ScreenRect{X: float32(bounds.Left), Y: float32(bounds.Top), Width: float32(bounds.Right - bounds.Left), Height: float32(bounds.Bottom - bounds.Top)} + if status, _, _ := notifyIconGetRect.Call(uintptr(unsafe.Pointer(&identifier)), uintptr(unsafe.Pointer(&bounds))); int32(uint32(status)) >= 0 && bounds.Right > bounds.Left && bounds.Bottom > bounds.Top { + return platform.ScreenRect{X: float32(bounds.Left), Y: float32(bounds.Top), Width: float32(bounds.Right - bounds.Left), Height: float32(bounds.Bottom - bounds.Top)}, true } - return platform.ScreenRect{X: float32(int16(click)), Y: float32(int16(click >> 16))} + return platform.ScreenRect{}, false } // Quit closes every window, close requests notwithstanding, and ends the loop. diff --git a/internal/platform/windows/status_item_windows_test.go b/internal/platform/windows/status_item_windows_test.go index 55423e6ca..6cd297432 100644 --- a/internal/platform/windows/status_item_windows_test.go +++ b/internal/platform/windows/status_item_windows_test.go @@ -23,6 +23,38 @@ func TestStatusItemAsksTheShellForTheStandardTooltip(t *testing.T) { } } +func TestStatusPreviewClearsAndRestoresTheShellTooltip(t *testing.T) { + application := &windowsApplication{status: &statusState{window: 1}} + item := &statusItem{application: application, tooltip: "Unread conversations"} + item.hover = func(platform.StatusHover) {} + for _, text := range []string{"Unread conversations", "New sender"} { + item.tooltip = text + data := item.data() + if data.Flags¬ifyTip == 0 || data.Flags¬ifyShowTip != 0 || data.Tip[0] != 0 { + t.Fatalf("preview must send NIF_TIP and an empty szTip: flags=%#x tip=%q", data.Flags, syscall.UTF16ToString(data.Tip[:])) + } + } + item.hover = nil + data := item.data() + if data.Flags¬ifyTip == 0 || data.Flags¬ifyShowTip == 0 || syscall.UTF16ToString(data.Tip[:]) != "New sender" { + t.Fatalf("disabling preview did not restore the current tooltip: flags=%#x tip=%q", data.Flags, syscall.UTF16ToString(data.Tip[:])) + } +} + +func TestStatusPreviewDisableDoesNotRequireVersion4(t *testing.T) { + item := &statusItem{} + if item.SetHover(func(platform.StatusHover) {}) { + t.Fatal("a shell without version 4 unexpectedly accepted native hover") + } + if !item.SetHover(nil) || !item.SetHover(nil) { + t.Fatal("disabling an unsupported hover must still succeed") + } + item.removed.Store(true) + if item.SetHover(nil) { + t.Fatal("a removed item unexpectedly accepted a setter") + } +} + // Exercise the notification dispatcher, not only its button decoder. A menu // must not swallow primary activation when the application also has a callback. func TestStatusNotificationRoutesActivationAndContextMenu(t *testing.T) { diff --git a/internal/platform/windows/window_decoration_windows.go b/internal/platform/windows/window_decoration_windows.go new file mode 100644 index 000000000..82ed9cbd5 --- /dev/null +++ b/internal/platform/windows/window_decoration_windows.go @@ -0,0 +1,214 @@ +package windows + +import ( + "errors" + "fmt" + "sync" + "syscall" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +const wmChangeDecoration = 0x8056 + +var ( + decorationGetFocus = user.NewProc("GetFocus") + decorationGetActive = user.NewProc("GetActiveWindow") + decorationGetMenu = user.NewProc("GetMenu") + decorationIsVisible = user.NewProc("IsWindowVisible") +) + +type windowDecoration struct { + mu sync.Mutex + closed bool + pending *decorationRequest + // The owner thread alone reads and changes the style and placement state. + changing bool + removed bool + style uint32 +} + +type decorationRequest struct { + decorated bool + done func(error) +} + +func (window *nativeWindow) SetDecorated(decorated bool, done func(error)) error { + if window == nil || window.state == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + if done == nil { + return fmt.Errorf("windows: window decoration completion callback is required") + } + state := window.state + if state.config.WindowMode != platform.WindowTitled { + return platform.ErrWindowDecorationUnsupported + } + d := &state.decoration + d.mu.Lock() + defer d.mu.Unlock() + if d.closed || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + if d.pending != nil { + return fmt.Errorf("windows: a decoration change is already pending") + } + d.pending = &decorationRequest{decorated: decorated, done: done} + if posted, _, err := postMessage.Call(state.window, wmChangeDecoration, 0, 0); posted == 0 { + d.pending = nil + return fmt.Errorf("windows: post decoration change: %w", err) + } + return nil +} + +func (state *windowState) applyDecoration() { + d := &state.decoration + d.mu.Lock() + request := d.pending + d.mu.Unlock() + if request == nil || d.changing { + return + } + err := state.changeDecoration(request.decorated) + d.mu.Lock() + if d.pending != request { + d.mu.Unlock() + return // destruction already owns this completion + } + d.pending = nil + d.mu.Unlock() + request.done(err) +} + +func (d *windowDecoration) close() *decorationRequest { + d.mu.Lock() + defer d.mu.Unlock() + d.closed = true + request := d.pending + d.pending = nil + return request +} + +func (state *windowState) changeDecoration(decorated bool) error { + hwnd := state.window + visible, _, _ := decorationIsVisible.Call(hwnd) + if !state.ready || visible == 0 || state.iconic() || state.zoomed() || + state.fullscreen.Load() || state.fullscreenChanging || state.sizingMove { + return fmt.Errorf("windows: decorations can change only on a visible normal window") + } + d := &state.decoration + if decorated == !d.removed { + return nil + } + before, err := readDecorationStyle(hwnd, ^uintptr(15)) // GWL_STYLE + if err != nil { + return err + } + extended, err := readDecorationStyle(hwnd, ^uintptr(19)) // GWL_EXSTYLE + if err != nil { + return err + } + client, ok := decorationClientRect(hwnd) + var outer rect + if read, _, _ := getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&outer))); !ok || read == 0 { + return fmt.Errorf("windows: could not read the current window rectangle") + } + after := before &^ wsOverlappedWindow + if decorated { + after = (before &^ wsOverlappedWindow) | d.style + } + target, err := decorationOuterRect(hwnd, client, after, extended) + if err != nil { + return err + } + focus, _, _ := decorationGetFocus.Call() + active, _, _ := decorationGetActive.Call() + d.changing = true + defer func() { d.changing = false }() + if err := state.setFullscreenStyle(after); err != nil { + return err + } + d.removed = !decorated + err = positionDecorationFrame(hwnd, target) + currentStyle, styleErr := readDecorationStyle(hwnd, ^uintptr(15)) + currentExtended, extendedErr := readDecorationStyle(hwnd, ^uintptr(19)) + current, ok := decorationClientRect(hwnd) + newFocus, _, _ := decorationGetFocus.Call() + newActive, _, _ := decorationGetActive.Call() + newVisible, _, _ := decorationIsVisible.Call(hwnd) + if state.window == hwnd && err == nil && styleErr == nil && extendedErr == nil && + ok && current == client && currentStyle == after && currentExtended&wsExTopmost == extended&wsExTopmost && + newFocus == focus && newActive == active && newVisible != 0 { + if !decorated { + d.style = before & wsOverlappedWindow + } + return nil + } + err = errors.Join(err, styleErr, extendedErr, fmt.Errorf("windows: decoration change did not preserve the window")) + d.removed = decorated + if state.window != hwnd { + return err + } + if restoreErr := state.setFullscreenStyle(before); restoreErr != nil { + return errors.Join(err, restoreErr) + } + return errors.Join(err, positionDecorationFrame(hwnd, outer)) +} + +func readDecorationStyle(hwnd, index uintptr) (uint32, error) { + fullscreenClearError.Call(0) + style, _, err := fullscreenGetStyle.Call(hwnd, index) + if style == 0 && err != syscall.Errno(0) { + return 0, fmt.Errorf("windows: get decoration style: %w", err) + } + return uint32(style), nil +} + +func decorationClientRect(hwnd uintptr) (rect, bool) { + var client rect + var origin point + if ok, _, _ := getClientRect.Call(hwnd, uintptr(unsafe.Pointer(&client))); ok == 0 { + return rect{}, false + } + if ok, _, _ := clientToScreen.Call(hwnd, uintptr(unsafe.Pointer(&origin))); ok == 0 { + return rect{}, false + } + return rect{Left: origin.X, Top: origin.Y, Right: origin.X + client.Right, Bottom: origin.Y + client.Bottom}, true +} + +func decorationOuterRect(hwnd uintptr, client rect, style, extended uint32) (rect, error) { + menu, _, _ := decorationGetMenu.Call(hwnd) + if menu != 0 { + return rect{}, platform.ErrWindowDecorationUnsupported + } + frame := rect{Right: client.Right - client.Left, Bottom: client.Bottom - client.Top} + var dpi uintptr + if getDPI.Find() == nil { + dpi, _, _ = getDPI.Call(hwnd) + } + var ok uintptr + var err error + if dpi != 0 && adjustWindow.Find() == nil { + ok, _, err = adjustWindow.Call(uintptr(unsafe.Pointer(&frame)), uintptr(style), 0, uintptr(extended), dpi) + } else { + ok, _, err = adjustWindowLegacy.Call(uintptr(unsafe.Pointer(&frame)), uintptr(style), 0, uintptr(extended)) + } + if ok == 0 { + return rect{}, fmt.Errorf("windows: calculate decorated window rectangle: %w", err) + } + frame.Left += client.Left + frame.Right += client.Left + frame.Top += client.Top + frame.Bottom += client.Top + return frame, nil +} + +func positionDecorationFrame(hwnd uintptr, target rect) error { + const noZOrder, noActivate, frameChanged, noOwnerZOrder = 0x4, 0x10, 0x20, 0x200 + if ok, _, err := setWindowPosition.Call(hwnd, 0, uintptr(target.Left), uintptr(target.Top), + uintptr(target.Right-target.Left), uintptr(target.Bottom-target.Top), noZOrder|noActivate|frameChanged|noOwnerZOrder); ok == 0 { + return fmt.Errorf("windows: apply decoration frame: %w", err) + } + return nil +} diff --git a/internal/platform/windows/window_decoration_windows_test.go b/internal/platform/windows/window_decoration_windows_test.go new file mode 100644 index 000000000..158ba568f --- /dev/null +++ b/internal/platform/windows/window_decoration_windows_test.go @@ -0,0 +1,120 @@ +package windows + +import ( + "fmt" + "runtime" + "testing" + "time" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +func TestNativeWindowDecorationRoundTrip(t *testing.T) { + for _, tc := range []struct { + width, height int + above bool + }{{640, 400, false}, {1280, 800, true}} { + t.Run(fmt.Sprintf("%dx%d", tc.width, tc.height), func(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + var result error + completed := false + err := RunApplication(func(application platform.Application) error { + control, err := application.OpenWindow(platform.Config{Title: "Viva decoration probe", Width: tc.width, Height: tc.height}) + if err != nil { + return err + } + window := control.(*nativeWindow) + hwnd := window.state.window + setFocus.Call(hwnd) + focusProc := user.NewProc("GetFocus") + focus, _, _ := focusProc.Call() + if focus != hwnd { + return fmt.Errorf("test window did not receive keyboard focus") + } + if err := window.SetAlwaysOnTop(tc.above); err != nil { + return err + } + frame, available := window.Frame() + var outer rect + if ok, _, _ := getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&outer))); ok == 0 || !available { + return fmt.Errorf("could not read initial geometry") + } + before, _, _ := fullscreenGetStyle.Call(hwnd, ^uintptr(15)) + finish := func(err error) { + if !completed { + completed, result = true, err + window.Close() + } + } + guard := time.AfterFunc(5*time.Second, func() { application.Post(func() { finish(fmt.Errorf("decoration callback did not run")) }) }) + window.state.config.OnClosed = func() { guard.Stop() } + verify := func(decorated bool) error { + style, _, _ := fullscreenGetStyle.Call(hwnd, ^uintptr(15)) + ex, _, _ := fullscreenGetStyle.Call(hwnd, ^uintptr(19)) + current, available := window.Frame() + focused, _, _ := focusProc.Call() + if window.state.window != hwnd || !available || current != frame || focused != focus || (ex&wsExTopmost != 0) != tc.above { + return fmt.Errorf("geometry, focus, window identity or level changed: frame %v, want %v; focus %#x, want %#x; exstyle %#x", current, frame, focused, focus, ex) + } + if decorated && uint32(style) != uint32(before) || !decorated && style&wsOverlappedWindow != 0 { + return fmt.Errorf("unexpected window style %#x, original %#x, decorated=%t", style, before, decorated) + } + var now rect + if ok, _, _ := getWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&now))); ok == 0 || (now == outer) != decorated { + return fmt.Errorf("outer rectangle %v, original %v, decorated=%t", now, outer, decorated) + } + return nil + } + if err := window.SetDecorated(false, func(err error) { + if err == nil { + err = verify(false) + } + if err != nil { + finish(err) + return + } + if err := window.SetDecorated(true, func(err error) { + if err == nil { + err = verify(true) + } + finish(err) + }); err != nil { + finish(err) + } + }); err != nil { + return err + } + if err := window.SetDecorated(false, func(error) { finish(fmt.Errorf("rejected duplicate completed")) }); err == nil { + return fmt.Errorf("accepted a duplicate request") + } + return nil + }) + if err != nil || result != nil || !completed { + t.Fatalf("Windows decoration round trip: completed=%t, loop=%v, request=%v", completed, err, result) + } + }) + } +} + +func TestNativeWindowDecorationCompletesWhenClosing(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + var outcomes []error + err := RunApplication(func(application platform.Application) error { + control, err := application.OpenWindow(platform.Config{Title: "Viva decoration close probe", Width: 320, Height: 240}) + if err != nil { + return err + } + window := control.(*nativeWindow) + if err := window.SetDecorated(false, func(err error) { outcomes = append(outcomes, err) }); err != nil { + return err + } + destroyWindow.Call(window.state.window) + return nil + }) + if err != nil || len(outcomes) != 1 || outcomes[0] == nil { + t.Fatalf("close before dispatch: loop=%v, completions=%v", err, outcomes) + } +} diff --git a/internal/platform/windows/window_dpi_windows_test.go b/internal/platform/windows/window_dpi_windows_test.go new file mode 100644 index 000000000..af5bdebab --- /dev/null +++ b/internal/platform/windows/window_dpi_windows_test.go @@ -0,0 +1,66 @@ +package windows + +import ( + "runtime" + "syscall" + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// Restoring a window can change monitors before the renderer is initialized. +// Exercise the actual message dispatch with a hidden window, without touching +// the interactive desktop's foreground window or the user's display settings. +func TestDPIChangeBeforeWindowReady(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + class, _ := syscall.UTF16PtrFromString("STATIC") + handle, _, err := createWindow.Call(0, uintptr(unsafe.Pointer(class)), 0, wsPopup, 0, 0, 300, 200, 0, 0, 0, 0) + if handle == 0 { + t.Fatal(err) + } + defer destroyWindow.Call(handle) + previous := active.Load() + defer active.Store(previous) + defer windowStates.Delete(handle) + for _, test := range []struct { + name string + before, want float32 + dpi uint16 + fixed bool + }{ + {"200_to_150", 2, 1.5, 144, false}, + {"150_to_200", 1.5, 2, 192, false}, + {"explicit_override", 1.25, 1.25, 192, true}, + {"zero_dpi_ignored", 1.5, 1.5, 0, false}, + } { + t.Run(test.name, func(t *testing.T) { + resizes := 0 + state := &windowState{window: handle, scale: test.before, scaleFixed: test.fixed, + config: platform.Config{OnResize: func(platform.Size) (platform.Frame, error) { + resizes++ + return platform.Frame{}, nil + }}, + } + state.configureClicks() + windowStates.Store(handle, state) + bounds := rect{Right: 300, Bottom: 200} + windowProc(handle, wmDPIChanged, uintptr(test.dpi)|uintptr(test.dpi)<<16, uintptr(unsafe.Pointer(&bounds))) + if state.scale != test.want { + t.Fatalf("startup scale = %v, want %v", state.scale, test.want) + } + expectedClicks := windowState{scale: test.want} + expectedClicks.configureClicks() + if state.clicks.Distance != expectedClicks.clicks.Distance { + t.Fatalf("click distance = %v, want %v for scale %v", state.clicks.Distance, expectedClicks.clicks.Distance, test.want) + } + if size := state.logicalSize(600, 300); size.Width != 600/test.want || size.Height != 300/test.want || size.Scale != test.want { + t.Fatalf("first logical size = %+v at scale %v", size, test.want) + } + if resizes != 0 || state.ready || state.err != nil { + t.Fatalf("startup DPI change reached the uninitialized renderer: resizes=%d ready=%v err=%v", resizes, state.ready, state.err) + } + }) + } +} diff --git a/internal/platform/windows/window_minimum_windows.go b/internal/platform/windows/window_minimum_windows.go index 0bfff9208..158feb57c 100644 --- a/internal/platform/windows/window_minimum_windows.go +++ b/internal/platform/windows/window_minimum_windows.go @@ -19,7 +19,7 @@ func (state *windowState) minimumTrackSize() point { return point{} } var frame rect - if state.config.WindowMode == platform.WindowTitled { + if state.config.WindowMode == platform.WindowTitled && !state.decoration.removed { if adjustWindow.Find() == nil { adjustWindow.Call(uintptr(unsafe.Pointer(&frame)), wsOverlappedWindow, 0, 0, uintptr(max(state.scale, 1)*96)) } else { diff --git a/internal/platform/windows/window_notification_windows.go b/internal/platform/windows/window_notification_windows.go index 61ca928ce..9ac2c3942 100644 --- a/internal/platform/windows/window_notification_windows.go +++ b/internal/platform/windows/window_notification_windows.go @@ -12,7 +12,11 @@ var monitorEffectiveDPI = syscall.NewLazyDLL("shcore.dll").NewProc("GetDpiForMon func (state *windowState) placeNotification() { config := state.config monitor := cursorMonitor() - if config.HasOrigin { + if config.HasAnchor { + anchor := config.Anchor + x, y := int32(anchor.X+anchor.Width/2), int32(anchor.Y+anchor.Height/2) + monitor, _, _ = monitorFromPoint.Call(uintptr(uint32(x))|uintptr(uint32(y))<<32, monitorNearest) + } else if config.HasOrigin { x, y := int32(config.Origin.X), int32(config.Origin.Y) monitor, _, _ = monitorFromPoint.Call(uintptr(uint32(x))|uintptr(uint32(y))<<32, monitorNearest) } @@ -36,7 +40,9 @@ func (state *windowState) placeNotification() { width := min(float32(int32(float32(config.Width)*scale)), area.Width) height := min(float32(int32(float32(config.Height)*scale)), area.Height) x, y := platform.PlaceNotification(width, height, 12*scale, area) - if config.HasOrigin { + if config.HasAnchor { + x, y = platform.PlacePanel(config.Anchor, width, height, area) + } else if config.HasOrigin { x, y = platform.RestoreNotification(config.Origin.X, config.Origin.Y, width, height, area) } // The selected monitor's DPI is already included. A synchronous diff --git a/internal/platform/windows/window_notification_windows_test.go b/internal/platform/windows/window_notification_windows_test.go index 7ba52ad03..d0c1d062a 100644 --- a/internal/platform/windows/window_notification_windows_test.go +++ b/internal/platform/windows/window_notification_windows_test.go @@ -51,7 +51,7 @@ func TestNotificationNativeWindows(t *testing.T) { if before, _, _ := focus.Call(); before != handle { t.Fatalf("expected original keyboard focus %x, got %x", handle, before) } - clicks := 0 + clicks, exits := 0, 0 popup, err := app.OpenWindow(platform.Config{Title: "Incoming", Width: 336, Height: 136, WindowMode: platform.WindowNotification, PressAt: func(x, _ float32) platform.PressKind { if x < 100 { return platform.PressMove @@ -61,6 +61,9 @@ func TestNotificationNativeWindows(t *testing.T) { if e.Kind == platform.PointerDown { clicks++ } + if e.Kind == platform.PointerExit { + exits++ + } return platform.Frame{}, nil }}) if err != nil { @@ -94,6 +97,10 @@ func TestNotificationNativeWindows(t *testing.T) { if after, _, _ := focus.Call(); after != handle { t.Fatal("interacting with notification stole focus") } + send.Call(hwnd, wmMouseLeave, 0, 0) + if exits != 1 { + t.Fatalf("notification received %d exit event(s)", exits) + } var work monitorInfo work.Size = uint32(unsafe.Sizeof(work)) @@ -102,6 +109,23 @@ func TestNotificationNativeWindows(t *testing.T) { t.Fatal("missing monitor work area") } width, height := native.Right-native.Left, native.Bottom-native.Top + area := platform.ScreenRect{ + X: float32(work.Work.Left), Y: float32(work.Work.Top), + Width: float32(work.Work.Right - work.Work.Left), Height: float32(work.Work.Bottom - work.Work.Top), + } + anchor := platform.ScreenRect{X: area.X + area.Width/2, Y: area.Y + area.Height - 20, Width: 20, Height: 20} + anchored, err := app.OpenWindow(platform.Config{ + Width: 336, Height: 136, WindowMode: platform.WindowNotification, HasAnchor: true, Anchor: anchor, + }) + if err != nil { + return err + } + frame, ok := anchored.Frame() + x, y := platform.PlacePanel(anchor, float32(width), float32(height), area) + anchored.Close() + if !ok || frame.X != float32(int32(x)) || frame.Y != float32(int32(y)) { + t.Fatalf("anchored notification frame = %+v (ok=%v), want %v %v", frame, ok, x, y) + } for _, test := range []struct { name string origin, want point diff --git a/internal/platform/windows/window_size_windows.go b/internal/platform/windows/window_size_windows.go index 34588c19e..f02830ed7 100644 --- a/internal/platform/windows/window_size_windows.go +++ b/internal/platform/windows/window_size_windows.go @@ -37,7 +37,7 @@ func (state *windowState) resizeClient(width, height int) { Bottom: int32(math.Round(float64(height) * float64(scale))), } style := uintptr(wsOverlappedWindow) - if state.config.WindowMode == platform.WindowTitled { + if state.config.WindowMode == platform.WindowTitled && !state.decoration.removed { if adjustWindow.Find() == nil { adjustWindow.Call(uintptr(unsafe.Pointer(&bounds)), style, 0, 0, uintptr(scale*96)) } else { diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index dc5d97a8d..a70c357ec 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -80,6 +80,7 @@ type windowState struct { // pendingTitle is the title SetTitle asked for, applied on the window thread. pendingTitle titleRequest pendingIcon iconRequest + decoration windowDecoration fullscreen atomic.Bool fullscreenChanging bool fullscreenStyle uint32 @@ -214,7 +215,7 @@ type nativeWindow struct { // reportFrame tells the application where its content area is now, in logical // pixels of the window's display. It reports only changes. func (state *windowState) reportFrame() { - if !state.ready || state.config.OnFrameChange == nil || state.window == 0 || state.iconic() || state.zoomed() || state.fullscreen.Load() || state.fullscreenChanging { + if !state.ready || state.config.OnFrameChange == nil || state.window == 0 || state.iconic() || state.zoomed() || state.fullscreen.Load() || state.fullscreenChanging || state.decoration.changing { return } var client rect @@ -523,6 +524,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmFullscreen: state.setFullscreen(first != 0) return 0 + case wmChangeDecoration: + state.applyDecoration() + return 0 case wmSetTitle: state.applyTitle() return 0 @@ -640,6 +644,22 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { if state.customFrame() { return state.calcSize(first, second) } + case wmDPIChanged: + if dpi := uint16(first >> 16); !state.scaleFixed && dpi > 0 { + state.scale = float32(dpi) / 96 + } + state.configureClicks() + // Restoring the initial position can cross monitors before the + // renderer is ready. Keep that monitor's scale for the first frame and + // take the suggested bounds: placement sized the window at the old + // monitor's scale. Nothing is painted or resized yet. + if !state.ready { + if !state.placingNotification { + bounds := (*rect)(pointer(second)) + setWindowPosition.Call(window, 0, uintptr(bounds.Left), uintptr(bounds.Top), uintptr(bounds.Right-bounds.Left), uintptr(bounds.Bottom-bounds.Top), 0x14) + } + return 0 + } } if !state.ready { result, _, _ = defaultWindowProc.Call(window, kind, first, second) @@ -863,10 +883,6 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { state.serviceResize() return 0 case wmDPIChanged: - if !state.scaleFixed { - state.scale = float32(uint16(first>>16)) / 96 - } - state.configureClicks() state.accessibility.setScale(state.scale) bounds := (*rect)(pointer(second)) resizes := state.resizeEvents @@ -1362,6 +1378,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 + if request := state.decoration.close(); request != nil { + defer request.done(fmt.Errorf("windows: window closed before its decoration change completed")) + } killTimer.Call(window, resizeTimerID) if state.timerPeriodSet { timeEndPeriod.Call(1) diff --git a/internal/render/store.go b/internal/render/store.go index e372fac5c..b9cfa11ae 100644 --- a/internal/render/store.go +++ b/internal/render/store.go @@ -83,18 +83,57 @@ type node struct { // this batch and has no instance until the batch finishes flattening it. const freshInstance = uint32(1) << 31 +// unlinked marks, while a batch links its new nodes, the slot of a new node not +// linked yet; the rest of the entry is the index of its change in the batch. +const unlinked = uint32(1) << 30 + type Store struct { nodes []node instanceBySlot []uint32 rectangles []Rectangle // order is the paint order one rebuild computes for the new batch; scratch - // is the walk stack. Both are reused, so their capacity tracks the largest - // page rather than the number of rebuilds. + // is the walk stack. Both are reused from batch to batch; releaseScratch + // gives back what a past large batch left in them. order []scene.ID scratch []scene.ID + // deleted collects the instances a batch removes, and linking is the walk + // stack of the new nodes a batch links; both are reused like order. + deleted []int + linking []int root scene.ID } +// releaseScratch gives back the batch scratch a page that just shrank no longer +// needs, so a one-off peak does not stay for the rest of the session. The +// scratch holds nothing between batches and only ever looks oversized after +// the page shrinks, so this runs then and costs other frames nothing; a page +// that stays large keeps what its batches use and never reallocates. +func (store *Store) releaseScratch() { + page := len(store.rectangles) + if oversized(cap(store.order), page) { + store.order = make([]scene.ID, 0, max(page, minScratch)) + } + if oversized(cap(store.scratch), page) { + store.scratch = make([]scene.ID, 0, max(page, minScratch)) + } + if oversized(cap(store.deleted), page) { + store.deleted = make([]int, 0, max(page, minScratch)) + } + if oversized(cap(store.linking), page) { + store.linking = make([]int, 0, max(page, minScratch)) + } +} + +// minScratch is the capacity batch scratch is given back at; trimAt is the +// capacity below which it is never released. +const minScratch, trimAt = 64, 4096 + +// oversized is the retention rule for batch scratch: past trimAt, it keeps at +// most four times the page it serves. +func oversized(capacity, page int) bool { + return capacity > trimAt && page*4 < capacity +} + // Rectangles returns the current ordered rectangle instances. The result is // invalidated by the next call to Apply. func (store *Store) Rectangles() []Rectangle { @@ -111,9 +150,11 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { return store.deleteBatch(changes) } - oldCount := len(store.rectangles) structureChanged := false - deleted := false + // shrunk is the first instance a delete in the batch removed; the update + // then runs from there to the end of the list, as a delete-only batch's. + shrunk := -1 + before := len(store.rectangles) // appended collects new shape nodes whose insertion may be a pure append // after the last instance. If the chain holds, the store can append them // without rebuilding (and re-uploading) the whole instance list. @@ -122,51 +163,96 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { // rebuild resolves their geometry from this batch instead of the rectangles // the store already holds. var inserted []uint32 - appendOnly := oldCount > 0 // Deletes are applied before upserts. The scene relinks a deleted node's // successor without reporting that successor, so an upsert of it (queued // earlier in the same batch for another reason, such as a new color) carries // the post-delete previous sibling. Applied in queue order it would see the // stale link and be rejected as a structural mutation, dropping the rest of - // the batch. + // the batch. The deleted instances leave the list before anything is + // inserted, so every index below is one in the list the batch ends with. + store.deleted = store.deleted[:0] for _, change := range changes { switch change.Operation { case scene.OperationDelete: - if err := store.remove(change.ID); err != nil { + if err := store.removeInstance(change.ID); err != nil { return Update{}, err } structureChanged = true - deleted = true - appendOnly = false case scene.OperationUpsert: default: return Update{}, fmt.Errorf("render: unsupported operation %d", change.Operation) } } + if len(store.deleted) > 0 { + shrunk = store.compact() + } + oldCount := len(store.rectangles) + appendOnly := oldCount > 0 // New nodes are linked before changed ones are applied. The scene reports a // node's current neighbours, so an existing node's upsert queued before the // insert of its new predecessor already names that predecessor, which the - // store only learns of when it reaches the insert. + // store only learns of when it reaches the insert. A new node can likewise + // name a parent or previous sibling that is new too and queued after it (a + // shape inserted between a new one and its predecessor), so every new node + // is marked first and each is linked after the new nodes it names. Parents + // and previous siblings form a tree and lists, so the walk ends; a batch + // that names a cycle is rejected. + fresh := 0 for index, change := range changes { if change.Operation != scene.OperationUpsert || store.exists(change.ID) { continue } - if _, _, err := store.upsert(change); err != nil { - return Update{}, err + slot, ok := change.ID.Slot() + if !ok { + return Update{}, fmt.Errorf("render: invalid node ID %d", change.ID) } - if change.Kind != scene.KindGroup { - slot, _ := change.ID.Slot() - store.instanceBySlot[slot] = freshInstance | uint32(len(inserted)) - inserted = append(inserted, uint32(index)) + store.ensureSlots(slot) + store.instanceBySlot[slot] = unlinked | uint32(index) + fresh++ + } + for index := 0; fresh > 0 && index < len(changes); index++ { + if store.unlinkedChange(changes, changes[index].ID) < 0 { + continue } - structureChanged = true - if change.Kind == scene.KindGroup || change.Parent != store.root { - appendOnly = false - } else { - appended = append(appended, change) + stack := append(store.linking[:0], index) + for len(stack) > 0 { + if len(stack) > len(changes) { + return Update{}, fmt.Errorf("render: node %d is placed after or inside itself", changes[stack[0]].ID) + } + top := stack[len(stack)-1] + change := changes[top] + if dependency := store.unlinkedChange(changes, change.Parent); dependency >= 0 { + stack = append(stack, dependency) + continue + } + if dependency := store.unlinkedChange(changes, change.PreviousSibling); dependency >= 0 { + stack = append(stack, dependency) + continue + } + stack = stack[:len(stack)-1] + if store.unlinkedChange(changes, change.ID) < 0 { + continue // linked already, as the dependency of another + } + if _, _, err := store.upsert(change); err != nil { + return Update{}, err + } + fresh-- + slot, _ := change.ID.Slot() + store.instanceBySlot[slot] = 0 + if change.Kind != scene.KindGroup { + store.instanceBySlot[slot] = freshInstance | uint32(len(inserted)) + inserted = append(inserted, uint32(top)) + } + structureChanged = true + if change.Kind == scene.KindGroup || change.Parent != store.root { + appendOnly = false + } else { + appended = append(appended, change) + } } + store.linking = stack } first := oldCount @@ -217,13 +303,13 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { if first > oldCount { first = oldCount } - case !deleted && len(appended) > 0 && oldCount > 0: + case len(appended) > 0 && len(appended) == len(inserted) && oldCount > 0: // Insertions in the middle of the page move the tail of paint // order, but the scene's neighbour links say exactly where each // new shape goes. Splicing it in and renumbering the slots after // it costs one shift of the instance list instead of re-flattening - // and re-uploading the whole page. Deletions still rebuild, - // because every backend's retained store is sized to the count. + // and re-uploading the whole page. A shape inserted inside a group + // is placed by the rebuild below. for _, change := range appended { at := 0 if change.PreviousSibling != 0 { @@ -248,6 +334,8 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { if last < len(store.rectangles)-1 { last = len(store.rectangles) - 1 } + case len(appended) == 0 && len(inserted) == 0 && shrunk >= 0: + // Only deletes, alongside changes to shapes that stay. default: if err := store.rebuild(changes, inserted); err != nil { return Update{}, err @@ -255,6 +343,12 @@ func (store *Store) Apply(changes []scene.Change) (Update, error) { return Update{Count: len(store.rectangles), Rebuild: true}, nil } } + if shrunk >= 0 { + // Everything after the first removed instance moved: send it all, and + // let a backend truncate when the list ended shorter than it began. + first = min(first, shrunk) + return Update{First: first, Count: len(store.rectangles) - first, Shrink: len(store.rectangles) < before}, nil + } if last < first { return Update{}, nil } @@ -275,31 +369,50 @@ func changesAreDeletes(changes []scene.Change) bool { } func (store *Store) deleteBatch(changes []scene.Change) (Update, error) { - var instances []int + store.deleted = store.deleted[:0] for _, change := range changes { - slot, ok := change.ID.Slot() - if !ok || int(slot) >= len(store.nodes) { - return Update{}, fmt.Errorf("render: delete references invalid node %d", change.ID) - } - if instance := store.instanceIndex(slot, change.ID); instance >= 0 { - instances = append(instances, instance) - } - if err := store.remove(change.ID); err != nil { + if err := store.removeInstance(change.ID); err != nil { return Update{}, err } } - if len(instances) == 0 { + if len(store.deleted) == 0 { return Update{}, nil } - slices.Sort(instances) - first := instances[0] - for index := len(instances) - 1; index >= 0; index-- { - at := instances[index] - copy(store.rectangles[at:], store.rectangles[at+1:]) - store.rectangles = store.rectangles[:len(store.rectangles)-1] + first := store.compact() + return Update{First: first, Count: len(store.rectangles) - first, Shrink: true}, nil +} + +// removeInstance removes node id and notes its instance, if it has one, in +// deleted for compact. +func (store *Store) removeInstance(id scene.ID) error { + slot, ok := id.Slot() + if !ok || int(slot) >= len(store.nodes) { + return fmt.Errorf("render: delete references invalid node %d", id) + } + if instance := store.instanceIndex(slot, id); instance >= 0 { + store.deleted = append(store.deleted, instance) + } + return store.remove(id) +} + +// compact drops the instances in deleted from the list in one pass, renumbers +// the slots after the first of them, and returns it. +func (store *Store) compact() int { + slices.Sort(store.deleted) + first := store.deleted[0] + write, next := first, 0 + for read := first; read < len(store.rectangles); read++ { + if next < len(store.deleted) && store.deleted[next] == read { + next++ + continue + } + store.rectangles[write] = store.rectangles[read] + write++ } + store.rectangles = store.rectangles[:write] store.reindexFrom(first) - return Update{First: first, Count: len(store.rectangles) - first, Shrink: true}, nil + store.releaseScratch() + return first } // rectangleOf is the render instance a scene change describes. @@ -331,6 +444,24 @@ func (store *Store) reindexFrom(index int) { } } +// unlinkedChange is the index in changes of the new node id when the batch has +// not linked it yet, or -1. +func (store *Store) unlinkedChange(changes []scene.Change, id scene.ID) int { + slot, ok := id.Slot() + if !ok || int(slot) >= len(store.nodes) || store.nodes[slot].alive { + return -1 + } + encoded := store.instanceBySlot[slot] + if encoded&unlinked == 0 || encoded&freshInstance != 0 { + return -1 + } + index := int(encoded &^ unlinked) + if index >= len(changes) || changes[index].ID != id { + return -1 + } + return index +} + // exists reports whether the store already holds the node with this identity. func (store *Store) exists(id scene.ID) bool { slot, ok := id.Slot() diff --git a/internal/render/store_bench_test.go b/internal/render/store_bench_test.go index 636e07924..2d193049d 100644 --- a/internal/render/store_bench_test.go +++ b/internal/render/store_bench_test.go @@ -28,10 +28,10 @@ func BenchmarkStoreAppendTail(b *testing.B) { } } -// Deleting one instance from a large page still rebuilds every instance, -// because the backends keep a store sized to the count. Measure that fallback -// so an incremental delete can be compared against it. -func BenchmarkStoreDeleteRebuild(b *testing.B) { +// Deleting one instance from the middle of a large page and appending another +// in the same batch compacts the list and sends the suffix from the deleted +// instance, rather than re-flattening the page. +func BenchmarkStoreDeleteAndAppend(b *testing.B) { graph := scene.NewWithCapacity(10_001) var id scene.ID for index := 0; index < 10000; index++ { @@ -56,8 +56,8 @@ func BenchmarkStoreDeleteRebuild(b *testing.B) { } id = next update, err := store.Apply(graph.DrainChanges(nil)) - if err != nil || !update.Rebuild { - b.Fatalf("delete update = %+v, err %v", update, err) + if err != nil || update.Rebuild { + b.Fatalf("delete and append update = %+v, err %v", update, err) } } } diff --git a/internal/render/store_test.go b/internal/render/store_test.go index 58ba2bcac..efeec5411 100644 --- a/internal/render/store_test.go +++ b/internal/render/store_test.go @@ -1,6 +1,8 @@ package render import ( + "math/rand" + "slices" "testing" "github.com/vivaui/viva/internal/scene" @@ -167,8 +169,9 @@ func TestStoreAcceptsSuccessorUpsertQueuedBeforeItsPredecessorsDelete(t *testing if err != nil { t.Fatalf("apply: %v", err) } - if !update.Rebuild { - t.Fatalf("update = %+v, want a rebuild after a delete", update) + // Everything from the deleted instance on moved, and the list is shorter. + if update != (Update{First: 1, Count: 2, Shrink: true}) { + t.Fatalf("update = %+v, want the suffix from the deleted instance, shrunk", update) } rectangles := store.Rectangles() if len(rectangles) != 3 || rectangles[0].ID != kept || rectangles[1].ID != successor || rectangles[2].ID != tail { @@ -375,7 +378,8 @@ func TestStoreDeletesOneShapeAndInsertsAnotherBeforeIt(t *testing.T) { if err != nil { t.Fatal(err) } - if !update.Rebuild { + // One instance left and one took its place: the suffix from there, same length. + if update != (Update{First: 1, Count: 2}) { t.Fatalf("delete plus insert update = %+v", update) } rectangles := store.Rectangles() @@ -430,3 +434,185 @@ func TestStoreDeletesNonContiguousInstancesInOrder(t *testing.T) { t.Fatalf("remaining = %+v", got) } } + +// storeModel is the tree a random test builds alongside a scene: the paint +// order the store must end each batch in is its depth-first walk. +type storeModel struct { + id scene.ID + group bool + color scene.Color + children []*storeModel +} + +func (model *storeModel) walk(visit func(parent, node *storeModel)) { + for _, child := range model.children { + visit(model, child) + if child.group { + child.walk(visit) + } + } +} + +// TestStoreUpdatesKeepABackendInStep applies random batches of appends, +// insertions, deletions, recolors and groups, and checks after each one that +// the store holds the scene's paint order and that a backend which applies only +// the reported Update (rebuild, or a range that may grow the list or be cut +// short with Shrink) holds exactly the store's instances. +func TestStoreUpdatesKeepABackendInStep(t *testing.T) { + random := rand.New(rand.NewSource(7)) + graph := scene.New() + root := &storeModel{id: graph.Root(), group: true} + var store Store + var backend []Rectangle + color := func() scene.Color { return scene.Color{Red: float32(random.Intn(1000)), Alpha: 1} } + pick := func(groups bool) (parent, node *storeModel, index int) { + var parents, nodes []*storeModel + root.walk(func(p, n *storeModel) { + if groups || !n.group { + parents, nodes = append(parents, p), append(nodes, n) + } + }) + if len(nodes) == 0 { + return nil, nil, -1 + } + at := random.Intn(len(nodes)) + return parents[at], nodes[at], slices.Index(parents[at].children, nodes[at]) + } + groupOf := func() *storeModel { + groups := []*storeModel{root} + root.walk(func(_, n *storeModel) { + if n.group { + groups = append(groups, n) + } + }) + return groups[random.Intn(len(groups))] + } + for batch := 0; batch < 3000; batch++ { + for operations := 1 + random.Intn(5); operations > 0; operations-- { + switch random.Intn(6) { + case 0, 1: // insert a shape after a random sibling, or first + parent := groupOf() + at := random.Intn(len(parent.children) + 1) + previous := scene.ID(0) + if at > 0 { + previous = parent.children[at-1].id + } + shade := color() + id, ok := graph.InsertRoundedRectangle(parent.id, previous, scene.Rect{Width: 1}, shade, 0) + if !ok { + t.Fatal("insert failed") + } + parent.children = slices.Insert(parent.children, at, &storeModel{id: id, color: shade}) + case 2: // remove a shape or a whole group + if parent, node, index := pick(true); node != nil { + if !graph.Remove(node.id) { + t.Fatal("remove failed") + } + parent.children = slices.Delete(parent.children, index, index+1) + } + case 3, 4: // recolor a shape + if _, node, _ := pick(false); node != nil { + node.color.Red++ // a change, which the scene queues + if !graph.SetRectangle(node.id, scene.Rect{Width: 1}, node.color) { + t.Fatal("recolor failed") + } + } + case 5: // a group holding a few shapes, at the end of the page + id, ok := graph.AddGroup(graph.Root()) + if !ok { + t.Fatal("group failed") + } + group := &storeModel{id: id, group: true} + for count := random.Intn(3); count > 0; count-- { + shade := color() + child, _ := graph.AddRectangle(id, scene.Rect{Width: 1}, shade) + group.children = append(group.children, &storeModel{id: child, color: shade}) + } + root.children = append(root.children, group) + } + } + + update, err := store.Apply(graph.DrainChanges(nil)) + if err != nil { + t.Fatalf("batch %d: %v", batch, err) + } + rectangles := store.Rectangles() + switch { + case update.Rebuild: + backend = append(backend[:0], rectangles...) + case update.Count > 0 || update.Shrink: + if end := update.First + update.Count; end > len(backend) { + backend = append(backend, make([]Rectangle, end-len(backend))...) + } + copy(backend[update.First:], rectangles[update.First:update.First+update.Count]) + if update.Shrink { + backend = backend[:len(rectangles)] + } + } + if !slices.Equal(backend, rectangles) { + t.Fatalf("batch %d: update %+v left the backend with %d instances, the store %d", batch, update, len(backend), len(rectangles)) + } + var want []*storeModel + root.walk(func(_, n *storeModel) { + if !n.group { + want = append(want, n) + } + }) + if len(rectangles) != len(want) { + t.Fatalf("batch %d: %d instances, want %d", batch, len(rectangles), len(want)) + } + for index, node := range want { + if rectangles[index].ID != node.id || rectangles[index].Color != node.color { + t.Fatalf("batch %d: instance %d is %d %v, want %d %v", batch, index, rectangles[index].ID, rectangles[index].Color, node.id, node.color) + } + } + } +} + +// Deleting most of a large page gives back the batch scratch that page needed, +// once the page left is small. +func TestStoreReleasesTheScratchOfAPageThatShrank(t *testing.T) { + graph := scene.NewWithCapacity(20_001) + ids := make([]scene.ID, 0, 20_000) + for index := 0; index < 20_000; index++ { + id, _ := graph.AddRectangle(graph.Root(), scene.Rect{X: float32(index)}, scene.Color{Alpha: 1}) + ids = append(ids, id) + } + var store Store + if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { + t.Fatal(err) + } + for _, id := range ids[1:] { + graph.Remove(id) + } + if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { + t.Fatal(err) + } + if cap(store.deleted) > 4096 { + t.Fatalf("the store keeps %d scratch for a one-shape page", cap(store.deleted)) + } +} + +// A page that stays large keeps the scratch its batches use, so its next large +// batch does not allocate again. +func TestStoreKeepsTheScratchOfAPageThatStaysLarge(t *testing.T) { + graph := scene.NewWithCapacity(20_001) + ids := make([]scene.ID, 0, 20_000) + for index := 0; index < 20_000; index++ { + id, _ := graph.AddRectangle(graph.Root(), scene.Rect{X: float32(index)}, scene.Color{Alpha: 1}) + ids = append(ids, id) + } + var store Store + if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { + t.Fatal(err) + } + for _, id := range ids[:10_000] { + graph.Remove(id) + } + if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { + t.Fatal(err) + } + if cap(store.deleted) < 10_000 { + t.Fatalf("the store dropped the scratch of a %d-instance page: %d", len(store.Rectangles()), cap(store.deleted)) + } +} diff --git a/style/moved_types.go b/style/moved_types.go index c95a17e16..654735e5e 100644 --- a/style/moved_types.go +++ b/style/moved_types.go @@ -14,6 +14,7 @@ type MenuItemPaint struct { Theme gfx.Theme Bounds gfx.Rect Label string + Mnemonic string Description string Shortcut string Checked bool diff --git a/text/editor.go b/text/editor.go index 60b6d899f..f1d664c19 100644 --- a/text/editor.go +++ b/text/editor.go @@ -68,6 +68,12 @@ type textChange struct { // thread, where native input and painting run. Read a string snapshot there // before starting background work; the returned string remains valid after edits. type Editor struct { + // OnDeleteAtEdge runs when DeleteBackward finds nothing before the caret to + // remove (forward false) or DeleteForward finds nothing after it (forward + // true): Backspace in an empty field, which a tag input takes as "remove the + // last tag". It runs on the event-loop thread; nil leaves the key a no-op. + OnDeleteAtEdge func(forward bool) + runes runeStore anchor int caret int @@ -442,6 +448,9 @@ func (editor *Editor) DeleteBackward() bool { editor.releaseCompositionHistory() caret := editor.caret if caret == 0 { + if editor.OnDeleteAtEdge != nil { + editor.OnDeleteAtEdge(false) + } return false } start := editor.runes.Prev(caret) @@ -466,6 +475,9 @@ func (editor *Editor) DeleteForward() bool { editor.releaseCompositionHistory() caret := editor.caret if caret == editor.runes.Len() { + if editor.OnDeleteAtEdge != nil { + editor.OnDeleteAtEdge(true) + } return false } end := editor.runes.Next(caret) diff --git a/text/editor_test.go b/text/editor_test.go index c25b3bd9b..8defae4cb 100644 --- a/text/editor_test.go +++ b/text/editor_test.go @@ -640,3 +640,22 @@ func TestArrowKeysAreMonotonicOnTheScreenInMixedText(t *testing.T) { } } } + +func TestDeleteAtTheEdgeIsReportedOnlyWhenNothingIsRemoved(t *testing.T) { + var editor Editor + var edges []bool + editor.OnDeleteAtEdge = func(forward bool) { edges = append(edges, forward) } + if editor.DeleteBackward() || editor.DeleteForward() { + t.Fatal("an empty editor deleted something") + } + if len(edges) != 2 || edges[0] || !edges[1] { + t.Fatalf("edges = %v, want [false true]", edges) + } + editor.Insert("ab") + editor.DeleteBackward() + editor.SetSelection(Range{Start: 0, End: 0}) + editor.DeleteForward() + if len(edges) != 2 { + t.Fatalf("a delete that removed text was reported as an edge: %v", edges) + } +} diff --git a/text/store.go b/text/store.go index baf3d6f66..ce6802f84 100644 --- a/text/store.go +++ b/text/store.go @@ -7,32 +7,39 @@ import ( "strings" "unicode/utf8" + "github.com/vivaui/viva/internal/bidi" "github.com/vivaui/viva/internal/grapheme" ) // runeStore is the editor's text: what Range, Caret and Selection count in runes, // held as UTF-8 in leaves of about leafBytes bytes (ADR 0092). Each leaf knows how -// many runes, UTF-16 units and newlines it holds, and running totals over the -// leaves turn a rune index into a byte offset, a UTF-16 offset or a line in a -// binary search and a walk inside one leaf. An edit rewrites the leaves it -// touches, not the text after it. The editor reads and changes the text only -// through these methods. +// many runes, UTF-16 units, newlines and characters that need bidirectional +// processing it holds, and running totals over the leaves turn a rune index into +// a byte offset, a UTF-16 offset or a line in a binary search and a walk inside +// one leaf. An edit rewrites the leaves it touches, not the text after it. The +// editor reads and changes the text only through these methods. type runeStore struct { leaves []storeLeaf // sums[i] is the totals before leaf i, valid for i <= summed; an edit lowers // summed to the first leaf it touched and sums are made again from there // when next asked for. - sums []storeSums - summed int - total storeSums - cursor storeCursor - scratch []byte - boundaries []rune + sums []storeSums + summed int + total storeSums + // bidi is how many characters of the text bidi.NeedsBidiRune reports, the + // sum of the leaves' counts. No running total of it is kept: it only ever + // answers whether the whole text has one. + bidi int + cursor storeCursor + // read is the leaf storeText read last. + read int + scratch []byte } type storeLeaf struct { text []byte sizes storeSums + bidi int } type storeSums struct{ runes, bytes, units, newlines int } @@ -60,6 +67,7 @@ func newRuneStore(value string) (store runeStore, valid bool) { } for index := range store.leaves { store.total.add(store.leaves[index].sizes) + store.bidi += store.leaves[index].bidi } return store, valid } @@ -73,6 +81,11 @@ func (store *runeStore) Bytes() int { return store.total.bytes } // Newlines is how many newline runes the text holds. func (store *runeStore) Newlines() int { return store.total.newlines } +// NeedsBidi reports whether the text holds a character that can need +// bidirectional processing (bidi.NeedsBidiRune). Text without one is read left +// to right throughout, so a caller can skip the bidi algorithm for every line. +func (store *runeStore) NeedsBidi() bool { return store.bidi > 0 } + // At is the rune at index. func (store *runeStore) At(index int) rune { leaf, offset := store.seek(index) @@ -261,45 +274,88 @@ func (store *runeStore) Line(index int) int { var newline = []byte{'\n'} // Next is the grapheme cluster boundary after start; Prev the one before end. -// A cluster is found in a window of the runes around it, with the context on -// both sides the rules read, widened for a cluster longer than the window. +// The rules read the leaves in place, with as much context on either side as +// they ask for. func (store *runeStore) Next(start int) int { - // Between two ASCII runes other than CR LF there is always a boundary. - if start >= 0 && start < store.Len() && store.At(start) < utf8.RuneSelf { - if start+1 == store.Len() { - return start + 1 - } - if next := store.At(start + 1); next < utf8.RuneSelf && (next != '\n' || store.At(start) != '\r') { - return start + 1 - } - } - for width := 64; ; width *= 4 { - from, to := max(start-width, 0), min(start+width, store.Len()) - store.boundaries = store.AppendSlice(store.boundaries[:0], from, to) - next := grapheme.NextRunes(store.boundaries, start-from) + from - if next < to || to == store.Len() { - return next - } + if start >= store.Len() { + return store.Len() } + start = max(start, 0) + text := store.graphemeText() + from := store.ByteOffset(start) + return start + text.runes(from, grapheme.NextIn(text, from)) } func (store *runeStore) Prev(end int) int { - if end > 0 && end <= store.Len() && store.At(end-1) < utf8.RuneSelf { - if end == 1 { - return 0 - } - if previous := store.At(end - 2); previous < utf8.RuneSelf && (previous != '\r' || store.At(end-1) != '\n') { - return end - 1 - } + if end <= 0 { + return 0 } - for width := 64; ; width *= 4 { - from, to := max(end-width, 0), min(end+width, store.Len()) - store.boundaries = store.AppendSlice(store.boundaries[:0], from, to) - previous := grapheme.PrevRunes(store.boundaries, end-from) + from - if previous > from || from == 0 { - return previous - } + end = min(end, store.Len()) + text := store.graphemeText() + to := store.ByteOffset(end) + return end - text.runes(grapheme.PrevIn(text, to), to) +} + +// storeText is the store read as a grapheme.Source: offsets are byte offsets +// in the text, and the store's read leaf is the one last read, so the runes the +// rules read around one place cost no search. Leaves are cut on rune boundaries +// and hold valid UTF-8, so a rune never spans two of them. +type storeText runeStore + +func (store *runeStore) graphemeText() *storeText { + store.sum(len(store.leaves)) + return (*storeText)(store) +} + +func (text *storeText) Len() int { return text.total.bytes } + +func (text *storeText) At(offset int) (rune, int) { + bytes := text.find(offset)[offset-text.sums[text.read].bytes:] + if bytes[0] < utf8.RuneSelf { + return rune(bytes[0]), 1 } + return utf8.DecodeRune(bytes) +} + +func (text *storeText) Before(offset int) (rune, int) { + bytes := text.find(offset - 1)[:offset-text.sums[text.read].bytes] + if last := bytes[len(bytes)-1]; last < utf8.RuneSelf { + return rune(last), 1 + } + return utf8.DecodeLastRune(bytes) +} + +// find makes the read leaf the one holding byte offset and returns its text. The rules +// walk from a place to its neighbours, so the leaf last read and the ones beside +// it are tried before a search. +func (text *storeText) find(offset int) []byte { + sums, leaves := text.sums, text.leaves + holds := func(leaf int) bool { + return leaf >= 0 && leaf < len(leaves) && sums[leaf].bytes <= offset && offset < sums[leaf+1].bytes + } + switch { + case holds(text.read): + case holds(text.read + 1): + text.read++ + case holds(text.read - 1): + text.read-- + default: + text.read = sort.Search(len(leaves), func(i int) bool { return sums[i+1].bytes > offset }) + } + return leaves[text.read].text +} + +// runes counts the runes in bytes [from, to), both offsets of rune starts. +func (text *storeText) runes(from, to int) int { + count := 0 + for from < to { + leaf := text.find(from) + begin := text.sums[text.read].bytes + piece := leaf[from-begin : min(len(leaf), to-begin)] + count += utf8.RuneCount(piece) + from += len(piece) + } + return count } // Replace makes runes [start, end) replacement. @@ -313,6 +369,7 @@ func (store *runeStore) Replace(start, end int, replacement []rune) { store.leaves = splitLeaves(encoded) for index := range store.leaves { store.total.add(store.leaves[index].sizes) + store.bidi += store.leaves[index].bidi } return } @@ -323,12 +380,15 @@ func (store *runeStore) Replace(start, end int, replacement []rune) { // only leaf stays when it is emptied, ready for the next text. leaf := &store.leaves[first] if size := len(leaf.text) - (endOffset - startOffset) + len(encoded); (size > 0 || len(store.leaves) == 1) && size <= 2*leafBytes { - removed, added := measure(leaf.text[startOffset:endOffset]), measure(encoded) + removed, removedBidi := measure(leaf.text[startOffset:endOffset]) + added, addedBidi := measure(encoded) leaf.text = slices.Replace(leaf.text, startOffset, endOffset, encoded...) leaf.sizes.sub(removed) leaf.sizes.add(added) + leaf.bidi += addedBidi - removedBidi store.total.sub(removed) store.total.add(added) + store.bidi += addedBidi - removedBidi store.edited(first, startOffset) return } @@ -347,9 +407,11 @@ func (store *runeStore) Replace(start, end int, replacement []rune) { made := splitLeaves(buffer) for index := first; index < last; index++ { store.total.sub(store.leaves[index].sizes) + store.bidi -= store.leaves[index].bidi } for index := range made { store.total.add(made[index].sizes) + store.bidi += made[index].bidi } store.leaves = slices.Replace(store.leaves, first, last, made...) store.edited(first, 0) @@ -381,25 +443,36 @@ func splitLeaves[T string | []byte](text T) []storeLeaf { size++ } chunk := append([]byte(nil), text[:size]...) - leaves = append(leaves, storeLeaf{text: chunk, sizes: measure(chunk)}) + sizes, bidi := measure(chunk) + leaves = append(leaves, storeLeaf{text: chunk, sizes: sizes, bidi: bidi}) text = text[size:] } return leaves } -// measure counts text's runes, bytes, UTF-16 units and newlines. -func measure(text []byte) storeSums { - sizes := storeSums{bytes: len(text)} +// measure counts text's runes, bytes, UTF-16 units and newlines, and the +// characters in it that need bidirectional processing. +func measure(text []byte) (sizes storeSums, bidiRunes int) { + sizes = storeSums{bytes: len(text)} for i := 0; i < len(text); { + if c := text[i]; c < utf8.RuneSelf { + sizes.runes++ + sizes.units++ + if c == '\n' { + sizes.newlines++ + } + i++ + continue + } r, size := utf8.DecodeRune(text[i:]) sizes.runes++ sizes.units += utf16Len(r) - if r == '\n' { - sizes.newlines++ + if bidi.NeedsBidiRune(r) { + bidiRunes++ } i += size } - return sizes + return sizes, bidiRunes } func (sums *storeSums) sub(other storeSums) { diff --git a/text/store_test.go b/text/store_test.go index 80c54d70f..f7ff52a2a 100644 --- a/text/store_test.go +++ b/text/store_test.go @@ -8,6 +8,7 @@ import ( "unicode/utf16" "unicode/utf8" + "github.com/vivaui/viva/internal/bidi" "github.com/vivaui/viva/internal/grapheme" ) @@ -15,7 +16,7 @@ import ( // boundaries and with text that is not UTF-8, and checks every way the editor // reads the store against the runes. func TestRuneStoreAgreesWithRunes(t *testing.T) { - alphabet := []rune{'a', 'b', ' ', '\n', '\r', 'é', '中', '😀', 0x301, 0x200d, 0x1f3fd, 0xd800, -1, utf8.MaxRune + 1} + alphabet := []rune{'a', 'b', ' ', '\n', '\r', 'é', '中', '😀', 0x301, 0x200d, 0x1f3fd, 0x1f1e8, 'א', 0x2067, 0xd800, -1, utf8.MaxRune + 1} random := rand.New(rand.NewSource(1)) piece := func(limit int) []rune { runes := make([]rune, random.Intn(limit)) @@ -56,6 +57,9 @@ func TestRuneStoreAgreesWithRunes(t *testing.T) { if store.Newlines() != countLabelLF(want) { t.Fatalf("step %d: %d newlines, want %d", step, store.Newlines(), countLabelLF(want)) } + if store.NeedsBidi() != bidi.NeedsBidi(string(want)) { + t.Fatalf("step %d: NeedsBidi = %v for %q", step, store.NeedsBidi(), string(want)) + } for probe := 0; probe < 8; probe++ { index := random.Intn(len(want) + 1) bytes := len(string(want[:index])) @@ -112,6 +116,26 @@ func TestRuneStoreAgreesWithRunes(t *testing.T) { } } +// A cluster's boundaries can depend on every rune before it: whether a +// regional indicator ends a flag is the parity of the whole run. Next and Prev +// read the leaves in place, so a run longer than a leaf answers as the runes do. +func TestRuneStoreClustersReadTheWholeContext(t *testing.T) { + run := []rune(strings.Repeat("\U0001F1E8", 3*leafBytes/4+1)) + run = append([]rune("a"), run...) + store, _ := newRuneStore(string(run)) + if len(store.leaves) < 2 { + t.Fatalf("the run fits one leaf (%d bytes)", store.Bytes()) + } + for index := 0; index <= len(run); index++ { + if got, want := store.Next(index), grapheme.NextRunes(run, index); got != want { + t.Fatalf("cluster after %d ends at %d, want %d", index, got, want) + } + if got, want := store.Prev(index), grapheme.PrevRunes(run, index); got != want { + t.Fatalf("cluster before %d starts at %d, want %d", index, got, want) + } + } +} + // TestRuneStoreRollbackAgreesWithRunes checks the rolled-back reading the input // method planner uses against the runes it stands for. func TestRuneStoreRollbackAgreesWithRunes(t *testing.T) { diff --git a/text/visual.go b/text/visual.go index 4f9cba362..6628948ef 100644 --- a/text/visual.go +++ b/text/visual.go @@ -34,6 +34,9 @@ func (editor *Editor) stepRight(caret int) int { // to the boundary with the next place along the screen; boundaries drawn at the same place // are one stop. func (editor *Editor) visualStep(caret, direction int) (int, bool) { + if !editor.runes.NeedsBidi() { + return 0, false // no line of the text reads other than left to right + } lineStart, lineEnd := editor.runes.LineStart(caret), editor.runes.LineEnd(caret) lineOffset := editor.runes.ByteOffset(lineStart) line := editor.String()[lineOffset:editor.runes.ByteOffset(lineEnd)] diff --git a/tools/docs/catalog_test.go b/tools/docs/catalog_test.go index c0ad678e7..4215abb5c 100644 --- a/tools/docs/catalog_test.go +++ b/tools/docs/catalog_test.go @@ -486,6 +486,11 @@ func TestPageSnippetsHaveNoUndeclaredNames(t *testing.T) { "imagepreview": true, "mentions": true, "tour": true, + "overflowlist": true, + "statistic": true, + "inputtag": true, + "autocomplete": true, + "indicator": true, "questionnaire": true, "inputotp": true, "inputgroup": true, @@ -683,6 +688,11 @@ func TestModelFreePageSnippetsCompile(t *testing.T) { "imagepreview": "github.com/vivaui/viva/ui/imagepreview", "mentions": "github.com/vivaui/viva/ui/mentions", "tour": "github.com/vivaui/viva/ui/tour", + "overflowlist": "github.com/vivaui/viva/ui/overflowlist", + "statistic": "github.com/vivaui/viva/ui/statistic", + "inputtag": "github.com/vivaui/viva/ui/inputtag", + "autocomplete": "github.com/vivaui/viva/ui/autocomplete", + "indicator": "github.com/vivaui/viva/ui/indicator", "sidebar": "github.com/vivaui/viva/ui/sidebar", "multiselect": "github.com/vivaui/viva/ui/multiselect", "hierarchypicker": "github.com/vivaui/viva/ui/hierarchypicker", } diff --git a/ui/autocomplete/autocomplete.go b/ui/autocomplete/autocomplete.go new file mode 100644 index 000000000..b0d678fe7 --- /dev/null +++ b/ui/autocomplete/autocomplete.go @@ -0,0 +1,210 @@ +// Package autocomplete is the opt-in page control for a text field that suggests +// completions while the user types: a list of the options that contain what was +// typed opens under the field, and choosing one writes it into the field. Unlike a +// Combobox, the value stays free text: the user may type something that is in no +// option and keep it. A page keeps the field's value in a ui.Field and an +// Autocomplete in its model: +// +// m.host = autocomplete.New() +// // in the page: +// m.host.View(c, &m.hostField, "Host", "Hostname", autocomplete.Spec{Options: m.known}) +// if option, ok := m.host.Chosen(); ok { +// // the field already holds option +// } +// +// The list opens while the field has the keyboard and something is typed that at +// least one option contains, without regard to case, and an option equal to the +// text is not offered. Up and Down move through the options, Enter and Tab choose +// the highlighted one, and Escape closes the list until the text changes. Without +// a highlighted option Enter is left to the page, so it still submits a form. A +// press on an option chooses it without taking the keyboard from the field. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an Autocomplete in the model beside its field. Do not copy +// one after it has been declared. +package autocomplete + +import ( + "unicode" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" +) + +// Spec declares the list. +type Spec struct { + // Options are the completions on offer, in the order the list shows the ones + // that match. Keep the slice in the model. + Options []string + // MaxRows is how many options the list shows at most; 6 when zero. + MaxRows int +} + +// Autocomplete is one field's list. +type Autocomplete struct { + open bool + matches []int + highlight int // the row highlighted, or -1 until a key moves it + typed string + dismissed string // the text Escape closed the list for + pending int // 1 + the option chosen since the last paint, or 0 + chosen int + spec Spec + field *ui.Field + id gfx.ID + fieldID gfx.ID + key func(gfx.KeyEvent) gfx.EventResult +} + +// New returns a closed list. +func New() *Autocomplete { + a := &Autocomplete{highlight: -1} + a.key = a.onKey + return a +} + +// FieldID names the field with an identity the application already holds, for a +// runner that resolves the platform text service by an application identity. +func (a *Autocomplete) FieldID(id gfx.ID) *Autocomplete { a.fieldID = id; return a } + +// Chosen reports the option the user chose since the paint before this one. +func (a *Autocomplete) Chosen() (string, bool) { + if a.chosen == 0 { + return "", false + } + return a.spec.Options[a.chosen-1], true +} + +// containsFold reports whether s has query in it, without regard to case. +func containsFold(s, query string) bool { + if query == "" { + return true + } + for i := range s { + rest, q := s[i:], query + for q != "" && rest != "" { + x, xs := utf8.DecodeRuneInString(rest) + y, ys := utf8.DecodeRuneInString(q) + if unicode.ToLower(x) != unicode.ToLower(y) { + break + } + rest, q = rest[xs:], q[ys:] + } + if q == "" { + return true + } + } + return false +} + +func (a *Autocomplete) refresh(c ui.C) bool { + a.matches = a.matches[:0] + editor := a.field.GetEditor() + if editor == nil || c.Canvas().Focused() != a.id { + return false + } + value := editor.String() + if value != a.typed { + a.typed, a.highlight, a.dismissed = value, -1, "" + } + if value == "" || value == a.dismissed { + return false + } + limit := a.spec.MaxRows + if limit <= 0 { + limit = 6 + } + for i, option := range a.spec.Options { + if len(a.matches) == limit { + break + } + if option != value && containsFold(option, value) { + a.matches = append(a.matches, i) + } + } + a.highlight = min(a.highlight, len(a.matches)-1) + return len(a.matches) > 0 +} + +func (a *Autocomplete) onKey(event gfx.KeyEvent) gfx.EventResult { + if !a.open || event.Release { + return gfx.EventResult{} + } + switch event.Key { + case gfx.KeyDown: + a.highlight = (a.highlight + 1) % len(a.matches) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyUp: + if a.highlight <= 0 { + a.highlight = len(a.matches) - 1 + } else { + a.highlight-- + } + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyEnter, gfx.KeyTab: + if a.highlight < 0 { + return gfx.EventResult{} + } + a.choose(a.matches[a.highlight]) + return gfx.EventResult{Handled: true, Repaint: true} + case gfx.KeyEscape: + a.dismissed, a.open = a.typed, false + return gfx.EventResult{Handled: true, Repaint: true} + } + return gfx.EventResult{} +} + +// choose writes the option in place of the text. +func (a *Autocomplete) choose(index int) { + editor := a.field.GetEditor() + if editor == nil { + return + } + editor.SetSelection(text.Range{Start: 0, End: editor.RuneCount()}) + editor.Insert(a.spec.Options[index]) + a.pending, a.open = index+1, false +} + +// View declares the field and, while a completion is on offer, the list under it. +// label and placeholder are the field's. Declare the view on its own, not inside +// a Memo. +func (a *Autocomplete) View(c ui.C, field *ui.Field, label, placeholder string, spec Spec) ui.Box { + if a == nil { + panic("autocomplete: View needs its Autocomplete") + } + a.chosen, a.pending = a.pending, 0 + a.spec, a.field = spec, field + if a.id = a.fieldID; a.id.IsZero() { + a.id = ui.ID(c) + } + a.open = a.refresh(c) + box := ui.TextField(c, field, label, placeholder, ui.WithID(a.id)).OnKey(a.key) + if a.open { + ui.Popover(c, box, &a.open, ui.PopoverSpec{ + Align: ui.Start, Padding: 4, Instant: true, NoDismiss: true, KeepOpenOnAnchor: true, + }, func() { a.list(c) }) + } + return box +} + +func (a *Autocomplete) list(c ui.C) { + theme := c.Theme() + metrics := theme.Metrics + ui.Column(c).FillWidth().Children(func() { + for row, index := range a.matches { + item := c.KeyInt(index) + box := ui.Row(item).FillWidth().Items(ui.Center).Pad(metrics.GapItem).Radius(metrics.RadiusControl) + if row == a.highlight { + box = box.Background(theme.Accent) + } + box = box.HitWith(ui.ID(item), a.spec.Options[index], gfx.HitOptions{Role: gfx.RoleOption, SkipFocus: true}) + box.Hover(ui.Look{}.Background(theme.Hover)) + box.Children(func() { ui.Text(item, a.spec.Options[index]) }) + if box.Clicked() { + a.choose(index) + } + } + }) +} diff --git a/ui/autocomplete/autocomplete_test.go b/ui/autocomplete/autocomplete_test.go new file mode 100644 index 000000000..dc9d71900 --- /dev/null +++ b/ui/autocomplete/autocomplete_test.go @@ -0,0 +1,165 @@ +package autocomplete_test + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/autocomplete" +) + +var hosts = []string{"build-01", "build-02", "db-primary", "staging"} + +type model struct { + a *autocomplete.Autocomplete + field ui.Field + chosen []string + enters int +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + m.a.View(c, &m.field, "Host", "", autocomplete.Spec{Options: hosts}).FillWidth() + if v, ok := m.a.Chosen(); ok { + m.chosen = append(m.chosen, v) + } + }) +} + +type driver struct { + t *testing.T + *app.Driver +} + +func open(t *testing.T) (*model, driver) { + t.Helper() + m := &model{a: autocomplete.New()} + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 400, Height: 320, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + dr := driver{t, d} + dr.click("Host") + return m, dr +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func (d driver) listed(label string) bool { + for _, h := range d.Snapshot().Hits { + if h.Label == label && h.Role == gfx.RoleOption { + return true + } + } + return false +} + +func (d driver) typ(s string) { + d.t.Helper() + if err := d.Type(s); err != nil { + d.t.Fatal(err) + } +} + +func (d driver) key(k gfx.Key) { + d.t.Helper() + if err := d.Key(k, 0); err != nil { + d.t.Fatal(err) + } +} + +func TestTypingListsTheOptionsThatContainIt(t *testing.T) { + _, d := open(t) + d.typ("BUILD") + if !d.listed("build-01") || !d.listed("build-02") || d.listed("staging") { + t.Fatal("the list does not follow what was typed") + } +} + +func TestAnOptionEqualToTheTextIsNotOffered(t *testing.T) { + _, d := open(t) + d.typ("staging") + if d.listed("staging") { + t.Fatal("the option the text already is was offered") + } +} + +func TestEnterWithoutAHighlightIsLeftToThePage(t *testing.T) { + m, d := open(t) + d.typ("bui") + d.key(gfx.KeyEnter) + if len(m.chosen) != 0 || m.field.GetEditor().String() != "bui" { + t.Fatalf("Enter chose something nobody highlighted: %v %q", m.chosen, m.field.GetEditor().String()) + } +} + +func TestArrowsAndEnterChoose(t *testing.T) { + m, d := open(t) + d.typ("build") + d.key(gfx.KeyDown) + d.key(gfx.KeyDown) + d.key(gfx.KeyUp) + d.key(gfx.KeyEnter) + if got := m.field.GetEditor().String(); got != "build-01" { + t.Fatalf("field = %q, want build-01", got) + } + if len(m.chosen) != 1 || m.chosen[0] != "build-01" { + t.Fatalf("chosen %v", m.chosen) + } +} + +func TestUpFromNothingGoesToTheLastOption(t *testing.T) { + m, d := open(t) + d.typ("build") + d.key(gfx.KeyUp) + d.key(gfx.KeyEnter) + if got := m.field.GetEditor().String(); got != "build-02" { + t.Fatalf("field = %q, want build-02", got) + } +} + +func TestPressingAnOptionChoosesIt(t *testing.T) { + m, d := open(t) + d.typ("db") + d.click("db-primary") + if got := m.field.GetEditor().String(); got != "db-primary" { + t.Fatalf("field = %q", got) + } +} + +func TestFreeTextIsKept(t *testing.T) { + m, d := open(t) + d.typ("elsewhere") + d.key(gfx.KeyEnter) + if got := m.field.GetEditor().String(); got != "elsewhere" { + t.Fatalf("field = %q", got) + } +} + +func TestEscapeClosesUntilTheTextChanges(t *testing.T) { + _, d := open(t) + d.typ("bu") + d.key(gfx.KeyEscape) + if d.listed("build-01") { + t.Fatal("Escape left the list open") + } + d.typ("i") + if !d.listed("build-01") { + t.Fatal("typing did not bring the list back") + } +} diff --git a/ui/edit_menu.go b/ui/edit_menu.go index 00e74fc36..306813e41 100644 --- a/ui/edit_menu.go +++ b/ui/edit_menu.go @@ -15,7 +15,7 @@ type EditMenuLabels = base.EditMenuLabels // application gives a ContextMenu of its own. func WithoutEditMenu() Option { return base.WithoutEditMenu() } -var installEditMenu sync.Once +var installEditMenu, installPrimarySelection sync.Once // useEditMenu installs the menu painter and the system clipboard the edit menu of // a TextField or TextArea needs. diff --git a/ui/facade.go b/ui/facade.go index d3593c32d..98f59cbfe 100644 --- a/ui/facade.go +++ b/ui/facade.go @@ -287,9 +287,9 @@ func TextField[T TextValue](c C, Value T, Label, placeholder string, opts ...Opt return base.TextField(c, Value, Label, placeholder, opts...) } -func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string) Box { +func TextFieldBase[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { useField() - return base.TextFieldBase(c, Value, Label, placeholder) + return base.TextFieldBase(c, Value, Label, placeholder, opts...) } func TextArea[T TextValue](c C, Value T, Label, placeholder string, opts ...Option) Box { diff --git a/ui/indicator/indicator.go b/ui/indicator/indicator.go new file mode 100644 index 000000000..d65cf7195 --- /dev/null +++ b/ui/indicator/indicator.go @@ -0,0 +1,110 @@ +// Package indicator is the opt-in page layout for a count or a dot pinned to the +// corner of another control, the red mark of an unread count on an icon or an +// avatar. A page declares the control it marks inside Child, and says what the +// mark shows: +// +// indicator.View(c, "Inbox", indicator.Spec{Count: m.unread, Max: 99}, func() { +// ui.Button(c, "Inbox").Icon(inboxIcon).IconOnly().Ghost() +// }) +// +// A Count above zero shows the number, and above Max shows Max and a plus sign +// ("99+"); a Count of zero shows nothing unless ShowZero is set. Dot shows a plain +// dot in place of the number. Status colors the mark as an alert does, the danger +// color by default. The mark is pinned to the top right corner of the control, +// reaches outside it by half its size, and takes no room of its own, so adding it +// does not move the control. label names the group for assistive technology. +// +// Keep no state: the page gives the count each paint. Counts up to 99 and their capped +// forms have their words made once, so a warm paint allocates nothing. +// It is a separate package so an application that does not import it pays +// nothing for it. +package indicator + +import ( + "strconv" + + "github.com/vivaui/viva/ui" +) + +// Spec declares the mark. +type Spec struct { + // Count is the number shown. + Count int + // Max is the largest number shown as it is; above it the mark reads "Max+". 99 + // when zero. + Max int + // ShowZero shows the mark for a Count of zero. + ShowZero bool + // Dot shows a dot, whatever the count, while Count is above zero or ShowZero + // is set. + Dot bool + // Status colors the mark; the danger color by default. + Status ui.Status +} + +// texts are the words of the small counts, made once. +var texts = func() (t [100]string) { + for i := range t { + t[i] = strconv.Itoa(i) + } + return t +}() + +// pluses are the words of a capped count, made once. +var pluses = func() (t [100]string) { + for i := range t { + t[i] = strconv.Itoa(i) + "+" + } + return t +}() + +// text is the words of a count, cached for the small ones. +func text(count, max int) string { + if max <= 0 { + max = 99 + } + if count > max { + if max < len(pluses) { + return pluses[max] + } + return strconv.Itoa(max) + "+" + } + if count >= 0 && count < len(texts) { + return texts[count] + } + return strconv.Itoa(count) +} + +// View declares the control and its mark. child declares the control, one +// element. The result is the box that holds them. +func View(c ui.C, label string, spec Spec, child func()) ui.Box { + theme := c.Theme() + metrics := theme.Metrics + root := ui.Stack(c).Shrink(0).Label(label) + root.Children(func() { + child() + shown := spec.Count > 0 || spec.ShowZero + if !shown { + return + } + fill := theme.Danger + switch spec.Status { + case ui.StatusSuccess: + fill = theme.Success + case ui.StatusWarning: + fill = theme.WarningColor() + } + if spec.Dot { + ui.Row(c).Absolute().Top(-4).Right(-4).Size(10, 10).Radius(5).Background(fill).Border(2, theme.Background) + return + } + words := text(spec.Count, spec.Max) + size := metrics.FontSizeS + mark := ui.Row(c).Absolute().Top(-size*0.6).Right(-size*0.6).Height(size+6).Center().PadSides(0, 5, 0, 5) + mark = mark.Radius((size + 6) / 2).Background(fill) + mark.Children(func() { + ui.Text(c, words).FontSize(size).Color(theme.PrimaryForeground).Shrink(0) + }) + }) + return root +} diff --git a/ui/indicator/indicator_test.go b/ui/indicator/indicator_test.go new file mode 100644 index 000000000..9e413cc85 --- /dev/null +++ b/ui/indicator/indicator_test.go @@ -0,0 +1,95 @@ +package indicator_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/indicator" +) + +func texts(t *testing.T, spec indicator.Spec) (values map[string]bool, button gfx.Rect) { + t.Helper() + view := func(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + indicator.View(c, "Inbox", spec, func() { ui.Button(c, "Inbox") }) + }) + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 200}, view) + canvas.EndFrame() + values = map[string]bool{} + for _, x := range canvas.Texts() { + values[x.Value] = true + } + for _, h := range canvas.Hits() { + if h.Label == "Inbox" && !h.IsLabel { + button = h.Bounds + } + } + return values, button +} + +func TestCountShowsAsNumberOrCapped(t *testing.T) { + for _, c := range []struct { + spec indicator.Spec + want string + }{ + {indicator.Spec{Count: 7}, "7"}, + {indicator.Spec{Count: 120}, "99+"}, + {indicator.Spec{Count: 12, Max: 9}, "9+"}, + {indicator.Spec{Count: 0, ShowZero: true}, "0"}, + {indicator.Spec{Count: 1234, Max: 1000}, "1000+"}, + } { + got, _ := texts(t, c.spec) + if !got[c.want] { + t.Errorf("%+v: %q is not shown (have %v)", c.spec, c.want, got) + } + } +} + +func TestNothingShownForZeroAndDotShowsNoNumber(t *testing.T) { + got, _ := texts(t, indicator.Spec{Count: 0}) + if len(got) != 1 { + t.Errorf("a zero count shows %v", got) + } + got, _ = texts(t, indicator.Spec{Count: 5, Dot: true}) + if got["5"] { + t.Error("a dot shows the number") + } +} + +func TestTheMarkTakesNoRoom(t *testing.T) { + _, plain := texts(t, indicator.Spec{}) + _, marked := texts(t, indicator.Spec{Count: 5}) + if plain != marked { + t.Fatalf("the control moved or resized: %+v then %+v", plain, marked) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + view := func(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + indicator.View(c, "Inbox", indicator.Spec{Count: 12}, func() { ui.Button(c, "Inbox") }) + }) + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 200}, view) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/inputtag/inputtag.go b/ui/inputtag/inputtag.go new file mode 100644 index 000000000..9ac780bfe --- /dev/null +++ b/ui/inputtag/inputtag.go @@ -0,0 +1,281 @@ +// Package inputtag is the opt-in page control for entering several short values +// as tags: the values entered so far are tags in a row, each with a close button, +// followed by a text field to type the next. A page keeps the values in its model +// and an InputTag beside them: +// +// m.hosts = inputtag.New() +// // in the page: +// m.hosts.View(c, "Allowed hosts", m.allowed, inputtag.Spec{Placeholder: "Add a host"}).FillWidth() +// if value, ok := m.hosts.Added(); ok { +// m.allowed = append(m.allowed, value) +// } +// if i, ok := m.hosts.Removed(); ok { +// m.allowed = slices.Delete(m.allowed, i, i+1) +// } +// +// Enter, or a typed Separator (a comma by default), adds what is in the field as +// a tag; Backspace in the empty field removes the last tag, and the close button +// of a tag removes that one. Empty or white-space-only entries are ignored, and a +// value already in the list is not added twice unless AllowDuplicates is set. The +// control reports what the user did and the page changes its list: the same +// answer as for an alert's close button, so the list stays the page's. +// +// MaxTags stops adding when the list is that long; Validate can refuse a value, +// and the field then keeps its text and shows the invalid look. Rejected reports +// the refusal. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an InputTag in the model. Do not copy one after it has been +// declared. +package inputtag + +import ( + "strings" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/tag" +) + +// Spec declares the control. +type Spec struct { + // Placeholder is shown in the field while it and the list are empty. + Placeholder string + // Separator is the rune that adds the typed value; ',' when zero. NoSeparator + // leaves only Enter. + Separator rune + NoSeparator bool + // MaxTags is how many tags the list may have; zero is no limit. + MaxTags int + // AllowDuplicates lets a value be added that is already in the list. + AllowDuplicates bool + // Validate returns whether a value may be added; nil accepts every value. + Validate func(value string) bool + // Disabled leaves the field and the close buttons inert. + Disabled bool + // RemoveLabel is the accessible name of a close button, before the tag's text: + // "Remove" when empty. + RemoveLabel string +} + +// InputTag is one control's state: the text being typed and what was done. +type InputTag struct { + field ui.Field + added string + hasAdded bool + removed int // 1 + the index removed since the paint before, or 0 + rejected bool + invalid bool + // pending is what a key or a press did since the last paint, reported by the + // paint after it. + pending struct { + added string + hasAdded bool + removeLast bool + rejected bool + } + key func(gfx.KeyEvent) gfx.EventResult + deleteAtEdge func(forward bool) + spec Spec + tags []string + labels []name // "Remove ", kept while the tag stays + id gfx.ID + fieldID gfx.ID +} + +// New returns an empty control. +func New() *InputTag { + t := &InputTag{} + t.key = t.onKey + t.deleteAtEdge = t.onDeleteAtEdge + return t +} + +// FieldID names the field with an identity the application already holds, and +// Field is the text field behind the control, for a runner that binds the editor +// the platform edits to it with Field.Bind. A page needs neither. +func (t *InputTag) FieldID(id gfx.ID) *InputTag { t.fieldID = id; return t } + +// Field is the text field behind the control. +func (t *InputTag) Field() *ui.Field { return &t.field } + +// Added returns the value the user added since the paint before this one. +func (t *InputTag) Added() (string, bool) { return t.added, t.hasAdded } + +// Removed returns the index of the tag the user removed since the paint before +// this one. +func (t *InputTag) Removed() (int, bool) { return t.removed - 1, t.removed > 0 } + +// Rejected reports whether a value was refused (by Validate, MaxTags or as a +// duplicate) since the paint before this one. +func (t *InputTag) Rejected() bool { return t.rejected } + +func (s *Spec) separator() rune { + if s.NoSeparator { + return -1 + } + if s.Separator == 0 { + return ',' + } + return s.Separator +} + +// accepts says whether value may join the list, and records a refusal. +func (t *InputTag) accepts(value string) bool { + ok := value != "" + if ok && !t.spec.AllowDuplicates { + for _, existing := range t.tags { + if existing == value { + ok = false + break + } + } + } + if ok && t.spec.MaxTags > 0 && len(t.tags) >= t.spec.MaxTags { + ok = false + } + if ok && t.spec.Validate != nil && !t.spec.Validate(value) { + ok = false + } + return ok +} + +// commit takes the typed text as a tag, or refuses it. +func (t *InputTag) commit() { + editor := t.field.GetEditor() + if editor == nil { + return + } + value := strings.TrimSpace(editor.String()) + if value == "" { + return + } + if !t.accepts(value) { + t.pending.rejected, t.invalid = true, true + return + } + t.pending.added, t.pending.hasAdded, t.invalid = value, true, false + clear(editor) +} + +// clear empties the editor. +func clear(editor *text.Editor) { + editor.SetSelection(text.Range{Start: 0, End: editor.RuneCount()}) + editor.DeleteBackward() +} + +func (t *InputTag) onKey(event gfx.KeyEvent) gfx.EventResult { + if event.Release || t.spec.Disabled { + return gfx.EventResult{} + } + editor := t.field.GetEditor() + switch { + case event.Key == gfx.KeyEnter: + if editor != nil && strings.TrimSpace(editor.String()) != "" { + t.commit() + return gfx.EventResult{Handled: true, Repaint: true} + } + } + return gfx.EventResult{} +} + +// takeSeparated commits the text typed or pasted before a separator, and keeps +// what follows it in the field. +func (t *InputTag) takeSeparated() { + editor := t.field.GetEditor() + sep := t.spec.separator() + if editor == nil || sep < 0 { + return + } + value := editor.String() + i := strings.IndexRune(value, sep) + if i < 0 { + return + } + editor.SetSelection(text.Range{Start: 0, End: utf8.RuneCountInString(value[:i+utf8.RuneLen(sep)])}) + editor.DeleteBackward() + if value = strings.TrimSpace(value[:i]); value != "" { + if t.accepts(value) { + t.added, t.hasAdded, t.invalid = value, true, false + } else { + t.rejected, t.invalid = true, true + } + } +} + +// onDeleteAtEdge is Backspace in the empty field: it removes the last tag. +func (t *InputTag) onDeleteAtEdge(forward bool) { + if !forward && !t.spec.Disabled && len(t.tags) > 0 && t.field.GetEditor().RuneCount() == 0 { + t.pending.removeLast = true + } +} + +// View declares the tags and the field at c. tags are the values in the list, in +// order; keep the slice in the model. label names the field for assistive +// technology. Declare the view on its own, not inside a Memo. +func (t *InputTag) View(c ui.C, label string, tags []string, spec Spec) ui.Box { + if t == nil { + panic("inputtag: View needs its InputTag") + } + t.added, t.hasAdded, t.rejected, t.removed = t.pending.added, t.pending.hasAdded, t.pending.rejected, 0 + t.pending.added, t.pending.hasAdded, t.pending.rejected = "", false, false + if t.pending.removeLast { + t.pending.removeLast, t.removed = false, len(tags) + } + t.spec, t.tags = spec, tags + if editor := t.field.GetEditor(); editor != nil && editor.OnDeleteAtEdge == nil { + editor.OnDeleteAtEdge = t.deleteAtEdge + } + t.takeSeparated() + theme := c.Theme() + metrics := theme.Metrics + remove := spec.RemoveLabel + if remove == "" { + remove = "Remove" + } + for len(t.labels) < len(tags) { + t.labels = append(t.labels, name{}) + } + t.id = ui.ID(c) + if t.fieldID.IsZero() { + t.fieldID = ui.ID(c) + } + rim := theme.Input + if c.Canvas().Focused() == t.fieldID { + rim = theme.Primary + } + if t.invalid { + rim = theme.Danger + } + root := ui.Flow(c).Items(ui.Center).Gap(metrics.GapItem * 0.5).LineGap(metrics.GapItem * 0.5).Pad(metrics.GapItem) + root = root.Radius(metrics.RadiusControl).Border(1, rim) + root.Children(func() { + for i, value := range tags { + if n := &t.labels[i]; n.of != value || n.verb != remove { + n.of, n.verb, n.text = value, remove, remove+" "+value + } + key := c.Key(value) + if i < len(tags) && spec.AllowDuplicates { + key = c.KeyInt(i) + } + result := tag.View(key, value, tag.Spec{Closable: !spec.Disabled, CloseLabel: t.labels[i].text}) + if result.Closed { + t.removed = i + 1 + } + } + placeholder := "" + if len(tags) == 0 { + placeholder = spec.Placeholder + } + field := ui.TextFieldBase(c, &t.field, label, placeholder, ui.WithID(t.fieldID)).OnKey(t.key).Width(120).Grow(1) + if spec.Disabled { + field.Disabled(true) + } + }) + return root +} + +// name is the accessible name of one close button and what it was made from. +type name struct{ of, verb, text string } diff --git a/ui/inputtag/inputtag_test.go b/ui/inputtag/inputtag_test.go new file mode 100644 index 000000000..2595369bf --- /dev/null +++ b/ui/inputtag/inputtag_test.go @@ -0,0 +1,158 @@ +package inputtag_test + +import ( + "slices" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/inputtag" +) + +type model struct { + t *inputtag.InputTag + tags []string + spec inputtag.Spec + rej int +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + m.t.View(c, "Hosts", m.tags, m.spec).FillWidth() + if v, ok := m.t.Added(); ok { + m.tags = append(m.tags, v) + } + if i, ok := m.t.Removed(); ok { + m.tags = slices.Delete(m.tags, i, i+1) + } + if m.t.Rejected() { + m.rej++ + } + }) +} + +type driver struct { + t *testing.T + *app.Driver +} + +func open(t *testing.T, m *model) driver { + t.Helper() + m.t = inputtag.New() + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: 420, Height: 240, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + dr := driver{t, d} + dr.click("Hosts") + return dr +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func (d driver) typ(s string) { + d.t.Helper() + if err := d.Type(s); err != nil { + d.t.Fatal(err) + } +} + +func (d driver) key(k gfx.Key) { + d.t.Helper() + if err := d.Key(k, 0); err != nil { + d.t.Fatal(err) + } +} + +func TestEnterAddsATagAndBackspaceRemovesTheLast(t *testing.T) { + m := &model{} + d := open(t, m) + d.typ("alpha") + d.key(gfx.KeyEnter) + d.typ("beta") + d.key(gfx.KeyEnter) + if !slices.Equal(m.tags, []string{"alpha", "beta"}) { + t.Fatalf("tags %v", m.tags) + } + d.key(gfx.KeyBackspace) + if !slices.Equal(m.tags, []string{"alpha"}) { + t.Fatalf("after Backspace %v", m.tags) + } +} + +func TestBackspaceInANonEmptyFieldOnlyEdits(t *testing.T) { + m := &model{tags: []string{"alpha"}} + d := open(t, m) + d.typ("be") + d.key(gfx.KeyBackspace) + if !slices.Equal(m.tags, []string{"alpha"}) { + t.Fatalf("Backspace removed a tag while text was typed: %v", m.tags) + } +} + +func TestSeparatorAddsTheTypedValue(t *testing.T) { + m := &model{} + d := open(t, m) + d.typ("one,") + if !slices.Equal(m.tags, []string{"one"}) { + t.Fatalf("tags %v", m.tags) + } +} + +func TestDuplicatesBlankAndLimitAreRefused(t *testing.T) { + m := &model{tags: []string{"a"}, spec: inputtag.Spec{MaxTags: 2}} + d := open(t, m) + d.typ("a") + d.key(gfx.KeyEnter) + if len(m.tags) != 1 || m.rej == 0 { + t.Fatalf("a duplicate was added or not reported: %v rej %d", m.tags, m.rej) + } + d.key(gfx.KeyBackspace) // removes nothing of the typed text, which is still "a" + d.key(gfx.KeyEnter) + if len(m.tags) != 1 { + t.Fatalf("tags %v", m.tags) + } +} + +func TestCloseButtonRemovesThatTag(t *testing.T) { + m := &model{tags: []string{"a", "b", "c"}} + d := open(t, m) + d.click("Remove b") + if !slices.Equal(m.tags, []string{"a", "c"}) { + t.Fatalf("tags %v", m.tags) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + m := &model{t: inputtag.New(), tags: []string{"a", "b"}} + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 420, Height: 240}, m.page) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/markdown/markdown.go b/ui/markdown/markdown.go index 67fe0b717..bfad88664 100644 --- a/ui/markdown/markdown.go +++ b/ui/markdown/markdown.go @@ -32,6 +32,7 @@ package markdown import ( + "github.com/vivaui/viva/base" "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/markdown" @@ -47,7 +48,7 @@ type Style = components.MarkdownStyle type Look = components.MarkdownLook // Selection is a range of the rendered text, in byte offsets. -type Selection = components.MarkdownSelection +type Selection = base.TextRange // Code is a laid-out fenced code block. type Code = components.MarkdownCode diff --git a/ui/menu_paint.go b/ui/menu_paint.go index da02c8643..34fb85c27 100644 --- a/ui/menu_paint.go +++ b/ui/menu_paint.go @@ -11,7 +11,7 @@ import ( // good until the next row. func menuItemsRow(m *MenuItems, i int) components.DropdownMenuItem { row := &m.Items[i] - item := components.DropdownMenuItem{ID: m.GetScope().At(MenuRowsPart + i), Label: row.Label, Description: row.GetDescription(), Disabled: row.GetDisabled(), Icon: row.GetIcon(), TrailingWidth: row.GetTrailingWidth()} + item := components.DropdownMenuItem{ID: m.GetScope().At(MenuRowsPart + i), Label: row.Label, Mnemonic: row.GetMnemonic(), Description: row.GetDescription(), Disabled: row.GetDisabled(), Icon: row.GetIcon(), TrailingWidth: row.GetTrailingWidth()} if row.GetDestructive() { item.Variant = components.DropdownMenuItemDestructive } @@ -168,7 +168,7 @@ func paintAt(m *MenuItems, Surface *gfx.Canvas, Palette *Theme, bounds Rect, lay // 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, TrailingWidth: item.TrailingWidth, + ID: item.ID, Label: item.Label, Mnemonic: item.Mnemonic, Description: item.Description, Keys: item.Keys, Icon: item.Icon, Disabled: item.Disabled, TrailingWidth: item.TrailingWidth, Checked: item.Checked, Selected: item.Selected, } switch item.Kind { @@ -221,7 +221,7 @@ func menuSize(m *MenuItems) (width, height float32) { // scratch, good until the next row. func menuItemRow(m *MenuItems, i int) components.DropdownMenuItem { row := &m.Items[i] - item := components.DropdownMenuItem{ID: m.GetScope().At(MenuRowsPart + i), Label: row.Label, Description: row.GetDescription(), Disabled: row.GetDisabled(), Icon: row.GetIcon(), TrailingWidth: row.GetTrailingWidth()} + item := components.DropdownMenuItem{ID: m.GetScope().At(MenuRowsPart + i), Label: row.Label, Mnemonic: row.GetMnemonic(), Description: row.GetDescription(), Disabled: row.GetDisabled(), Icon: row.GetIcon(), TrailingWidth: row.GetTrailingWidth()} if row.GetDestructive() { item.Variant = components.DropdownMenuItemDestructive } diff --git a/ui/menu_test.go b/ui/menu_test.go index ea91b7d1a..b0dbf75a7 100644 --- a/ui/menu_test.go +++ b/ui/menu_test.go @@ -164,11 +164,12 @@ func BenchmarkMenuOpen(b *testing.B) { } type contextModel struct { - hosts []string - connected string - wrap bool - open bool - renames, opens int + hosts []string + connected string + wrap bool + open bool + connectDisabled bool + renames, opens int } func (m *contextModel) page(c ui.C) { @@ -176,7 +177,7 @@ func (m *contextModel) page(c ui.C) { for _, h := range m.hosts { row := ui.Button(c.Key(h), h) ui.ContextMenu(c, row, func(menu *ui.MenuItems) { - if menu.Item("Connect").Clicked() { + if menu.Item("Connect").Mnemonic("r").Disabled(m.connectDisabled).Clicked() { m.connected = h } if menu.Item("Rename").Keys(ui.Primary, "r").Clicked() { @@ -230,6 +231,56 @@ func TestContextMenuOpensAtThePointer(t *testing.T) { } } +func TestContextMenuMnemonicPrecedesLabelTypeahead(t *testing.T) { + m := &contextModel{hosts: []string{"alpha"}} + d := openPage(t, m.page) + alpha := d.hit("alpha").Bounds + x, y := alpha.X+5, alpha.Y+alpha.Height/2 + if err := d.driver.ClickButton(x, y, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + if _, err := d.driver.ShortcutChord(0, 'r'); err != nil { + t.Fatal(err) + } + if focused := d.Focused(); focused != "Connect" { + t.Fatalf("mnemonic r focused %q, want Connect before Rename typeahead", focused) + } +} + +func TestContextMenuDisabledMnemonicDoesNotCaptureKey(t *testing.T) { + m := &contextModel{hosts: []string{"alpha"}, connectDisabled: true} + d := openPage(t, m.page) + alpha := d.hit("alpha").Bounds + x, y := alpha.X+5, alpha.Y+alpha.Height/2 + if err := d.driver.ClickButton(x, y, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + if _, err := d.driver.ShortcutChord(0, 'r'); err != nil { + t.Fatal(err) + } + if focused := d.Focused(); focused != "Rename" { + t.Fatalf("disabled mnemonic focused %q, want Rename via typeahead", focused) + } +} + +func TestContextMenuMnemonicYieldsToALabelSearchInProgress(t *testing.T) { + m := &contextModel{hosts: []string{"alpha"}} + d := openPage(t, m.page) + alpha := d.hit("alpha").Bounds + if err := d.driver.ClickButton(alpha.X+5, alpha.Y+alpha.Height/2, gfx.PointerButtonSecondary); err != nil { + t.Fatal(err) + } + // W starts a label search; R would be the Connect mnemonic on its own. + for _, key := range "wr" { + if _, err := d.driver.ShortcutChord(0, key); err != nil { + t.Fatal(err) + } + } + if focused := d.Focused(); focused == "Connect" { + t.Fatal("a mnemonic interrupted a label search in progress") + } +} + // Shift+F10 opens the focused target's menu; Tab stays in it, Escape closes it. func TestContextMenuKeyboard(t *testing.T) { m := &contextModel{hosts: []string{"alpha"}} diff --git a/ui/overflowlist/overflowlist.go b/ui/overflowlist/overflowlist.go new file mode 100644 index 000000000..2dcda3fe1 --- /dev/null +++ b/ui/overflowlist/overflowlist.go @@ -0,0 +1,144 @@ +// Package overflowlist is the opt-in page control for a row of icon actions that +// shows as many as fit and puts the rest in a "More" menu: a toolbar that keeps +// working when its window or panel is narrowed. A page keeps an OverflowList in +// its model and gives it the actions each paint: +// +// m.tools = overflowlist.New() +// // in the page: +// m.tools.View(c, "Actions", overflowlist.Spec{Items: m.actions}).FillWidth() +// if i, ok := m.tools.Clicked(); ok { +// m.run(m.actions[i]) +// } +// +// An Item is an icon, the label that names it (its tooltip and accessible name +// when shown, its words in the menu when not) and whether it is Disabled. Items +// leave the row from the end, last first, and appear in the menu in their own +// order; a Disabled item stays disabled in the menu. When every item fits there is +// no menu button. Min keeps at least that many items in the row however narrow it +// gets, and the row never leaves room for fewer than one button besides More. +// +// The number that fit is measured from the width the control is placed in, never +// from what it holds, so it settles in the paint that first sees the width and +// again as the window is resized; it asks for nothing between resizes. +// +// It is a separate package so an application that does not import it pays +// nothing for it. Keep an OverflowList in the model: its menu state is made once. +// Do not copy one after it has been declared. +package overflowlist + +import ( + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +var moreIcon = gfx.Icon{ViewBox: 24, Stroke: 2, Cap: gfx.CapRound, Join: gfx.JoinRound, Commands: []gfx.PathCommand{ + gfx.MoveTo(5, 12), gfx.LineTo(5.01, 12), gfx.MoveTo(12, 12), gfx.LineTo(12.01, 12), gfx.MoveTo(19, 12), gfx.LineTo(19.01, 12), +}} + +// Item is one action. +type Item struct { + // Label names the action: its accessible name and tooltip in the row, its + // words in the menu. + Label string + // Icon is the glyph of the action's button. + Icon gfx.Icon + // Disabled leaves the action inert, in the row and in the menu. + Disabled bool +} + +// Spec declares the row. +type Spec struct { + // Items are the actions, in order. Keep the slice in the model. + Items []Item + // Min is how many items stay in the row however narrow it gets; one when + // zero. + Min int + // Gap is the space between buttons; the theme's item gap when zero. + Gap float32 + // MoreLabel is the accessible name of the menu button, "More" when empty. + MoreLabel string +} + +// OverflowList is one row and its menu. +type OverflowList struct { + open bool + clicked int // 1 + the item pressed in the paint being declared, or 0 +} + +// New returns a row. +func New() *OverflowList { return &OverflowList{} } + +// Clicked reports which action the user chose in the paint just made, from the row +// or from the menu. +func (o *OverflowList) Clicked() (int, bool) { return o.clicked - 1, o.clicked > 0 } + +// View declares the row at c. label names it for assistive technology. The row is +// one button high and as wide as the room it is given; give it FillWidth. Declare +// the view on its own, not inside a Memo. +func (o *OverflowList) View(c ui.C, label string, spec Spec) ui.Box { + if o == nil { + panic("overflowlist: View needs its OverflowList") + } + o.clicked = 0 + theme := c.Theme() + gap := spec.Gap + if gap <= 0 { + gap = theme.Metrics.GapItem + } + button := theme.Metrics.ControlHeight + more := spec.MoreLabel + if more == "" { + more = "More" + } + n := len(spec.Items) + root := ui.Container(c).FillWidth().Label(label) + root.Children(func() { + shown := n + // The widest row that fits: all of the items, or as many as leave room for the + // menu button. Each question is answered from the width the container had in the + // last layout. + if n > 0 && !c.AtLeast(ui.Width(span(n, button, gap))) { + floor := max(min(max(spec.Min, 1), n), 1) + shown = floor + for k := n - 1; k > floor; k-- { + if c.AtLeast(ui.Width(span(k+1, button, gap))) { + shown = k + break + } + } + } + ui.Row(c).FillWidth().Items(ui.Center).Gap(gap).Children(func() { + for i := 0; i < shown; i++ { + item := &spec.Items[i] + b := ui.Button(c.KeyInt(i), item.Label).Icon(item.Icon).IconOnly().Ghost().Disabled(item.Disabled).Shrink(0) + if b.Clicked() { + o.clicked = i + 1 + } + } + if shown < n { + ui.Spacer(c).Grow(1) + trigger := ui.Button(c, more).Icon(moreIcon).IconOnly().Ghost().Shrink(0) + if trigger.Clicked() { + o.open = !o.open + } + ui.Menu(c, trigger, &o.open, func(menu *ui.MenuItems) { + for i := shown; i < n; i++ { + entry := menu.Item(spec.Items[i].Label) + if spec.Items[i].Disabled { + entry.Disabled(true) + } + if entry.Clicked() { + o.clicked = i + 1 + } + } + }) + } + }) + }) + return root +} + +// span is the width of count buttons with a gap between each. +func span(count int, button, gap float32) float32 { + return float32(count)*button + float32(max(count-1, 0))*gap +} diff --git a/ui/overflowlist/overflowlist_test.go b/ui/overflowlist/overflowlist_test.go new file mode 100644 index 000000000..17fb5e6b4 --- /dev/null +++ b/ui/overflowlist/overflowlist_test.go @@ -0,0 +1,189 @@ +package overflowlist_test + +import ( + "fmt" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/overflowlist" +) + +var glyph = gfx.Icon{ViewBox: 24, Stroke: 2, Commands: []gfx.PathCommand{gfx.MoveTo(4, 12), gfx.LineTo(20, 12)}} + +type model struct { + o *overflowlist.OverflowList + items []overflowlist.Item + min int + clicked []int +} + +func newModel(n int) *model { + m := &model{o: overflowlist.New()} + for i := 0; i < n; i++ { + m.items = append(m.items, overflowlist.Item{Label: fmt.Sprintf("Tool %d", i), Icon: glyph}) + } + return m +} + +func (m *model) page(c ui.C) { + ui.Column(c).Fill().Pad(8).Children(func() { + m.o.View(c, "Actions", overflowlist.Spec{Items: m.items, Min: m.min}).FillWidth() + if i, ok := m.o.Clicked(); ok { + m.clicked = append(m.clicked, i) + } + }) +} + +type driver struct { + t *testing.T + *app.Driver +} + +func open(t *testing.T, m *model, width int) driver { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: m.page}) + d, err := app.NewDriver(ui.Configure(page, app.Config{Width: width, Height: 200, Invalidator: new(app.Invalidator)}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(d.Close) + return driver{t, d} +} + +// row is the tool buttons in the row, left to right, and whether More is there. +func (d driver) row() (tools []string, more bool) { + for _, h := range d.Snapshot().Hits { + if h.IsLabel || h.Role != gfx.RoleButton { + continue + } + if h.Label == "More" { + more = true + } else { + tools = append(tools, h.Label) + } + } + return tools, more +} + +func (d driver) click(label string) { + d.t.Helper() + hits := d.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + if h := hits[i]; h.Label == label && !h.IsLabel && !h.ID.IsZero() { + if err := d.Click(h.Bounds.X+h.Bounds.Width/2, h.Bounds.Y+h.Bounds.Height/2); err != nil { + d.t.Fatal(err) + } + return + } + } + d.t.Fatalf("no control labeled %q", label) +} + +func TestEverythingFitsThenThereIsNoMore(t *testing.T) { + m := newModel(4) + d := open(t, m, 600) + tools, more := d.row() + if len(tools) != 4 || more { + t.Fatalf("tools %v more %v", tools, more) + } +} + +func TestNarrowingMovesTheLastItemsIntoMoreAndWideningBringsThemBack(t *testing.T) { + m := newModel(6) + d := open(t, m, 600) + previous := 6 + for _, width := range []int{240, 180, 120, 80} { + if err := d.Resize(width, 200); err != nil { + t.Fatal(err) + } + if err := d.Pump(); err != nil { + t.Fatal(err) + } + tools, more := d.row() + if len(tools) >= 6 || !more { + t.Fatalf("width %d: %d tools, more %v; want fewer than all and a menu", width, len(tools), more) + } + if len(tools) > previous { + t.Fatalf("width %d: %d tools, more than at the wider width (%d)", width, len(tools), previous) + } + for i, label := range tools { + if want := fmt.Sprintf("Tool %d", i); label != want { + t.Fatalf("width %d: row has %v; items must leave from the end", width, tools) + } + } + previous = len(tools) + } + if err := d.Resize(600, 200); err != nil { + t.Fatal(err) + } + if err := d.Pump(); err != nil { + t.Fatal(err) + } + if tools, more := d.row(); len(tools) != 6 || more { + t.Fatalf("widened: %v more %v", tools, more) + } +} + +func TestNeverFewerThanTheMinimum(t *testing.T) { + m := newModel(6) + m.min = 3 + d := open(t, m, 40) + if tools, _ := d.row(); len(tools) < 3 { + t.Fatalf("only %d tools in a row that keeps at least 3", len(tools)) + } +} + +func TestAnOverflowedItemIsChosenFromTheMenuAndKeepsItsDisabledState(t *testing.T) { + m := newModel(6) + m.items[5].Disabled = true + d := open(t, m, 160) + tools, more := d.row() + if !more || len(tools) >= 6 { + t.Fatalf("not overflowed: %v %v", tools, more) + } + d.click("More") + var hidden, disabled bool + for _, h := range d.Snapshot().Hits { + if h.Label == "Tool 5" && !h.IsLabel { + hidden, disabled = true, h.Disabled + } + } + if !hidden || !disabled { + t.Fatalf("the last item in the menu: present %v disabled %v", hidden, disabled) + } + d.click("Tool 4") + if len(m.clicked) != 1 || m.clicked[0] != 4 { + t.Fatalf("clicked %v, want [4]", m.clicked) + } +} + +func TestClickingARowButtonReportsIt(t *testing.T) { + m := newModel(3) + d := open(t, m, 600) + d.click("Tool 1") + if len(m.clicked) != 1 || m.clicked[0] != 1 { + t.Fatalf("clicked %v", m.clicked) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + m := newModel(6) + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: m.page, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 180, Height: 200}, m.page) + canvas.EndFrame() + } + draw() + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} diff --git a/ui/statistic/statistic.go b/ui/statistic/statistic.go new file mode 100644 index 000000000..1822fa54e --- /dev/null +++ b/ui/statistic/statistic.go @@ -0,0 +1,153 @@ +// Package statistic is the opt-in page control for one number shown as a +// reading: a muted title, then the value in a large size with its prefix and +// suffix, formatted to a number of decimals with digit groups. A page keeps a +// Statistic in its model and gives it the number each paint: +// +// m.sessions = statistic.New() +// // in the page: +// m.sessions.View(c, statistic.Spec{Title: "Active sessions", Value: m.count, Group: true}) +// m.latency.View(c, statistic.Spec{Title: "Latency", Value: m.ms, Precision: 1, Suffix: "ms"}) +// +// Precision is the number of decimals; Group puts a comma between thousands +// (GroupSeparator changes it). Status colors the value as an alert or a tag +// does: success, warning or danger take the theme's color for it. NaN and the +// infinities are shown as an em dash, the usual mark of a reading that is not +// there. +// +// Unlike metriccard, which is a card with a trend and a description, this is the +// number alone, to place in a row, a toolbar or a card of the page's own. The +// formatted text is made again only when the number or its format changes, so a +// warm paint of an unchanged reading allocates nothing. Keep a Statistic in the +// model; do not copy one after it has been declared. +package statistic + +import ( + "math" + "strconv" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Spec declares one reading. +type Spec struct { + // Title is the muted caption above the value; not drawn when empty. + Title string + // Value is the number. + Value float64 + // Precision is the number of decimals shown. + Precision int + // Group puts GroupSeparator between the thousands of the integer part. + Group bool + // GroupSeparator is the rune between groups; ',' when zero. + GroupSeparator rune + // Prefix and Suffix are written around the number, such as a currency sign or a + // unit. They take the value's color. + Prefix, Suffix string + // Status colors the value; the zero value keeps the foreground. + Status ui.Status + // ValueSize is the value's font size; 24 when zero. + ValueSize float32 +} + +// Statistic is one reading and the text made from it. +type Statistic struct { + last Spec + text string + label string // the title and the text, the reading's name for assistive technology + made bool +} + +// New returns a reading. +func New() *Statistic { return &Statistic{} } + +// Format writes value with precision decimals, and with sep between groups of +// three digits of the integer part when sep is not zero. NaN and infinities are +// an em dash. +func Format(value float64, precision int, sep rune) string { + if math.IsNaN(value) || math.IsInf(value, 0) { + return "—" + } + precision = max(precision, 0) + digits := strconv.FormatFloat(math.Abs(value), 'f', precision, 64) + whole, fraction := digits, "" + for i := 0; i < len(digits); i++ { + if digits[i] == '.' { + whole, fraction = digits[:i], digits[i:] + break + } + } + out := make([]byte, 0, len(digits)+len(digits)/3+2) + // A value that rounds to zero is not negative. + if value < 0 && (precision == 0 && math.Round(value) != 0 || precision > 0 && !allZero(digits)) { + out = append(out, '-') + } + for i := 0; i < len(whole); i++ { + if sep != 0 && i > 0 && (len(whole)-i)%3 == 0 { + out = append(out, string(sep)...) + } + out = append(out, whole[i]) + } + return string(append(out, fraction...)) +} + +func allZero(digits string) bool { + for i := 0; i < len(digits); i++ { + if digits[i] != '0' && digits[i] != '.' { + return false + } + } + return true +} + +// Text is the number as View shows it, with the prefix and suffix. +func (s *Statistic) Text(spec Spec) string { + if s.made && s.last.Value == spec.Value && s.last.Precision == spec.Precision && s.last.Group == spec.Group && + s.last.GroupSeparator == spec.GroupSeparator && s.last.Prefix == spec.Prefix && s.last.Suffix == spec.Suffix && s.last.Title == spec.Title || + s.made && math.IsNaN(spec.Value) && math.IsNaN(s.last.Value) && s.last.Precision == spec.Precision && + s.last.Prefix == spec.Prefix && s.last.Suffix == spec.Suffix && s.last.Title == spec.Title { + return s.text + } + var sep rune + if spec.Group { + if sep = spec.GroupSeparator; sep == 0 { + sep = ',' + } + } + s.text = spec.Prefix + Format(spec.Value, spec.Precision, sep) + spec.Suffix + s.label = spec.Title + " " + s.text + s.last, s.made = spec, true + return s.text +} + +// View declares the reading at c. The reading is as wide as its text and as tall +// as its title and value. Declare it on its own, not inside a Memo. +func (s *Statistic) View(c ui.C, spec Spec) ui.Box { + if s == nil { + panic("statistic: View needs its Statistic") + } + text := s.Text(spec) + theme := c.Theme() + metrics := theme.Metrics + size := spec.ValueSize + if size <= 0 { + size = 24 + } + ink := theme.Foreground + switch spec.Status { + case ui.StatusSuccess: + ink = theme.Success + case ui.StatusWarning: + ink = theme.WarningColor() + case ui.StatusDanger: + ink = theme.Danger + } + root := ui.Column(c).Gap(4).HitWith(ui.ID(c), s.label, gfx.HitOptions{Role: gfx.RoleStatus, SkipFocus: true}) + root.Children(func() { + if spec.Title != "" { + ui.Text(c, spec.Title).FontSize(metrics.FontSizeS).Muted() + } + ui.Text(c, text).FontSize(size).Weight(gfx.WeightMedium).Color(ink) + }) + return root +} diff --git a/ui/statistic/statistic_test.go b/ui/statistic/statistic_test.go new file mode 100644 index 000000000..f48f10d6b --- /dev/null +++ b/ui/statistic/statistic_test.go @@ -0,0 +1,71 @@ +package statistic_test + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/statistic" +) + +func TestFormat(t *testing.T) { + for _, c := range []struct { + v float64 + prec int + sep rune + want string + }{ + {0, 0, 0, "0"}, {1234567, 0, ',', "1,234,567"}, {999, 0, ',', "999"}, {1000, 0, ',', "1,000"}, + {-1234.5, 1, ',', "-1,234.5"}, {3.14159, 2, 0, "3.14"}, {2, 2, 0, "2.00"}, {-0.001, 2, 0, "0.00"}, + {12345.678, 1, '.', "12.345.7"}, {math.NaN(), 0, 0, "—"}, {math.Inf(1), 0, 0, "—"}, {-4, -3, 0, "-4"}, + } { + if got := statistic.Format(c.v, c.prec, c.sep); got != c.want { + t.Errorf("Format(%v, %d, %q) = %q, want %q", c.v, c.prec, c.sep, got, c.want) + } + } +} + +func TestTextAddsPrefixAndSuffixAndKeepsItWhileUnchanged(t *testing.T) { + s := statistic.New() + spec := statistic.Spec{Value: 1234.5, Precision: 1, Group: true, Prefix: "$", Suffix: " ms"} + if got := s.Text(spec); got != "$1,234.5 ms" { + t.Fatalf("Text = %q", got) + } + nan := statistic.Spec{Value: math.NaN()} + s.Text(nan) + if n := testing.AllocsPerRun(100, func() { s.Text(nan) }); n != 0 { + t.Fatalf("an unchanged NaN reading allocates %v times", n) + } +} + +func TestWarmPaintDoesNotAllocate(t *testing.T) { + s := statistic.New() + view := func(c ui.C) { + ui.Column(c).Fill().Pad(16).Children(func() { + s.View(c, statistic.Spec{Title: "Sessions", Value: 12840, Group: true, Status: ui.StatusSuccess}) + }) + } + theme := gfx.LightTheme() + page := ui.NewPage(ui.PageConfig{View: view, Theme: &theme}) + canvas := &gfx.Canvas{} + canvas.SetReduceMotion(true) + draw := func() { + canvas.BeginFrame() + canvas.Reset() + page.Draw(canvas, gfx.Rect{Width: 320, Height: 200}, view) + canvas.EndFrame() + } + draw() + draw() + if n := testing.AllocsPerRun(100, draw); n != 0 { + t.Fatalf("a warm paint allocates %v times", n) + } +} + +func BenchmarkFormat(b *testing.B) { + b.ReportAllocs() + for i := 0; i < b.N; i++ { + statistic.Format(1234567.891, 2, ',') + } +} diff --git a/ui/text_selection.go b/ui/text_selection.go new file mode 100644 index 000000000..856e9d971 --- /dev/null +++ b/ui/text_selection.go @@ -0,0 +1,32 @@ +package ui + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/base" +) + +// TextSelectionState is the selection of one TextSelectionArea; keep it in the model. +type TextSelectionState = base.TextSelectionState + +// TextSelection is a selection that may begin in one painted text and end in +// another, for texts an application paints itself; TextPoint is a place in them and +// TextRange the selected part of one; TextSelectionResult says what a pointer event +// did to it. +type ( + TextSelection = base.TextSelection + TextPoint = base.TextPoint + TextRange = base.TextRange + TextSelectionResult = base.TextSelectionResult +) + +// TextSelectionArea declares a column whose texts the user can select and copy; +// see base.TextSelectionArea. +// +// ui.TextSelectionArea(c, &m.details).Gap(6).Children(func() { +// ui.Text(c, m.fingerprint) +// }) +func TextSelectionArea(c C, state *TextSelectionState) Box { + useEditMenu() + installPrimarySelection.Do(func() { base.SetPrimarySelection = app.SetPrimarySelection }) + return base.TextSelectionArea(c, state) +} diff --git a/ui/text_selection_test.go b/ui/text_selection_test.go new file mode 100644 index 000000000..65163dd6f --- /dev/null +++ b/ui/text_selection_test.go @@ -0,0 +1,504 @@ +package ui_test + +import ( + "strings" + "testing" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/keymap" + "github.com/vivaui/viva/ui" +) + +// selectable is a headless window with one TextSelectionArea, declared by body. +type selectable struct { + t *testing.T + driver *app.Driver + canvas *gfx.Canvas + area ui.TextSelectionState + body func(c ui.C) +} + +func openSelectable(t *testing.T, body func(c ui.C)) *selectable { + t.Helper() + s := &selectable{t: t, body: body} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(16).Gap(8).Children(func() { + ui.TextSelectionArea(c, &s.area).FillWidth().Gap(4).Children(func() { s.body(c) }) + }) + }}) + s.open(page) + return s +} + +func (s *selectable) open(page *ui.Page) { + s.t.Helper() + s.canvas = &gfx.Canvas{} + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 640, Height: 360}), s.canvas) + if err != nil { + s.t.Fatal(err) + } + s.t.Cleanup(driver.Close) + s.driver = driver + s.must(driver.Paint()) +} + +func (s *selectable) must(err error) { + s.t.Helper() + if err != nil { + s.t.Fatal(err) + } +} + +// painted is the line value as the last paint drew it. +func (s *selectable) painted(value string) gfx.Text { + s.t.Helper() + for _, text := range s.driver.Snapshot().Texts { + if text.Value == value { + return text + } + } + s.t.Fatalf("%q is not painted", value) + return gfx.Text{} +} + +func (s *selectable) text(value string) gfx.Rect { return s.painted(value).Bounds } + +// width is how wide the words of the line holding value are drawn: part of it, when +// part is a prefix of value. +func (s *selectable) width(value, part string) float32 { + return s.canvas.TextWidthStyle(part, s.painted(value).Style) +} + +// start and end are points just inside the first and the last character of a line. +func (s *selectable) start(value string) (float32, float32) { + r := s.text(value) + return r.X + 1, r.Y + r.Height/2 +} + +func (s *selectable) end(value string) (float32, float32) { + r := s.text(value) + return r.X + s.width(value, value) + 4, r.Y + r.Height/2 +} + +func (s *selectable) drag(fromX, fromY, toX, toY float32) { + s.t.Helper() + s.must(s.driver.Press(fromX, fromY, gfx.PointerButtonPrimary)) + s.must(s.driver.Move((fromX+toX)/2, (fromY+toY)/2)) + s.must(s.driver.Move(toX, toY)) + s.must(s.driver.Release(toX, toY, gfx.PointerButtonPrimary)) + s.must(s.driver.Paint()) +} + +// copied presses Primary+C and returns what reached the clipboard. +func (s *selectable) copied() string { + s.t.Helper() + s.driver.SetClipboard("") + _, err := s.driver.ShortcutChord(keymap.Primary, 'c') + s.must(err) + s.must(s.driver.Paint()) + return s.driver.Clipboard() +} + +// A drag from one text into another selects the end of the first and the start of the +// second, and copies them as their source, one per line. +func TestTextSelectionAreaDragsAcrossTexts(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "host key fingerprint") + ui.Text(c, "SHA256:abcdef") + }) + fx, fy := s.start("host key fingerprint") + tx, ty := s.end("SHA256:abcdef") + s.drag(fx, fy, tx, ty) + if got := s.copied(); got != "host key fingerprint\nSHA256:abcdef" { + t.Fatalf("copied %q", got) + } + if got := s.area.Text(); got != "host key fingerprint\nSHA256:abcdef" { + t.Fatalf("Text is %q", got) + } +} + +// A label and its value side by side in a row copy as one line, joined with a tab, so +// rows of them paste into a table. +func TestTextSelectionAreaJoinsARowWithATab(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + for _, row := range [][2]string{{"Address", "10.0.0.2"}, {"Type", "ed25519"}} { + ui.Row(c).Gap(6).Children(func() { + ui.Text(c, row[0]).Width(90) + ui.Text(c, row[1]) + }) + } + }) + _, err := s.driver.ShortcutChord(keymap.Primary, 'a') + s.must(err) + s.must(s.driver.Paint()) // nothing has the focus yet: the area does not take a page-wide Select All + fx, fy := s.start("Address") + tx, ty := s.end("ed25519") + s.drag(fx, fy, tx, ty) + if got := s.copied(); got != "Address\t10.0.0.2\nType\ted25519" { + t.Fatalf("copied %q", got) + } +} + +// A double press selects the word under the pointer and a triple press its line. +func TestTextSelectionAreaSelectsAWordAndALine(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "connection refused by peer") + }) + r := s.text("connection refused by peer") + line := "connection refused by peer" + x := r.X + s.width(line, "connection ") + (s.width(line, "connection refused")-s.width(line, "connection "))/2 + y := r.Y + r.Height/2 + s.must(s.driver.ClickCount(x, y, 2)) + s.must(s.driver.Paint()) + if got := s.copied(); got != "refused" { + t.Fatalf("a double press copied %q", got) + } + s.must(s.driver.ClickCount(x, y, 3)) + s.must(s.driver.Paint()) + if got := s.copied(); got != "connection refused by peer" { + t.Fatalf("a triple press copied %q", got) + } +} + +// Shift with a press extends the selection from where it began. +func TestTextSelectionAreaShiftPressExtends(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "first line") + ui.Text(c, "second line") + }) + r := s.text("first line") + x, y := r.X+s.width("first line", "first "), r.Y+r.Height/2 + s.must(s.driver.Click(x, y)) + tx, ty := s.end("second line") + s.must(s.driver.KeyDown(gfx.KeyShiftLeft, "")) + s.must(s.driver.Click(tx, ty)) + s.must(s.driver.KeyUp(gfx.KeyShiftLeft, "")) + s.must(s.driver.Paint()) + if got := s.copied(); got != "line\nsecond line" { + t.Fatalf("copied %q", got) + } +} + +// Text that belongs to a control is not selected: a press on a button inside the area +// clicks it, and Select All leaves its words out; nor is what Unselectable takes out. +func TestTextSelectionAreaLeavesControlsAlone(t *testing.T) { + clicks := 0 + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "error: timeout") + if ui.Button(c, "Retry").Clicked() { + clicks++ + } + ui.Text(c, "decoration").Unselectable() + ui.Text(c, "after") + }) + b := s.text("Retry") + s.must(s.driver.Click(b.X+b.Width/2, b.Y+b.Height/2)) + s.must(s.driver.Paint()) + if clicks != 1 { + t.Fatalf("the button inside the area was clicked %d times", clicks) + } + x, y := s.start("error: timeout") + s.must(s.driver.Click(x, y)) + s.must(s.driver.Paint()) + _, err := s.driver.ShortcutChord(keymap.Primary, 'a') + s.must(err) + s.must(s.driver.Paint()) + if got := s.copied(); got != "error: timeout\nafter" { + t.Fatalf("Select All copied %q", got) + } +} + +// A text cut short by an ellipsis copies whole. +func TestTextSelectionAreaCopiesTheTextAnEllipsisCut(t *testing.T) { + long := strings.Repeat("/very/long/remote/path", 12) + s := openSelectable(t, func(c ui.C) { + ui.Text(c, long).Ellipsis() + }) + var shown gfx.Rect + for _, text := range s.driver.Snapshot().Texts { + if strings.HasSuffix(text.Value, "…") { + shown = text.Bounds + } + } + if shown.Width == 0 { + t.Fatal("the text was not cut short") + } + y := shown.Y + shown.Height/2 + s.drag(shown.X+1, y, shown.X+shown.Width+40, y) + if got := s.copied(); got != long { + t.Fatalf("copied %d bytes of %d", len(got), len(long)) + } +} + +// Escape drops the selection; so does another control taking the keyboard, while a +// press on nothing leaves it. +func TestTextSelectionAreaDropsTheSelection(t *testing.T) { + var field string + s := &selectable{t: t} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(16).Gap(8).Children(func() { + ui.TextSelectionArea(c, &s.area).FillWidth().Children(func() { + ui.Text(c, "selected words") + }) + ui.Spacer(c).Height(80) + ui.TextField(c, &field, "Name", "type here").Width(200) + }) + }}) + s.open(page) + driver := s.driver + selectAll := func() { + x, y := s.start("selected words") + s.must(driver.Click(x, y)) + _, err := driver.ShortcutChord(keymap.Primary, 'a') + s.must(err) + s.must(driver.Paint()) + if !s.area.Has() { + t.Fatal("nothing was selected") + } + } + selectAll() + s.must(driver.Key(gfx.KeyEscape, 0)) + s.must(driver.Paint()) + if s.area.Has() { + t.Fatal("Escape left the selection") + } + selectAll() + s.must(driver.Click(600, 340)) + s.must(driver.Paint()) + if !s.area.Has() { + t.Fatal("a press on nothing dropped the selection") + } + r := s.text("type here") + s.must(driver.Click(r.X+r.Width/2, r.Y+r.Height/2)) + s.must(driver.Paint()) + if s.area.Has() { + t.Fatal("the selection stayed while a field had the keyboard") + } +} + +// A secondary press opens Copy and Select All; Copy puts the selection on the clipboard. +func TestTextSelectionAreaMenuCopies(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "ssh: handshake failed") + }) + fx, fy := s.start("ssh: handshake failed") + tx, ty := s.end("ssh: handshake failed") + s.drag(fx, fy, tx, ty) + s.must(s.driver.Press(fx+4, fy, gfx.PointerButtonSecondary)) + s.must(s.driver.Release(fx+4, fy, gfx.PointerButtonSecondary)) + s.must(s.driver.Paint()) + copyItem := s.text("Copy") + s.driver.SetClipboard("") + s.must(s.driver.Click(copyItem.X+copyItem.Width/2, copyItem.Y+copyItem.Height/2)) + s.must(s.driver.Paint()) + if got := s.driver.Clipboard(); got != "ssh: handshake failed" { + t.Fatalf("Copy put %q on the clipboard", got) + } +} + +// Shift with an arrow key moves the end of the selection by a character, into the next +// text past the end of one. +func TestTextSelectionAreaShiftArrowExtends(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "ab") + ui.Text(c, "cd") + }) + fx, fy := s.start("ab") + tx, ty := s.end("ab") + s.drag(fx, fy, tx, ty) + for range 2 { + s.must(s.driver.Key(gfx.KeyRight, gfx.ModifierShift)) + } + s.must(s.driver.Paint()) + if got := s.copied(); got != "ab\nc" { + t.Fatalf("copied %q", got) + } +} + +// A drag held below the scrolling area the texts are in scrolls it, and the selection +// follows into the texts it brings up. +func TestTextSelectionAreaDragScrollsItsArea(t *testing.T) { + s := &selectable{t: t} + lines := make([]string, 40) + for i := range lines { + lines[i] = "line " + string(rune('A'+i%26)) + strings.Repeat("x", i) + } + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Scroll(c).Height(200).FillWidth().Children(func() { + ui.TextSelectionArea(c, &s.area).FillWidth().Children(func() { + for _, line := range lines { + ui.Text(c, line) + } + }) + }) + }}) + s.open(page) + x, y := s.start(lines[0]) + s.must(s.driver.Press(x, y, gfx.PointerButtonPrimary)) + s.must(s.driver.Move(x, 150)) + s.must(s.driver.Move(x, 260)) // below the area's 200 pixels + for range 20 { + s.must(s.driver.Advance(50 * time.Millisecond)) + } + s.must(s.driver.Release(x, 260, gfx.PointerButtonPrimary)) + s.must(s.driver.Paint()) + got := s.area.Text() + if !strings.HasPrefix(got, lines[0]) || strings.Count(got, "\n") < 12 { + t.Fatalf("the drag selected %d lines: %q", strings.Count(got, "\n")+1, got) + } +} + +// Selecting fills the primary selection where the desktop has one. +func TestTextSelectionAreaFillsThePrimarySelection(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "middle click pastes this") + }) + if _, err := app.PrimarySelection(); err == app.ErrUnsupported { + t.Skip("only an X11 desktop has a primary selection") + } + fx, fy := s.start("middle click pastes this") + tx, ty := s.end("middle click pastes this") + s.drag(fx, fy, tx, ty) + if got, err := app.PrimarySelection(); err != nil || got != "middle click pastes this" { + t.Fatalf("the primary selection is %q (%v)", got, err) + } +} + +func selectionPage(area *ui.TextSelectionState) func(ui.C) { + return func(c ui.C) { + ui.TextSelectionArea(c, area).FillWidth().Gap(4).Children(func() { + for i := range 40 { + ui.Row(c).Gap(6).Children(func() { + ui.Text(c, detailLabels[i%len(detailLabels)]).Width(120) + ui.Paragraph(c, "a value long enough to wrap onto a second line at this width", 2).Width(180) + }) + } + }) + } +} + +var detailLabels = []string{"Address", "Fingerprint", "Type", "Saved"} + +// A steady page of selectable texts, with part of them selected, allocates nothing. +func TestTextSelectionAreaPaintAllocatesNothing(t *testing.T) { + var area ui.TextSelectionState + view := selectionPage(&area) + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + drawPage(page, canvas, view) + area.Selection.Select(ui.TextPoint{Surface: 3, Offset: 4}, ui.TextPoint{Surface: 30, Offset: 20}) + for range 3 { + drawPage(page, canvas, view) + } + if allocs := testing.AllocsPerRun(50, func() { drawPage(page, canvas, view) }); allocs != 0 { + t.Fatalf("a steady page of selectable texts allocates %v times", allocs) + } +} + +// BenchmarkTextSelectionArea is the cost of the same texts in an area and out of one. +func BenchmarkTextSelectionArea(b *testing.B) { + plain := func(c ui.C) { + ui.Column(c).FillWidth().Gap(4).Children(func() { + for i := range 40 { + ui.Row(c).Gap(6).Children(func() { + ui.Text(c, detailLabels[i%len(detailLabels)]).Width(120) + ui.Paragraph(c, "a value long enough to wrap onto a second line at this width", 2).Width(180) + }) + } + }) + } + var area ui.TextSelectionState + for _, bench := range []struct { + name string + view func(ui.C) + }{{"plain", plain}, {"area", selectionPage(&area)}} { + b.Run(bench.name, func(b *testing.B) { + page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() + drawPage(page, canvas, bench.view) + area.Selection.Select(ui.TextPoint{Surface: 3, Offset: 4}, ui.TextPoint{Surface: 30, Offset: 20}) + b.ReportAllocs() + for b.Loop() { + drawPage(page, canvas, bench.view) + } + }) + } +} + +// A group region that names its content for assistive technology does not take the +// text inside it out of the area, as a button does. +func TestTextSelectionAreaKeepsTheTextOfAGroupRegion(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Row(c).HitWith(ui.ID(c.Part("path")), "Path", gfx.HitOptions{Role: gfx.RoleGroup, SkipFocus: true, SkipTab: true}). + Children(func() { ui.Text(c, "/srv/backups/2026-11-26.tar.gz") }) + }) + fx, fy := s.start("/srv/backups/2026-11-26.tar.gz") + tx, ty := s.end("/srv/backups/2026-11-26.tar.gz") + s.drag(fx, fy, tx, ty) + if got := s.copied(); got != "/srv/backups/2026-11-26.tar.gz" { + t.Fatalf("copied %q", got) + } +} + +// A state copied into another field selects for that field, not for the one it was +// copied from. +func TestTextSelectionAreaStateCopiedByValue(t *testing.T) { + var first, second ui.TextSelectionState + showSecond := false + s := &selectable{t: t} + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + area := &first + if showSecond { + area = &second + } + ui.TextSelectionArea(c, area).FillWidth().Children(func() { ui.Text(c, "copied state") }) + }}) + s.open(page) + fx, fy := s.start("copied state") + tx, ty := s.end("copied state") + s.drag(fx, fy, tx, ty) + second, showSecond = first, true + first.Clear() + s.must(s.driver.Paint()) + s.drag(fx, fy, fx+20, fy) + if first.Has() || !second.Has() { + t.Fatalf("first has %q, second %q", first.Text(), second.Text()) + } +} + +// Select All from the menu selects everything and gives the area the keyboard back, so +// Primary+C copies what it selected. +func TestTextSelectionAreaMenuGivesTheKeyboardBack(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Text(c, "first") + ui.Text(c, "second") + }) + x, y := s.start("first") + s.must(s.driver.Press(x, y, gfx.PointerButtonSecondary)) + s.must(s.driver.Release(x, y, gfx.PointerButtonSecondary)) + s.must(s.driver.Paint()) + item := s.text("Select All") + s.must(s.driver.Click(item.X+item.Width/2, item.Y+item.Height/2)) + s.must(s.driver.Paint()) + s.must(s.driver.Paint()) + if got := s.copied(); got != "first\nsecond" { + t.Fatalf("copied %q after Select All", got) + } +} + +// A drag that begins in the blank part of the area, beside the words, selects from the +// nearest of them. +func TestTextSelectionAreaDragFromTheBlankBeside(t *testing.T) { + s := openSelectable(t, func(c ui.C) { + ui.Row(c).Gap(24).Children(func() { + ui.Spacer(c).Width(30) + ui.Text(c, "build 2026.11.26") + }) + }) + r := s.text("build 2026.11.26") + tx, ty := s.end("build 2026.11.26") + s.drag(r.X-12, ty, tx, ty) + if got := s.copied(); got != "build 2026.11.26" { + t.Fatalf("copied %q", got) + } +} diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index a6eaca8c7..d382a412a 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -27,7 +27,7 @@ A page control for a heavy or stateful component lives in its own package under - Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid` - Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard` -- Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer` +- Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer` `ui/textview` displays read-only text that the user can select and copy, such as logs and process output. Keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`; `textview.Strings` adapts a string slice. The caller owns the lines, styles and actions. The view owns selection and drawing without an editing or undo model. diff --git a/website/content/guides/en/system-integration.md b/website/content/guides/en/system-integration.md index 5ff1165a0..ff2ecdc0a 100644 --- a/website/content/guides/en/system-integration.md +++ b/website/content/guides/en/system-integration.md @@ -149,6 +149,126 @@ func main() { } ``` +## Status item previews + +`StatusItem.SetHoverPreview` lets an application supply a small window while Viva +owns paired pointer events, anchoring and delayed close. Handle the error passed +to `StatusPreview.Opened` to release prepared content if the window cannot open. +Call `RefreshMenu` when application state changes; Linux hosts may cache menus. + +Windows supports hover on visible taskbar icons, macOS on status bar buttons. +Linux's StatusNotifier protocol does not provide paired hover events, so keep a +click or menu fallback. X11 uses the activation point supplied by the host. Its +coordinate units are not specified: a host sending logical coordinates on a +scaled desktop may misplace the panel. Do not infer a coordinate scale or a +keyboard activation from the pointer's proximity. Wayland placement belongs to +the compositor. See [conformance boundaries](https://github.com/vivaui/viva/blob/main/docs/conformance.md#status-previews) +for what still needs verification on physical desktops. + +Run `go run ./examples/guides/status-preview` to try the complete example. + + +```go +package main + +import ( + "fmt" + "log" + "runtime" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +// AppKit must start on the process's main thread. +func init() { runtime.LockOSThread() } + +func main() { + if err := app.RunApplication(run); err != nil { + log.Fatal(err) + } +} + +func run(application *app.Application) error { + var main, preview *app.Window + var tray *app.StatusItem + var wake, previewWake app.Invalidator + unread := 1 + show := func() { + if preview != nil { + preview.Close() + } + main.Show() + } + build := func() app.StatusPreview { + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(8).Children(func() { + ui.Text(c, fmt.Sprintf("%d unread messages", unread)) + if ui.Button(c, "Open application").Clicked() { + c.Canvas().AfterPaint(show) + } + }) + }}) + config := ui.Configure(page, app.Config{ + Title: "Unread messages", Width: 240, Height: 96, Invalidator: &previewWake, + OnClosed: func() { preview = nil }, + }) + return app.StatusPreview{Config: config, Opened: func(window *app.Window, err error) { + if err != nil { + page.Close() + log.Printf("open status preview: %v", err) + return + } + preview = window + }} + } + var err error + main, err = ui.OpenWindow(application, app.Config{Title: "Status preview", Width: 400, Height: 180, Invalidator: &wake}, ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + ui.Text(c, fmt.Sprintf("%d unread messages", unread)) + if ui.Button(c, "Add a message").Clicked() { + unread++ + previewWake.Invalidate() + if tray != nil { + // Linux hosts cache their menu. Notify them when its text changes. + tray.RefreshMenu() + } + } + }) + }, + }) + if err != nil { + return err + } + tray, err = application.AddStatusItem(app.StatusItemConfig{ + Tooltip: "Status preview", Icon: app.StatusIcon{Size: 1, RGBA: []byte{70, 130, 210, 255}, Template: true}, + OnClick: func(click app.StatusClick) { + if click.PanelDismissed { + return + } + // Click remains available on hosts without paired hover events. + spec := build() + spec.Config.WindowMode, spec.Config.Anchor = app.WindowPanel, click.Anchor + window, err := application.OpenWindow(spec.Config, nil) + spec.Opened(window, err) + }, + Menu: func() []app.MenuItem { + return []app.MenuItem{ + {Title: fmt.Sprintf("%d unread messages", unread), ID: "unread", OnSelect: show}, + {Title: "Quit", OnSelect: application.Quit}, + } + }, + }) + if err != nil { + log.Printf("status area unavailable; main window remains usable: %v", err) + return nil + } + tray.SetHoverPreview(build) + return nil +} +``` + ## Boundaries worth knowing - Linux file dialogs and notifications use the desktop's portal and notification service over D-Bus, and start an installed desktop utility only on a desktop without them; URL dispatch always does. Viva does not bundle GTK or Qt. diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index c33368507..89580825c 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -27,7 +27,7 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") - 编辑器与可视化:`ui/codeeditor`、`ui/textview`、`ui/chart`、`ui/markdown`、`ui/image`、`ui/calendar`、`ui/carousel`、`ui/columnresize`、`ui/reordergrid` - 导航与浮层:`ui/command`、`ui/menubar`、`ui/navigationmenu`、`ui/sidebar`、`ui/hovercard` -- 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup`、`ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker`、`ui/transfer`、`ui/alert`、`ui/tag`、`ui/breadcrumb`、`ui/card`、`ui/empty`、`ui/result`、`ui/pagination`、`ui/editabletabs`、`ui/popconfirm`、`ui/divider`、`ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour` +- 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup`、`ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker`、`ui/transfer`、`ui/alert`、`ui/tag`、`ui/breadcrumb`、`ui/card`、`ui/empty`、`ui/result`、`ui/pagination`、`ui/editabletabs`、`ui/popconfirm`、`ui/divider`、`ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` `ui/textview` 用来显示可选择、可复制的只读文本,例如日志和进程输出。在 model 中保留 `textview.View`,调用 `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`;`textview.Strings` 可以把字符串切片适配成数据源。调用方拥有文本、样式和动作,视图负责选择与绘制,不带编辑或撤销模型。 diff --git a/website/content/guides/zh/system-integration.md b/website/content/guides/zh/system-integration.md index 60131b5b0..5fabfecd5 100644 --- a/website/content/guides/zh/system-integration.md +++ b/website/content/guides/zh/system-integration.md @@ -149,6 +149,116 @@ func main() { } ``` +## 托盘预览 + +`StatusItem.SetHoverPreview` 让应用提供一个小窗口,Viva 负责成对的进入、离开事件、锚定和延迟关闭。通过 `StatusPreview.Opened` 接收打开错误,在失败时释放已经准备的页面。应用状态变化后调用 `RefreshMenu`,让缓存菜单的 Linux 宿主刷新内容。 + +Windows 支持可见任务栏图标的悬停,macOS 支持状态栏按钮。Linux 的 StatusNotifier 协议不提供成对悬停事件,因此需要保留点击或菜单入口。X11 原样使用宿主给出的激活点;协议没有标明坐标单位,缩放桌面上的宿主若给出逻辑坐标,浮层仍可能偏移,不能通过鼠标距离猜测缩放或键盘激活。Wayland 定位由合成器决定。需要实机验证的边界见[平台一致性记录](https://github.com/vivaui/viva/blob/main/docs/conformance.md#status-previews)。 + +执行 `go run ./examples/guides/status-preview` 可以运行完整示例。 + + +```go +package main + +import ( + "fmt" + "log" + "runtime" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +// AppKit must start on the process's main thread. +func init() { runtime.LockOSThread() } + +func main() { + if err := app.RunApplication(run); err != nil { + log.Fatal(err) + } +} + +func run(application *app.Application) error { + var main, preview *app.Window + var tray *app.StatusItem + var wake, previewWake app.Invalidator + unread := 1 + show := func() { + if preview != nil { + preview.Close() + } + main.Show() + } + build := func() app.StatusPreview { + page := ui.NewPage(ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(12).Gap(8).Children(func() { + ui.Text(c, fmt.Sprintf("%d unread messages", unread)) + if ui.Button(c, "Open application").Clicked() { + c.Canvas().AfterPaint(show) + } + }) + }}) + config := ui.Configure(page, app.Config{ + Title: "Unread messages", Width: 240, Height: 96, Invalidator: &previewWake, + OnClosed: func() { preview = nil }, + }) + return app.StatusPreview{Config: config, Opened: func(window *app.Window, err error) { + if err != nil { + page.Close() + log.Printf("open status preview: %v", err) + return + } + preview = window + }} + } + var err error + main, err = ui.OpenWindow(application, app.Config{Title: "Status preview", Width: 400, Height: 180, Invalidator: &wake}, ui.PageConfig{ + View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + ui.Text(c, fmt.Sprintf("%d unread messages", unread)) + if ui.Button(c, "Add a message").Clicked() { + unread++ + previewWake.Invalidate() + if tray != nil { + // Linux hosts cache their menu. Notify them when its text changes. + tray.RefreshMenu() + } + } + }) + }, + }) + if err != nil { + return err + } + tray, err = application.AddStatusItem(app.StatusItemConfig{ + Tooltip: "Status preview", Icon: app.StatusIcon{Size: 1, RGBA: []byte{70, 130, 210, 255}, Template: true}, + OnClick: func(click app.StatusClick) { + if click.PanelDismissed { + return + } + // Click remains available on hosts without paired hover events. + spec := build() + spec.Config.WindowMode, spec.Config.Anchor = app.WindowPanel, click.Anchor + window, err := application.OpenWindow(spec.Config, nil) + spec.Opened(window, err) + }, + Menu: func() []app.MenuItem { + return []app.MenuItem{ + {Title: fmt.Sprintf("%d unread messages", unread), ID: "unread", OnSelect: show}, + {Title: "Quit", OnSelect: application.Quit}, + } + }, + }) + if err != nil { + log.Printf("status area unavailable; main window remains usable: %v", err) + return nil + } + tray.SetHoverPreview(build) + return nil +} +``` + ## 值得了解的边界 - Linux 上的文件对话框、URL 分发和通知,会在用户请求时启动已安装的桌面工具。Viva 不捆绑 GTK、Qt 或 D-Bus 栈。 diff --git a/website/src/lib/i18n.ts b/website/src/lib/i18n.ts index db433dbd8..fe33c7084 100644 --- a/website/src/lib/i18n.ts +++ b/website/src/lib/i18n.ts @@ -187,6 +187,11 @@ const chineseComponentNames: Record = { 'image-preview': '图片预览', mentions: '提及', tour: '引导', + 'overflow-list': '折叠列表', + statistic: '统计数值', + 'input-tag': '标签输入', + autocomplete: '自动补全', + indicator: '角标', 'labeled-divider': '带文字分隔线', 'editable-tabs': '可编辑标签页', steps: '步骤条', @@ -326,6 +331,21 @@ const englishComponents: Record