From b987c21a625ca97057db2acbb2489e3272c67d7c Mon Sep 17 00:00:00 2001 From: Dean Cen Date: Mon, 16 Nov 2026 10:04:26 +0800 Subject: [PATCH 01/13] test(update): expect the Windows recovery launcher --- update/install_windows_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/update/install_windows_test.go b/update/install_windows_test.go index 407a326f2..bbdd53c6e 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -244,7 +244,7 @@ func TestPayloadHelperScriptKeepsABackupAndRestores(t *testing.T) { "Copy-Item -LiteralPath $_.FullName -Destination $dest -Force", "Start-Process -FilePath $exe -PassThru", "$p.HasExited -and $p.ExitCode -ne 0", - "Restore; Start-Process -FilePath $exe", + "Restore; Launch", "Remove-Item -Recurse -Force $payload", "exit 0", } { From 61a660f30681a82b90a7c74ad84ce165ebaff108 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:05:25 +0800 Subject: [PATCH 02/13] fix(text): retain LF labels when composition compacts backing --- text/composition_retention.go | 12 ++- text/lf_labels.go | 17 ++++ text/lf_labels_tentative_bench_test.go | 66 +++++++++++++ text/lf_labels_tentative_rekey_test.go | 131 +++++++++++++++++++++++++ 4 files changed, 224 insertions(+), 2 deletions(-) create mode 100644 text/lf_labels_tentative_bench_test.go create mode 100644 text/lf_labels_tentative_rekey_test.go diff --git a/text/composition_retention.go b/text/composition_retention.go index 1ff8c151d..20374b6b2 100644 --- a/text/composition_retention.go +++ b/text/composition_retention.go @@ -49,14 +49,22 @@ func (editor *Editor) ownCompositionEventText(state *compositionState) { } func (editor *Editor) ownCompositionUnitText(edit *historyEdit) { - + labels := editor.lfLabelState() + var previousKey *rune + if labels != nil { + previousKey = lfLabelHistoryKey(edit) + } if cap(edit.removed) != len(edit.removed) { edit.removed = ownRunes(edit.removed) } if cap(edit.inserted) != len(edit.inserted) { edit.inserted = ownRunes(edit.inserted) } - + if labels != nil { + if currentKey := lfLabelHistoryKey(edit); currentKey != previousKey { + labels.ops.rekey(labels, previousKey, currentKey) + } + } } // reserveCompositionHistory gives the planned event exact backing capacity so diff --git a/text/lf_labels.go b/text/lf_labels.go index 9f21e940c..490a0950f 100644 --- a/text/lf_labels.go +++ b/text/lf_labels.go @@ -30,6 +30,7 @@ type lfLabelEntry struct { type lfLabelOps struct { replace func(*lfLabelState, int, []rune, []rune) record func(*lfLabelState, *rune, *rune) + rekey func(*lfLabelState, *rune, *rune) replay func(*lfLabelState, *rune, bool) forget func(*lfLabelState, *rune) clear func(*lfLabelState) @@ -80,6 +81,7 @@ func (editor *Editor) TrackLFLabels(labels []byte, defaultLabel byte, mapper LFL ops: lfLabelOps{ replace: replaceLFLabels, record: recordLFLabels, + rekey: rekeyLFLabels, replay: replayLFLabels, forget: forgetLFLabels, clear: clearLFLabelHistory, @@ -317,6 +319,21 @@ func recordLFLabels(state *lfLabelState, previous, current *rune) { } } +// Compaction changes a unit's backing, not its LF edits. A held composition +// still owns the old key, so preserve its map before moving the current entry. +func rekeyLFLabels(state *lfLabelState, previous, current *rune) { + if previous == current { + return + } + entry, exists := state.history[previous] + if !exists { + return + } + ensureLFLabelHistoryOwned(state) + delete(state.history, previous) + state.history[current] = entry +} + func replayLFLabels(state *lfLabelState, key *rune, inverse bool) { if state.mapping { panic("text: LF label mapper reentered history") diff --git a/text/lf_labels_tentative_bench_test.go b/text/lf_labels_tentative_bench_test.go new file mode 100644 index 000000000..a38e42cb0 --- /dev/null +++ b/text/lf_labels_tentative_bench_test.go @@ -0,0 +1,66 @@ +package text + +import "testing" + +func BenchmarkLFLabelsTentativeWorkflow(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + editor := NewEditor("a\nbc") + if !editor.TrackLFLabels([]byte("W"), 'L', nil) || !editor.EnableTentativeComposition() { + b.Fatal("capability setup refused") + } + editor.MoveTo(1, false) + editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: "x"}) + editor.ApplyComposition(CompositionEvent{Phase: CompositionResult, Text: "yz"}) + editor.Undo() + editor.Redo() + tentativeCoreEditorSink = editor + } + labels, ok := tentativeCoreEditorSink.LFLabels(nil) + if tentativeCoreEditorSink.String() != "ayz\nbc" || tentativeCoreEditorSink.CompositionActive() || !ok || string(labels) != "W" { + b.Fatal("workflow did not retain its committed result") + } +} + +func BenchmarkLFLabelsTentativeRekey(b *testing.B) { + for _, legacy := range []bool{false, true} { + name := "prestart-deletion" + if legacy { + name = "legacy-held-history" + } + b.Run(name, func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte("W"), 'M', nil) { + b.Fatal("label setup refused") + } + editor.SetSelection(Range{Start: 1, End: 2}) + if legacy { + editor.Insert("") + } + if !editor.EnableTentativeComposition() { + b.Fatal("capability setup refused") + } + if legacy { + editor.SetMarkedText("q\n", Range{End: 2}) + if !editor.CancelComposition() { + b.Fatal("legacy cancellation refused") + } + } else if !editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: "q\n"}) || + !editor.ApplyComposition(CompositionEvent{Phase: CompositionCancel}) { + b.Fatal("tentative event refused") + } + if !editor.Undo() || !editor.Redo() { + b.Fatal("deletion replay refused") + } + tentativeCoreEditorSink = editor + } + // Both versions replay the deletion text; baseline LF metadata is + // broken. The regression tests verify labels through Undo and Redo. + if tentativeCoreEditorSink.String() != "ab" || tentativeCoreEditorSink.CompositionActive() { + b.Fatal("workflow did not retain its replayed deletion") + } + }) + } +} diff --git a/text/lf_labels_tentative_rekey_test.go b/text/lf_labels_tentative_rekey_test.go new file mode 100644 index 000000000..7b0c92408 --- /dev/null +++ b/text/lf_labels_tentative_rekey_test.go @@ -0,0 +1,131 @@ +package text + +import ( + "fmt" + "testing" +) + +func TestLFLabelTentativePrestartDeletionReplay(t *testing.T) { + for _, phase := range []CompositionPhase{CompositionCancel, CompositionResult, CompositionCommit} { + for _, save := range []bool{false, true} { + t.Run(fmt.Sprintf("phase-%d/save-%t", phase, save), func(t *testing.T) { + editor := NewEditor("a\nb\nc\nd") + if !editor.TrackLFLabels([]byte("WLM"), 'W', nil) || !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetSelection(Range{Start: 1, End: 2}) + if !editor.ApplyComposition(CompositionEvent{Phase: CompositionUpdate, Text: "x\n"}) || + !editor.ApplyComposition(CompositionEvent{Phase: phase, Text: "x\n"}) { + t.Fatal("tentative event refused") + } + if editor.CompositionActive() { + t.Fatal("terminal event left a live composition") + } + if save { + editor.SetSavePoint() + } + if phase != CompositionCancel { + if editor.String() != "ax\nb\nc\nd" { + t.Fatalf("committed text = %q", editor.String()) + } + assertLFLabels(t, editor, []byte("WLM")) + if !editor.Undo() { + t.Fatal("result Undo refused") + } + } + if editor.String() != "ab\nc\nd" { + t.Fatalf("post-preedit text = %q", editor.String()) + } + assertLFLabels(t, editor, []byte("LM")) + if !editor.Undo() || editor.String() != "a\nb\nc\nd" || editor.CanUndo() { + t.Fatalf("prestart deletion Undo = %q", editor.String()) + } + assertLFLabels(t, editor, []byte("WLM")) + if !editor.SetLFLabels([]byte("ZLM"), 'W') { + t.Fatal("restored LF identities cannot be relabeled") + } + if !editor.Redo() || editor.String() != "ab\nc\nd" { + t.Fatalf("prestart deletion Redo = %q", editor.String()) + } + assertLFLabels(t, editor, []byte("LM")) + if phase != CompositionCancel { + if !editor.Redo() || editor.String() != "ax\nb\nc\nd" { + t.Fatalf("result Redo = %q", editor.String()) + } + assertLFLabels(t, editor, []byte("WLM")) + if !editor.Undo() { + t.Fatal("repeated result Undo refused") + } + } + if !editor.Undo() || editor.String() != "a\nb\nc\nd" { + t.Fatalf("repeated deletion Undo = %q", editor.String()) + } + assertLFLabels(t, editor, []byte("ZLM")) + }) + } + } +} + +func TestLFLabelTentativeCoalescedInsertedKeysReplayRelabel(t *testing.T) { + editor := NewEditor("a\nb") + calls := 0 + if !editor.TrackLFLabels([]byte("W"), 'M', func(LFLabelReplacement) []byte { + calls++ + return []byte("M") + }) { + t.Fatal("label setup refused") + } + editor.MoveTo(editor.RuneCount(), false) + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + for _, want := range []string{"a\nb\n", "a\nb\n\n", "a\nb\n\n\n"} { + if !editor.ApplyComposition(CompositionEvent{Phase: CompositionResult, Text: "\n"}) || editor.String() != want { + t.Fatalf("direct result = %q, want %q", editor.String(), want) + } + } + assertLFLabels(t, editor, []byte("WMMM")) + if !editor.SetLFLabels([]byte("WXYZ"), 'M') { + t.Fatal("inserted LF identities cannot be relabeled") + } + // Explicit insertion-mode Result events preserve source coalescing, + // including their LF scalars, so these three results share one unit. + for range 3 { + if !editor.Undo() || editor.String() != "a\nb" || editor.CanUndo() { + t.Fatalf("coalesced result Undo = %q, want original text in one unit", editor.String()) + } + assertLFLabels(t, editor, []byte("W")) + if !editor.Redo() || editor.String() != "a\nb\n\n\n" { + t.Fatalf("coalesced result Redo = %q", editor.String()) + } + assertLFLabels(t, editor, []byte("WXYZ")) + } + if calls != 3 { + t.Fatalf("compaction or replay reran the label mapper: %d calls, want 3", calls) + } +} + +func TestLFLabelTentativeCompactionPreservesLegacyHeldHistory(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte("W"), 'M', nil) { + t.Fatal("label setup refused") + } + editor.SetSelection(Range{Start: 1, End: 2}) + editor.Insert("") + if !editor.EnableTentativeComposition() { + t.Fatal("capability setup refused") + } + editor.SetMarkedText("q\n", Range{End: 2}) + if !editor.CancelComposition() || editor.String() != "ab" { + t.Fatalf("legacy cancellation = %q, want ab", editor.String()) + } + assertLFLabels(t, editor, nil) + if !editor.Undo() || editor.String() != "a\nb" || editor.CanUndo() { + t.Fatalf("held deletion Undo = %q", editor.String()) + } + assertLFLabels(t, editor, []byte("W")) + if !editor.Redo() || editor.String() != "ab" { + t.Fatalf("held deletion Redo = %q", editor.String()) + } + assertLFLabels(t, editor, nil) +} From e9a6a7a91e467e7ca38085752f382c89fadcde4b Mon Sep 17 00:00:00 2001 From: jakey <267309453@qq.com> Date: Mon, 16 Nov 2026 10:06:04 +0800 Subject: [PATCH 03/13] fix(components): keep a menu row unlit on menu padding --- app/painter.go | 19 ++- app/painter_test.go | 35 ++++++ cmd/viva/templates/dropdown_menu.go.txt | 26 +++- components/context_menu_padding_test.go | 159 ++++++++++++++++++++++++ components/dropdown_menu.go | 26 +++- gfx/canvas.go | 45 +++++++ gfx/replay.go | 2 +- internal/devreload/supervisor.go | 3 +- internal/input/input.go | 29 +++++ internal/input/input_test.go | 44 +++++++ internal/interaction/focus.go | 1 + internal/platform/web/painter.go | 17 ++- internal/reloadwire/canvas.go | 6 +- internal/reloadwire/codec.go | 29 +++-- internal/reloadwire/motion_test.go | 43 +++++++ internal/reloadwire/reloadwire_test.go | 1 + internal/reloadwire/worker.go | 3 + 17 files changed, 455 insertions(+), 33 deletions(-) create mode 100644 components/context_menu_padding_test.go diff --git a/app/painter.go b/app/painter.go index 4b4858d27..79f7cd59b 100644 --- a/app/painter.go +++ b/app/painter.go @@ -147,9 +147,13 @@ type painter struct { // The press keeps the pointer until the button comes up, so the exit waits // for the release instead of ending a drag at the window's edge. pointerOutside bool - cursor Cursor - scrollX float32 - scrollY float32 + // onSurface says the pointer is on a surface the page declared with + // gfx.Canvas.BlockSurface, such as an open menu's panel. It is recorded with + // the hit test and read back into the next paint. + onSurface bool + cursor Cursor + scrollX float32 + scrollY float32 // scheduleFrame asks the runtime for one more frame, after at least the // delay, while a transition is in flight or the application asked for one. scheduleFrame func(delay time.Duration) @@ -279,6 +283,7 @@ func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Fram // exactly where the user needs it: past the edge of the terminal, the // list or the window. The exit is delivered when the button is released. painter.pointerOutside = true + painter.onSurface = false if painter.pointer.Hovered().IsZero() { return platform.Frame{}, nil } @@ -287,6 +292,7 @@ func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Fram return painter.repaintAfterInput() } beforeHovered, beforePressed := painter.pointer.Hovered(), painter.pointer.Pressed() + beforeSurface := painter.onSurface beforeFocus, beforeKeyboard := painter.focus.Focused(), painter.focus.KeyboardFocus() passes := event.Kind == platform.PointerDown && (event.Button == gfx.PointerButtonSecondary && painter.focus.Router().PassesSecondary(event.X, event.Y) || @@ -332,6 +338,7 @@ func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Fram } if painter.pointer.Hovered() == beforeHovered && painter.pointer.Pressed() == beforePressed && + painter.onSurface == beforeSurface && painter.focus.Focused() == beforeFocus && painter.focus.KeyboardFocus() == beforeKeyboard && !focusChanged && !result.Repaint { if edgeChanged { @@ -349,10 +356,12 @@ func (painter *painter) pointerEvent(event platform.PointerEvent) (platform.Fram func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.EventResult, focusChanged, edgeChanged bool) { painter.pointer.SetHovered(gfx.ID{}) painter.pointer.SetHoveredRole(gfx.Role(0)) + painter.onSurface = false if event.Kind != platform.PointerExit { - if target, ok := painter.focus.Router().HitTestRegion(event.X, event.Y); ok { + if target, ok, onSurface := painter.focus.Router().PointerAt(event.X, event.Y); ok || onSurface { painter.pointer.SetHovered(target.Target) painter.pointer.SetHoveredRole(target.Role) + painter.onSurface = onSurface } } edgeChanged = painter.trackEdge(event) @@ -915,6 +924,7 @@ func (painter *painter) paintCanvas() { focused, visible := painter.focus.PaintTarget() painter.canvas.SetInteraction(painter.pointer.Hovered(), painter.pointer.Pressed(), focused, visible) painter.canvas.SetHoveredRole(painter.pointer.HoveredRole()) + painter.canvas.SetPointerOnSurface(painter.onSurface) painter.canvas.SetScroll(painter.scrollX, painter.scrollY) painter.canvas.BeginFrame() painter.paint(painter.canvas, painter.size) @@ -1937,6 +1947,7 @@ func sameRegionHit(published, current *gfx.Hit) bool { published.FocusableDisabled == current.FocusableDisabled && published.SkipTab == current.SkipTab && published.Block == current.Block && + published.BlockSurface == current.BlockSurface && published.Container == current.Container && published.IsLabel == current.IsLabel && published.Backdrop == current.Backdrop && diff --git a/app/painter_test.go b/app/painter_test.go index 4ada51e45..33e2a1867 100644 --- a/app/painter_test.go +++ b/app/painter_test.go @@ -766,6 +766,41 @@ func TestPointerHoverEntersAndExitsOnce(t *testing.T) { } } +// A drag off a surface and out of the window ends the surface state even when no +// hit is hovered: the early return must not leave the host's copy of the flag set +// for the next paint. +func TestPointerExitWhileDraggingOffTheSurfaceClearsIt(t *testing.T) { + var canvas gfx.Canvas + config := Config{Title: "test", Width: 100, Height: 100} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.Fill(gfx.Rect{X: 0, Y: 0, Width: 100, Height: 100}, gfx.Color{Alpha: 1}) + canvas.Hit(gfx.Item(7), gfx.Rect{X: 0, Y: 0, Width: 20, Height: 20}) + canvas.BlockSurface(gfx.Rect{X: 40, Y: 40, Width: 40, Height: 40}) + } + painter := newTestPainter(t, &canvas, config) + + // A press on the control captures the pointer. + down := platform.PointerEvent{Kind: platform.PointerDown, X: 10, Y: 10, Button: gfx.PointerButtonPrimary} + if _, err := painter.pointerEvent(down); err != nil { + t.Fatal(err) + } + // Dragging onto the surface leaves no hit while putting the pointer on it. + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerMove, X: 60, Y: 60}); err != nil { + t.Fatal(err) + } + if !painter.onSurface || !painter.pointer.Hovered().IsZero() { + t.Fatalf("dragging onto the surface: onSurface = %v, hovered = %d", painter.onSurface, painter.pointer.Hovered()) + } + + // Leaving the window keeps the press but ends the surface state, hit or no hit. + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerExit}); err != nil { + t.Fatal(err) + } + if painter.onSurface { + t.Fatal("the surface flag survived a drag that left the window") + } +} + func TestPointerClickActivatesAndPressOnlyCountsInsideRegion(t *testing.T) { var canvas gfx.Canvas canvas.Hit(gfx.Item(7), gfx.Rect{X: 0, Y: 0, Width: 50, Height: 20}) diff --git a/cmd/viva/templates/dropdown_menu.go.txt b/cmd/viva/templates/dropdown_menu.go.txt index b0b17bb21..e699fb29d 100644 --- a/cmd/viva/templates/dropdown_menu.go.txt +++ b/cmd/viva/templates/dropdown_menu.go.txt @@ -796,7 +796,11 @@ func beginMenuSurface(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, minW menu.paintDismissBackdrop() // The surface itself is inside the menu: a press on its padding, a label, a // separator, or a disabled row must not reach the dismiss backdrop behind it. - menu.canvas.Block(bounds) + // Saying the pointer is on the surface also tells a row whether the pointer is + // on the menu at all: over the padding and the separators the pointer is on the + // menu but on no row, and treating that as "outside" relit the row that kept + // focus. + menu.canvas.BlockSurface(bounds) menu.canvas.Container(bounds, gfx.RoleMenu, "") part := overlaySurfacePart if options.submenu { @@ -1047,11 +1051,21 @@ func (menu *menuSurface) itemState(item menuItem) (active bool, foreground gfx.C enabled := !item.ID.IsZero() && !item.Disabled hovered := canvas.Hovered() claim := canvas.HoverCrossed() && !hovered.IsZero() - // While the pointer is over caller content inside the menu (a colour row, a - // switch), no row is the menu's current row: keeping the last focused row - // tinted would fight the control under the pointer. Menu rows themselves - // declare RoleMenuItem. - inContent := !hovered.IsZero() && canvas.HoveredRole() != 0 && canvas.HoveredRole() != gfx.RoleMenuItem + // No row is the menu's current one while the pointer is on the menu but not on + // a row. That covers the pointer over caller content inside the menu (a colour + // row, a switch), which declares a role that is not a row's, and the pointer + // over the menu's own padding and separators, which report the surface rather + // than a hit. Without the second case the row that kept focus relit whenever the + // pointer came back into the menu anywhere but on a row. + // + // Visible keyboard focus outranks a resting pointer, wherever it rests: a key + // press moves the menu's current row while the pointer sits on the padding or on + // a control of the caller's, and that row must stay lit. Focus that the pointer + // itself moved is not visible, so the row it entered still gives way to whatever + // is under the pointer. + inContent := canvas.FocusVisible().IsZero() && + (canvas.PointerOnSurface() || + !hovered.IsZero() && canvas.HoveredRole() != 0 && canvas.HoveredRole() != gfx.RoleMenuItem) if claim && hovered == item.ID { // A disabled row cannot take focus, but the frame is still repainted so // the row that kept focus is tinted again on the next paint. diff --git a/components/context_menu_padding_test.go b/components/context_menu_padding_test.go new file mode 100644 index 000000000..b0b079e91 --- /dev/null +++ b/components/context_menu_padding_test.go @@ -0,0 +1,159 @@ +package components + +import ( + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +// A menu remembers the row the pointer focused. That row must stay unlit while +// the pointer is anywhere else, including the menu's own padding and separators, +// which declare no hit of their own: a pointer travelling over them is on the +// menu, not on the page behind it. +func TestMenuRowStaysUnlitOverTheMenusOwnPadding(t *testing.T) { + var tree gfx.Tree + feature := tree.Feature("menu-padding") + scope := gfx.Item(64) + theme := gfx.DarkTheme() + var rows []gfx.Rect + var menuBounds, separator gfx.Rect + driver, err := app.NewDriver(app.Config{ + Width: 320, Height: 240, Tree: &tree, + Paint: func(c *gfx.Canvas, size gfx.Size) { + menu := BeginContextMenu(c, theme, gfx.Rect{X: 20, Y: 20, Width: 200, Height: 160}, ContextMenuOptions{ + Layer: 7, Scope: scope, DismissID: tree.ID(feature, "dismiss"), Viewport: gfx.Rect{Width: 320, Height: 240}, + }) + menuBounds = menu.Bounds() + rows = rows[:0] + for i := 0; i < 4; i++ { + rows = append(rows, menu.AddItem(ContextMenuItem{ID: tree.ID(feature, string(rune('a'+i))), Label: "Row"})) + } + separator = menu.AddSeparator() + menu.End() + }, + }, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + + move := func(x, y float32) { + t.Helper() + if err := driver.Move(x, y); err != nil { + t.Fatal(err) + } + } + row := rows[3] + rowTinted := func() bool { + t.Helper() + for _, primitive := range driver.Snapshot().Primitives { + if primitive.Color == theme.Accent && primitive.Bounds == row { + return true + } + } + return false + } + // Hovering the row makes it the menu's current row. + move(row.X+row.Width/2, row.Y+row.Height/2) + move(row.X+row.Width/2+1, row.Y+row.Height/2) + if !rowTinted() { + t.Fatal("hovering the row did not tint it: the test cannot see the state it checks") + } + + // The pointer leaves the menu entirely. + move(300, 230) + if rowTinted() { + t.Fatal("the row is still tinted with the pointer outside the menu") + } + + // It comes back over the menu's top padding, which is not a row. + move(menuBounds.X+40, menuBounds.Y+2) + if rowTinted() { + t.Fatal("the row relit as the pointer entered the menu's padding") + } + + // And over the separator, also not a row. The pointer lights a row first, so + // the frame after the move is a repaint that had the row lit: the assertion is + // about the separator putting it out, not about the padding result again. + if separator.Height <= 0 { + t.Fatal("the menu laid out no separator") + } + move(row.X+row.Width/2, row.Y+row.Height/2) + move(row.X+row.Width/2+1, row.Y+row.Height/2) + if !rowTinted() { + t.Fatal("the row did not relight before the separator: the test cannot see the state it checks") + } + separatorY := separator.Y + separator.Height/2 + if separatorY < row.Y+row.Height || separatorY >= row.Y+row.Height+separator.Height { + t.Fatalf("the separator's y %v is not inside the separator row %+v", separatorY, separator) + } + move(separator.X+40, separatorY) + if rowTinted() { + t.Fatal("the row relit as the pointer crossed the menu's separator") + } + + // Returning to the row lights it again. + move(row.X+row.Width/2, row.Y+row.Height/2) + move(row.X+row.Width/2+1, row.Y+row.Height/2) + if !rowTinted() { + t.Fatal("the row is no longer tinted after the pointer returned to it") + } +} + +// A key press moves the menu's current row while the pointer rests anywhere, +// the menu's padding included. That row must stay lit: the surface only says +// where the pointer is, it does not take the menu away from the keyboard. +func TestMenuRowKeepsVisibleKeyboardFocusOverTheMenusOwnPadding(t *testing.T) { + theme := gfx.DarkTheme() + var canvas gfx.Canvas + // paint is one frame. The pointer rests, so the caller paints twice: the first + // frame is the one that crossed onto the spot, and the second is the frame that + // rests there, which is the frame the rule is about. + paint := func(hovered gfx.ID, role gfx.Role, focused gfx.ID, onSurface, focusVisible bool) int { + t.Helper() + canvas.Reset() + canvas.SetInteraction(hovered, gfx.ID{}, focused, focusVisible) + canvas.SetHoveredRole(role) + canvas.SetPointerOnSurface(onSurface) + menu := BeginContextMenu(&canvas, theme, gfx.Rect{X: 20, Y: 20, Width: 220, Height: 160}, ContextMenuOptions{ + Layer: 7, Scope: gfx.Item(64), + }) + menu.AddItem(ContextMenuItem{ID: gfx.Item(11), Label: "One"}) + menu.AddItem(ContextMenuItem{ID: gfx.Item(12), Label: "Two"}) + menu.End() + tinted := 0 + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color == theme.Accent && rectangle.Radius == theme.Metrics.RadiusItem() { + tinted++ + } + } + return tinted + } + rest := func(hovered gfx.ID, role gfx.Role, focused gfx.ID, onSurface, focusVisible bool) int { + t.Helper() + paint(hovered, role, focused, onSurface, focusVisible) + return paint(hovered, role, focused, onSurface, focusVisible) + } + + // The pointer rests on the padding (no hit at all) and the keyboard moved the + // current row: Down must leave that row lit. + if got := rest(gfx.ID{}, 0, gfx.Item(11), true, true); got != 1 { + t.Fatalf("the keyboard's row tinted %d rows with the pointer on the padding", got) + } + // The same pointer position without visible focus lights nothing: the surface + // still keeps a remembered row from relighting. + if got := rest(gfx.ID{}, 0, gfx.Item(11), true, false); got != 0 { + t.Fatalf("a row with no visible focus tinted %d rows over the padding", got) + } + // Caller content under the pointer is no different: visible keyboard focus keeps + // its row lit wherever the pointer rests. + if got := rest(gfx.Item(99), gfx.RoleRadio, gfx.Item(11), false, true); got != 1 { + t.Fatalf("the keyboard's row tinted %d rows with the pointer on a radio", got) + } + // And without visible focus that same frame lights nothing, which is the + // behaviour the colour row depends on. + if got := rest(gfx.Item(99), gfx.RoleRadio, gfx.Item(11), false, false); got != 0 { + t.Fatalf("a row without visible focus tinted %d rows over a radio", got) + } +} diff --git a/components/dropdown_menu.go b/components/dropdown_menu.go index 9d36d9b20..da05e0f22 100644 --- a/components/dropdown_menu.go +++ b/components/dropdown_menu.go @@ -796,7 +796,11 @@ func beginMenuSurface(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, minW menu.paintDismissBackdrop() // The surface itself is inside the menu: a press on its padding, a label, a // separator, or a disabled row must not reach the dismiss backdrop behind it. - menu.canvas.Block(bounds) + // Saying the pointer is on the surface also tells a row whether the pointer is + // on the menu at all: over the padding and the separators the pointer is on the + // menu but on no row, and treating that as "outside" relit the row that kept + // focus. + menu.canvas.BlockSurface(bounds) menu.canvas.Container(bounds, gfx.RoleMenu, "") part := overlaySurfacePart if options.submenu { @@ -1047,11 +1051,21 @@ func (menu *menuSurface) itemState(item menuItem) (active bool, foreground gfx.C enabled := !item.ID.IsZero() && !item.Disabled hovered := canvas.Hovered() claim := canvas.HoverCrossed() && !hovered.IsZero() - // While the pointer is over caller content inside the menu (a colour row, a - // switch), no row is the menu's current row: keeping the last focused row - // tinted would fight the control under the pointer. Menu rows themselves - // declare RoleMenuItem. - inContent := !hovered.IsZero() && canvas.HoveredRole() != 0 && canvas.HoveredRole() != gfx.RoleMenuItem + // No row is the menu's current one while the pointer is on the menu but not on + // a row. That covers the pointer over caller content inside the menu (a colour + // row, a switch), which declares a role that is not a row's, and the pointer + // over the menu's own padding and separators, which report the surface rather + // than a hit. Without the second case the row that kept focus relit whenever the + // pointer came back into the menu anywhere but on a row. + // + // Visible keyboard focus outranks a resting pointer, wherever it rests: a key + // press moves the menu's current row while the pointer sits on the padding or on + // a control of the caller's, and that row must stay lit. Focus that the pointer + // itself moved is not visible, so the row it entered still gives way to whatever + // is under the pointer. + inContent := canvas.FocusVisible().IsZero() && + (canvas.PointerOnSurface() || + !hovered.IsZero() && canvas.HoveredRole() != 0 && canvas.HoveredRole() != gfx.RoleMenuItem) if claim && hovered == item.ID { // A disabled row cannot take focus, but the frame is still repainted so // the row that kept focus is tinted again on the next paint. diff --git a/gfx/canvas.go b/gfx/canvas.go index 9aa3f0209..302de9ebd 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -620,6 +620,11 @@ type Hit struct { // Block marks an opaque region rather than a target: it has no ID and no // accessibility node, and presses inside it reach nothing declared before it. Block bool + // BlockSurface marks a Block that is a surface of its own: presses inside it + // still reach nothing, and the runtime reports Canvas.PointerOnSurface for + // it, so a control painted on the surface can tell a pointer over the + // surface's own blank area from a pointer outside the surface altogether. + BlockSurface bool // 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 @@ -729,6 +734,11 @@ type Canvas struct { // Components that draw content inside a menu use it to tell their own rows // from caller content under the pointer. hoveredRole Role + // onSurface reports whether the pointer is on a surface declared with + // Canvas.BlockSurface, which is opaque to presses but says the pointer is on + // it. A menu row uses it to tell the menu's own padding from the world outside + // the menu. + onSurface bool // prevHovered is the hit the pointer was on at the end of the previous // paint, which is what HoverCrossed compares against. prevHovered ID @@ -1708,6 +1718,27 @@ func (canvas *Canvas) Block(bounds Rect) { canvas.hits = append(canvas.hits, Hit{Bounds: bounds, Scope: canvas.currentFocusScope(), Layer: canvas.currentLayer(), Block: true}) } +// BlockSurface is Block for a surface that says whether the pointer is on it. +// Presses inside it reach nothing, as with Block, and it declares no target. The +// difference is that the runtime reports Canvas.PointerOnSurface while the pointer +// is anywhere inside it, including the padding and separators that declare no hit +// of their own. A control painted on the surface uses that to tell a pointer over +// its own blank area from one outside the surface altogether: a menu row stays +// unlit while the pointer travels over the menu's padding (see +// menuSurface.itemState). +func (canvas *Canvas) BlockSurface(bounds Rect) { + if clip, clipped := canvas.clipSnapshot(); clipped { + bounds = intersectCanvasRect(bounds, clip) + } + if bounds.Width <= 0 || bounds.Height <= 0 { + return + } + canvas.hits = append(canvas.hits, Hit{ + Bounds: bounds, Scope: canvas.currentFocusScope(), Layer: canvas.currentLayer(), + Block: true, BlockSurface: true, + }) +} + // MoveRegion declares a place a custom-titlebar window is moved from: pressing // and dragging it moves the window, and a double click zooms it. It is inert as // Block is, with no ID, hover, focus or accessibility node, and it lies where it @@ -1953,6 +1984,7 @@ func (canvas *Canvas) Clips() []Clip { func (canvas *Canvas) SetInteraction(hovered, pressed, focused ID, focusVisible bool) { canvas.hovered = hovered canvas.hoveredRole = 0 + canvas.onSurface = false canvas.pressed = pressed canvas.focused = focused canvas.focusVisible = focusVisible @@ -1975,6 +2007,19 @@ func (canvas *Canvas) SetHoveredRole(role Role) { canvas.hoveredRole = role } +// PointerOnSurface reports whether the pointer is on a surface declared with +// BlockSurface, such as the panel of an open menu. Unlike Hovered it is true over +// the surface's padding and separators, which declare no control of their own. +func (canvas *Canvas) PointerOnSurface() bool { + return canvas.onSurface +} + +// SetPointerOnSurface records whether the pointer is on a surface declared with +// BlockSurface. It is runtime-facing; application paint code should only read it. +func (canvas *Canvas) SetPointerOnSurface(on bool) { + canvas.onSurface = on +} + // HoverCrossed reports whether the pointer reached a different hit since the // previous paint. Lists use it to move their current row onto the row the // pointer entered, without letting a pointer that rests in place take the row diff --git a/gfx/replay.go b/gfx/replay.go index 58d230f99..98dd498ff 100644 --- a/gfx/replay.go +++ b/gfx/replay.go @@ -348,7 +348,7 @@ func sameImage(a, b Image) bool { func sameHit(a, b Hit) bool { return a.ID == b.ID && a.Bounds == b.Bounds && a.Label == b.Label && a.Value == b.Value && a.Layer == b.Layer && a.Scope == b.Scope && a.Role == b.Role && a.Disabled == b.Disabled && a.Checked == b.Checked && a.Selected == b.Selected && a.Focusable == b.Focusable && - a.IsLabel == b.IsLabel && a.Backdrop == b.Backdrop && a.Block == b.Block + a.IsLabel == b.IsLabel && a.Backdrop == b.Backdrop && a.Block == b.Block && a.BlockSurface == b.BlockSurface } func contains(outer, inner Rect) bool { diff --git a/internal/devreload/supervisor.go b/internal/devreload/supervisor.go index c51460a2b..8ceb16f82 100644 --- a/internal/devreload/supervisor.go +++ b/internal/devreload/supervisor.go @@ -61,7 +61,8 @@ func (value *supervisor) paint(canvas *gfx.Canvas, size gfx.Size) { request := reloadwire.PaintRequest{ Width: size.Width, Height: size.Height, Hovered: canvas.Hovered(), Pressed: canvas.Pressed(), Focused: canvas.Focused(), FocusVisible: !canvas.FocusVisible().IsZero(), - ScrollX: canvas.ScrollX(), ScrollY: canvas.ScrollY(), + PointerOnSurface: canvas.PointerOnSurface(), + ScrollX: canvas.ScrollX(), ScrollY: canvas.ScrollY(), Now: uint64(canvas.Now()), ReduceMotion: canvas.ReduceMotion(), } value.mu.Lock() diff --git a/internal/input/input.go b/internal/input/input.go index 4252c69fc..c17dbf236 100644 --- a/internal/input/input.go +++ b/internal/input/input.go @@ -37,6 +37,10 @@ type Region struct { // Blocks makes the region opaque: presses inside it reach no target // behind it. Target is zero. Blocks bool + // BlockSurface marks a Blocks region that also says whether the pointer is on + // it (see gfx.Canvas.BlockSurface): PointerAt reports it, while a press still + // reaches nothing and no tab stop lands on it. + BlockSurface bool // Label makes the region a label of Target: a press on it focuses the // target's own focusable region. It is not focusable itself. Label bool @@ -187,6 +191,31 @@ func (router *Router) HitTestRegion(x float32, y float32) (Region, bool) { return router.regions[index], true } +// PointerAt is what a pointer move needs in one pass: the front-most region the +// pointer is on, and whether it is on a surface that says so (see +// Region.BlockSurface) rather than on a control. Both answers come from the same +// search, so a move costs one scan of the regions, as HitTestRegion alone did. +func (router *Router) PointerAt(x float32, y float32) (Region, bool, bool) { + for index := len(router.regions) - 1; index >= 0; index-- { + region := router.regions[index] + if !contains(region.Bounds, x, y) { + continue + } + if region.Blocks { + // A surface is opaque: the point is on it and on nothing declared + // before it, so no control is under the pointer here. + if router.activeScope.IsZero() || region.Scope == router.activeScope { + return Region{}, false, region.BlockSurface + } + continue + } + if router.hitAvailable(region) { + return region, true, false + } + } + return Region{}, false, false +} + // PressKind is what a press at a point does in a custom-titlebar window. type PressKind uint8 diff --git a/internal/input/input_test.go b/internal/input/input_test.go index a5f0f72c1..b351da3c3 100644 --- a/internal/input/input_test.go +++ b/internal/input/input_test.go @@ -154,6 +154,23 @@ func BenchmarkHitTest10KMiss(b *testing.B) { } } +func BenchmarkPointerAt10KMiss(b *testing.B) { + regions := make([]Region, 10_000) + for index := range regions { + regions[index] = Region{ + Target: gfx.Item(int(index + 1)), + Bounds: Rect{X: float32(index), Width: 1, Height: 1}, + } + } + var router Router + router.SetRegions(regions) + b.ReportAllocs() + b.ResetTimer() + for range b.N { + router.PointerAt(-1, -1) + } +} + func BenchmarkFocusNext10K(b *testing.B) { regions := make([]Region, 10_000) for index := range regions { @@ -287,6 +304,33 @@ func TestFocusScopeIgnoresUnavailableInitialTarget(t *testing.T) { } } +func TestBlockSurfaceReportsThePointerButTakesNoPress(t *testing.T) { + var router Router + router.SetRegions([]Region{ + {Target: gfx.Item(1), Bounds: Rect{Width: 100, Height: 100}, Scope: gfx.Item(9)}, // full-window dismiss + {Bounds: Rect{X: 20, Y: 20, Width: 60, Height: 60}, Scope: gfx.Item(9), Blocks: true, BlockSurface: true}, // the panel + {Target: gfx.Item(2), Bounds: Rect{X: 30, Y: 30, Width: 20, Height: 20}, Scope: gfx.Item(9), Focusable: true}, + }) + router.SetActiveScope(gfx.Item(9), gfx.ID{}) + + // Over the panel's padding the surface reports itself, and a press still + // reaches nothing. + if _, ok, onSurface := router.PointerAt(70, 70); !onSurface || ok { + t.Fatal("the panel's padding did not report its surface") + } + if target, ok := router.HitTest(70, 70); ok { + t.Fatalf("panel padding = %d, %v; the press must reach nothing", target, ok) + } + // Over a control on the panel it is the control's place, not the surface's. + if _, _, onSurface := router.PointerAt(40, 40); onSurface { + t.Fatal("a control on the panel reported the surface instead of itself") + } + // Outside the panel there is no surface at all, only the dismiss backdrop. + if _, _, onSurface := router.PointerAt(5, 5); onSurface { + t.Fatal("the dismiss backdrop reported itself as a surface") + } +} + func TestBlockingRegionStopsPressesReachingTargetsDeclaredBeforeIt(t *testing.T) { var router Router router.SetRegions([]Region{ diff --git a/internal/interaction/focus.go b/internal/interaction/focus.go index aeada13ad..5d057e6ea 100644 --- a/internal/interaction/focus.go +++ b/internal/interaction/focus.go @@ -118,6 +118,7 @@ func (f *Focus) Sync(canvas *gfx.Canvas) { Disabled: hit.Disabled, FocusableDisabled: hit.FocusableDisabled, Blocks: hit.Block, + BlockSurface: hit.BlockSurface, Label: hit.IsLabel, Backdrop: hit.Backdrop, MovesWindow: hit.MovesWindow, diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index 7adb0feb6..4c98bc095 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -36,9 +36,12 @@ type painter struct { // pointerOutside says the pointer left the page while a button was down. // The press keeps the pointer until the button comes up. pointerOutside bool - scrollX float32 - scrollY float32 - dirty bool + // onSurface says the pointer is on a surface the page declared with + // gfx.Canvas.BlockSurface, such as an open menu's panel. + onSurface bool + scrollX float32 + scrollY float32 + dirty bool // keys follows keys a terminal asked to see as presses and releases. The // zero value tracks nothing, so a page without such a terminal pays nothing. keys interaction.Keys @@ -419,6 +422,7 @@ func (p *painter) paint() { focused, visible := p.focus.PaintTarget() p.canvas.SetInteraction(p.pointer.Hovered(), p.pointer.Pressed(), focused, visible) p.canvas.SetHoveredRole(p.pointer.HoveredRole()) + p.canvas.SetPointerOnSurface(p.onSurface) p.canvas.SetScroll(p.scrollX, p.scrollY) p.canvas.BeginFrame() p.config.Paint(p.canvas, gfx.Size{Width: p.width, Height: p.height}) @@ -636,6 +640,7 @@ func (p *painter) pointerEvent(event gfx.PointerEvent) bool { } event.Viewport = gfx.Size{Width: p.width, Height: p.height} beforeHovered, beforePressed := p.pointer.Hovered(), p.pointer.Pressed() + beforeSurface := p.onSurface beforeFocus, beforeKeyboard := p.focus.Focused(), p.focus.KeyboardFocus() inside := event.X >= 0 && event.Y >= 0 && event.X < p.width && event.Y < p.height if event.Kind == gfx.PointerMove && p.pointerOutside && inside { @@ -652,6 +657,7 @@ func (p *painter) pointerEvent(event gfx.PointerEvent) bool { p.pointerOutside = true p.pointer.SetHovered(gfx.ID{}) p.pointer.SetHoveredRole(gfx.Role(0)) + p.onSurface = false if beforeHovered.IsZero() { return false } @@ -676,6 +682,7 @@ func (p *painter) pointerEvent(event gfx.PointerEvent) bool { result.Repaint = true } if p.pointer.Hovered() == beforeHovered && p.pointer.Pressed() == beforePressed && + p.onSurface == beforeSurface && p.focus.Focused() == beforeFocus && p.focus.KeyboardFocus() == beforeKeyboard && !focusChanged && !result.Repaint && !placed { return false @@ -699,10 +706,12 @@ func (p *painter) pointerCancel(event gfx.PointerEvent) bool { func (p *painter) pointerStep(event gfx.PointerEvent) (result gfx.EventResult, focusChanged, placed bool) { p.pointer.SetHovered(gfx.ID{}) p.pointer.SetHoveredRole(gfx.Role(0)) + p.onSurface = false if event.Kind != gfx.PointerExit { - if target, ok := p.focus.Router().HitTestRegion(event.X, event.Y); ok { + if target, ok, onSurface := p.focus.Router().PointerAt(event.X, event.Y); ok || onSurface { p.pointer.SetHovered(target.Target) p.pointer.SetHoveredRole(target.Role) + p.onSurface = onSurface } } if event.Kind == gfx.PointerDown { diff --git a/internal/reloadwire/canvas.go b/internal/reloadwire/canvas.go index c8a741d09..fa34070de 100644 --- a/internal/reloadwire/canvas.go +++ b/internal/reloadwire/canvas.go @@ -107,7 +107,11 @@ func ApplyCanvas(canvas *gfx.Canvas, snapshot CanvasSnapshot) { canvas.PushFocusScope(hit.Scope) } if hit.Block { - canvas.Block(hit.Bounds) + if hit.BlockSurface { + canvas.BlockSurface(hit.Bounds) + } else { + canvas.Block(hit.Bounds) + } } else if hit.MovesWindow { canvas.MoveRegion(hit.Bounds) } else { diff --git a/internal/reloadwire/codec.go b/internal/reloadwire/codec.go index a8cebf45f..6daa7074f 100644 --- a/internal/reloadwire/codec.go +++ b/internal/reloadwire/codec.go @@ -9,7 +9,7 @@ import ( ) const ( - ProtocolVersion = 28 + ProtocolVersion = 29 MaxFrameBytes = 32 << 20 MaxStateBytes = 8 << 20 maxItems = 200_000 @@ -68,14 +68,21 @@ type Hello struct { } type PaintRequest struct { - Width float32 - Height float32 - Hovered gfx.ID - Pressed gfx.ID - Focused gfx.ID + Width float32 + Height float32 + Hovered gfx.ID + Pressed gfx.ID + Focused gfx.ID + // FocusVisible says the focused target shows its focus ring, as it does after + // a key press and not after a pointer press. FocusVisible bool - ScrollX float32 - ScrollY float32 + // PointerOnSurface says the pointer is on a surface the page declared with + // gfx.Canvas.BlockSurface, such as an open menu's panel, rather than on a + // control. SetInteraction clears the canvas's copy, so a worker paint needs it + // carried here to draw the same frame the host described. + PointerOnSurface bool + ScrollX float32 + ScrollY float32 // Now is the host's monotonic frame time in nanoseconds, so transitions // advance on the host clock no matter when the worker process is asked. Now uint64 @@ -311,6 +318,7 @@ func encodePaintRequest(value PaintRequest) []byte { result.id(value.Pressed) result.id(value.Focused) result.bool(value.FocusVisible) + result.bool(value.PointerOnSurface) result.f32(value.ScrollX) result.f32(value.ScrollY) result.u64(value.Now) @@ -322,7 +330,7 @@ func decodePaintRequest(data []byte) (PaintRequest, error) { value := decoder{data: data} result := PaintRequest{ Width: value.f32(), Height: value.f32(), Hovered: value.id(), Pressed: value.id(), Focused: value.id(), - FocusVisible: value.bool(), ScrollX: value.f32(), ScrollY: value.f32(), + FocusVisible: value.bool(), PointerOnSurface: value.bool(), ScrollX: value.f32(), ScrollY: value.f32(), Now: value.u64(), ReduceMotion: value.bool(), } return result, value.finish() @@ -585,6 +593,7 @@ func encodeCanvas(value CanvasSnapshot) ([]byte, error) { result.bool(hit.Focusable) result.bool(hit.Autofocus) result.bool(hit.Block) + result.bool(hit.BlockSurface) result.bool(hit.MovesWindow) encodeRect(&result, text.Bounds) result.f32(text.Size) @@ -706,7 +715,7 @@ func decodeCanvas(data []byte) (CanvasSnapshot, error) { result.Hits[index] = gfx.Hit{ ID: value.id(), Bounds: decodeRect(&value), Label: value.string(), Value: value.string(), Hint: value.string(), Scope: value.id(), Layer: value.u16(), Role: gfx.Role(value.u8()), Disabled: value.bool(), Checked: value.bool(), - Selected: value.bool(), Expanded: value.bool(), Multiline: value.bool(), ReadOnly: value.bool(), Secure: value.bool(), Focusable: value.bool(), Autofocus: value.bool(), Block: value.bool(), MovesWindow: value.bool(), + Selected: value.bool(), Expanded: value.bool(), Multiline: value.bool(), ReadOnly: value.bool(), Secure: value.bool(), Focusable: value.bool(), Autofocus: value.bool(), Block: value.bool(), BlockSurface: value.bool(), MovesWindow: value.bool(), } result.HitTexts[index] = gfx.HitText{ Bounds: decodeRect(&value), Size: value.f32(), Color: decodeColor(&value), Weight: value.f32(), diff --git a/internal/reloadwire/motion_test.go b/internal/reloadwire/motion_test.go index d8a1a05b8..968c423f4 100644 --- a/internal/reloadwire/motion_test.go +++ b/internal/reloadwire/motion_test.go @@ -19,6 +19,49 @@ func TestPaintRequestCodecCarriesFrameClockAndReducedMotion(t *testing.T) { } } +func TestPaintRequestCodecCarriesPointerOnSurface(t *testing.T) { + for _, testCase := range []struct { + name string + onSurface bool + }{ + {name: "off the surface"}, + {name: "on the surface", onSurface: true}, + } { + t.Run(testCase.name, func(t *testing.T) { + want := PaintRequest{ + Width: 640, Height: 480, Hovered: gfx.Item(3), Focused: gfx.Item(7), + PointerOnSurface: testCase.onSurface, + } + got, err := decodePaintRequest(encodePaintRequest(want)) + if err != nil || got != want { + t.Fatalf("paint request = %+v, want %+v, err = %v", got, want, err) + } + }) + } +} + +// A worker paint must see the surface flag the host recorded: SetInteraction +// clears the canvas's copy, so the request has to carry it across. +func TestWorkerPaintSeesTheHostsPointerOnSurface(t *testing.T) { + var seen []bool + config := WorkerConfig{Paint: func(canvas *gfx.Canvas, size gfx.Size) { + seen = append(seen, canvas.PointerOnSurface()) + }} + paint := func(onSurface bool) { + t.Helper() + payload := encodePaintRequest(PaintRequest{Width: 200, Height: 100, PointerOnSurface: onSurface}) + var canvas gfx.Canvas + if _, err, _ := handleRequest(&config, &canvas, CanvasSnapshot{}, frame{kind: messagePaint, payload: payload}, func(frame) error { return nil }); err != nil { + t.Fatal(err) + } + } + paint(true) + paint(false) + if len(seen) != 2 || !seen[0] || seen[1] { + t.Fatalf("the worker saw %v, want [true false]", seen) + } +} + func TestCanvasCodecCarriesAnimatingFlagToHostCanvas(t *testing.T) { data, err := encodeCanvas(CanvasSnapshot{Animating: true}) if err != nil { diff --git a/internal/reloadwire/reloadwire_test.go b/internal/reloadwire/reloadwire_test.go index 557c93228..93847925e 100644 --- a/internal/reloadwire/reloadwire_test.go +++ b/internal/reloadwire/reloadwire_test.go @@ -41,6 +41,7 @@ func TestCanvasCodecPreservesRetainedOutput(t *testing.T) { canvas.PushLayer(600) canvas.PushFocusScope(gfx.Item(44)) canvas.Block(gfx.Rect{X: 2, Y: 3, Width: 70, Height: 40}) + canvas.BlockSurface(gfx.Rect{X: 2, Y: 50, Width: 70, Height: 40}) canvas.HitWithOptions(gfx.Item(9), gfx.Rect{X: 4, Y: 5, Width: 60, Height: 20}, "Enable", gfx.HitOptions{Role: gfx.RoleCheckbox, Checked: true}) canvas.HitWithOptions(gfx.Item(10), gfx.Rect{X: 4, Y: 40, Width: 60, Height: 20}, "Password", gfx.HitOptions{Role: gfx.RoleTextField, Value: "never", Secure: true}) canvas.HitWithOptions(gfx.Item(11), gfx.Rect{X: 4, Y: 70, Width: 120, Height: 30}, "Name", gfx.HitOptions{ diff --git a/internal/reloadwire/worker.go b/internal/reloadwire/worker.go index 296cc4205..e72dcd154 100644 --- a/internal/reloadwire/worker.go +++ b/internal/reloadwire/worker.go @@ -108,6 +108,9 @@ func handleRequest(config *WorkerConfig, canvas *gfx.Canvas, base CanvasSnapshot return nil, err, false } canvas.SetInteraction(value.Hovered, value.Pressed, value.Focused, value.FocusVisible) + // SetInteraction clears the surface flag, so the request has to restore it: + // the paint below decides what a row does from where the pointer is. + canvas.SetPointerOnSurface(value.PointerOnSurface) canvas.SetScroll(value.ScrollX, value.ScrollY) canvas.SetReduceMotion(value.ReduceMotion) if config.Paint != nil { From 2c0c8729b510b2d21d40e1a08a22b380a2b0cd1b Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:14:12 +0800 Subject: [PATCH 04/13] feat(clipboard): preserve Windows column selection metadata --- .github/workflows/text-input.yml | 8 + app/clipboard_rectangular.go | 27 ++ app/clipboard_rectangular_other.go | 12 + app/clipboard_rectangular_test.go | 231 ++++++++++ app/clipboard_rectangular_windows.go | 11 + app/composition_dispatch_test.go | 4 + app/driver.go | 28 +- app/driver_system.go | 21 + app/driver_system_unsupported.go | 4 + app/painter.go | 21 +- app/text_input.go | 12 +- docs/system-integrations.md | 1 + internal/platform/contract.go | 6 +- .../windows/clipboard_rectangular_windows.go | 108 +++++ .../clipboard_rectangular_windows_test.go | 409 ++++++++++++++++++ internal/platform/windows/keys_windows.go | 25 +- internal/platform/windows/system_windows.go | 43 +- 17 files changed, 951 insertions(+), 20 deletions(-) create mode 100644 app/clipboard_rectangular.go create mode 100644 app/clipboard_rectangular_other.go create mode 100644 app/clipboard_rectangular_test.go create mode 100644 app/clipboard_rectangular_windows.go create mode 100644 internal/platform/windows/clipboard_rectangular_windows.go create mode 100644 internal/platform/windows/clipboard_rectangular_windows_test.go diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 21dd8fc4c..2d21a3b37 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -96,6 +96,14 @@ jobs: } - name: Application input lifecycle run: go test ./app -count=1 + - name: Windows column clipboard protocol + if: runner.os == 'Windows' + env: + VIVA_WINDOWS_CLIPBOARD: '1' + run: | + git rev-parse HEAD + go version + go test ./internal/platform/windows -run '^TestColumnClipboardNative' -count=1 -v -timeout=90s - name: GTK native probe dependencies if: runner.os == 'Linux' run: | diff --git a/app/clipboard_rectangular.go b/app/clipboard_rectangular.go new file mode 100644 index 000000000..b70457c75 --- /dev/null +++ b/app/clipboard_rectangular.go @@ -0,0 +1,27 @@ +package app + +import ( + "fmt" + "strings" +) + +// SetRectangularClipboardText writes text with column-selection metadata on +// Windows. Other native targets retain the plain-text clipboard fallback. +func SetRectangularClipboardText(value string) error { + if strings.IndexByte(value, 0) >= 0 { + return fmt.Errorf("app: clipboard text contains NUL") + } + if err, handled := driverSetRectangularClipboardText(value); handled { + return err + } + return nativeSetRectangularClipboardText(value) +} + +// ClipboardTextWithFormat reads text and its rectangular-selection marker from +// one clipboard snapshot. A target without that format returns false. +func ClipboardTextWithFormat() (value string, rectangular bool, err error) { + if value, rectangular, err, handled := driverClipboardTextWithFormat(); handled { + return value, rectangular, err + } + return nativeClipboardTextWithFormat() +} diff --git a/app/clipboard_rectangular_other.go b/app/clipboard_rectangular_other.go new file mode 100644 index 000000000..361355f1c --- /dev/null +++ b/app/clipboard_rectangular_other.go @@ -0,0 +1,12 @@ +//go:build !windows + +package app + +func nativeSetRectangularClipboardText(value string) error { + return nativeSetClipboardText(value) +} + +func nativeClipboardTextWithFormat() (string, bool, error) { + value, err := nativeClipboardText() + return value, false, err +} diff --git a/app/clipboard_rectangular_test.go b/app/clipboard_rectangular_test.go new file mode 100644 index 000000000..cb24398f8 --- /dev/null +++ b/app/clipboard_rectangular_test.go @@ -0,0 +1,231 @@ +//go:build darwin || windows || linux + +package app + +import ( + "path/filepath" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +func assertClipboardTextFormat(t *testing.T, want string, rectangular bool) { + t.Helper() + value, column, err := ClipboardTextWithFormat() + if err != nil || value != want || column != rectangular { + t.Fatalf("clipboard snapshot = %q, rectangular=%v, err=%v; want %q, rectangular=%v", value, column, err, want, rectangular) + } +} + +func TestDriverRectangularClipboardCopyCutAndPaste(t *testing.T) { + editor := text.NewEditor("primary") + const copied = "\u00e9\r\n\u6f22\r\n" + calls := 0 + var events []TextEvent + config := Config{Title: "column clipboard", Width: 300, Height: 120} + config.Paint = func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{X: 10, Y: 10, Width: 220, Height: 30}, "editor", gfx.HitOptions{Role: gfx.RoleTextField, Multiline: true}) + } + config.TextInput = func(TextInputContext) *TextInput { + return &TextInput{State: TextStateOf(editor), CopyOverride: true, CopyRectangular: true, CopyText: func() string { + calls++ + return copied + }, OnEvent: func(event TextEvent) (TextState, error) { + events = append(events, event) + return TextStateOf(editor), nil + }} + } + driver, err := NewDriver(config, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + if err := driver.Click(20, 20); err != nil { + t.Fatal(err) + } + if err := driver.Resize(301, 120); err != nil { + t.Fatal(err) + } + if calls != 0 { + t.Fatalf("paint eagerly evaluated copy text %d times", calls) + } + for index, action := range []rune{'c', 'x', 'v'} { + if handled, err := driver.ShortcutChord(gfx.ModifierControl, action); !handled || err != nil { + t.Fatalf("shortcut %c: handled=%v err=%v", action, handled, err) + } + assertClipboardTextFormat(t, copied, true) + wantCalls := index + 1 + if action == 'v' { + wantCalls = 2 + } + if calls != wantCalls { + t.Fatalf("shortcut %c evaluated copy text %d times, want %d", action, calls, wantCalls) + } + } + if len(events) != 2 || events[0].Kind != TextPaste || events[0].Text != "" || events[0].Rectangular || + events[1].Kind != TextPaste || events[1].Text != copied || !events[1].Rectangular { + t.Fatalf("copy/cut/paste events = %+v", events) + } + if editor.String() != "primary" { + t.Fatal("clipboard metadata changed the application-owned editor") + } + if err := SetClipboardText("stream"); err != nil { + t.Fatal(err) + } + assertClipboardTextFormat(t, "stream", false) + if handled, err := driver.ShortcutChord(gfx.ModifierControl, 'v'); !handled || err != nil { + t.Fatalf("plain paste: handled=%v err=%v", handled, err) + } + if event := events[len(events)-1]; event.Kind != TextPaste || event.Text != "stream" || event.Rectangular { + t.Fatalf("plain paste borrowed a stale column marker: %+v", event) + } +} + +func TestDriverRectangularClipboardReplacementsClearMetadata(t *testing.T) { + for _, kind := range []string{"plain", "html", "image", "files"} { + t.Run(kind, func(t *testing.T) { + driver := newFilesDriver(t) + if err := SetRectangularClipboardText("column\n"); err != nil { + t.Fatal(err) + } + assertClipboardTextFormat(t, "column\n", true) + want := "plain" + switch kind { + case "plain": + driver.SetClipboard(want) + case "html": + want = "rich" + driver.SetClipboardHTML("rich", want) + case "image": + want = "" + if err := driver.SetClipboardImage(onePixelPNG(t)); err != nil { + t.Fatal(err) + } + case "files": + want = "file.txt" + driver.SetClipboardFiles([]string{filepath.Join(t.TempDir(), want)}) + } + assertClipboardTextFormat(t, want, false) + }) + } +} + +func TestDriverRectangularClipboardRefusalsLeaveTextUntouched(t *testing.T) { + for _, secure := range []bool{false, true} { + name := "empty override" + if secure { + name = "secure" + } + t.Run(name, func(t *testing.T) { + calls, mutations := 0, 0 + config := Config{Title: "refused column copy", Width: 300, Height: 120} + config.Paint = func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{X: 10, Y: 10, Width: 220, Height: 30}, "editor", gfx.HitOptions{Role: gfx.RoleTextField, Secure: secure}) + } + config.TextInput = func(TextInputContext) *TextInput { + return &TextInput{State: TextState{Value: "private"}, CopyOverride: true, CopyRectangular: true, CopyText: func() string { + calls++ + if secure { + return "secret" + } + return "" + }, OnEvent: func(TextEvent) (TextState, error) { + mutations++ + return TextState{Value: "private"}, nil + }} + } + driver, err := NewDriver(config, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + if err := driver.Click(20, 20); err != nil { + t.Fatal(err) + } + driver.SetClipboard("sentinel") + for _, action := range []rune{'c', 'x'} { + if handled, err := driver.ShortcutChord(gfx.ModifierControl, action); !handled || err != nil { + t.Fatalf("refused shortcut %c: handled=%v err=%v", action, handled, err) + } + assertClipboardTextFormat(t, "sentinel", false) + } + wantCalls := 2 + if secure { + wantCalls = 0 + } + if mutations != 0 || calls != wantCalls { + t.Fatalf("refused copy/cut: mutations=%d calls=%d, want 0/%d", mutations, calls, wantCalls) + } + if err := SetRectangularClipboardText("invalid\x00column"); err == nil { + t.Fatal("NUL-bearing column text was accepted") + } + assertClipboardTextFormat(t, "sentinel", false) + }) + } +} + +func TestDriverRectangularClipboardCallbackHandoffDoesNotCutTheReplacement(t *testing.T) { + for _, mode := range []string{"same cached input", "replacement", "metadata changed"} { + for _, action := range []rune{'c', 'x'} { + t.Run(mode+"/"+string(action), func(t *testing.T) { + incoming := text.NewEditor("abc") + incoming.SetSelection(text.Range{Start: 1, End: 2}) + oldEvents := 0 + current := &TextInput{State: TextState{Value: "outgoing"}, CopyOverride: true, CopyRectangular: true, + OnEvent: func(TextEvent) (TextState, error) { + oldEvents++ + return TextState{Value: "outgoing"}, nil + }} + var driver *Driver + current.CopyText = func() string { + if mode == "replacement" { + current = &TextInput{Editor: incoming} + } else if mode == "metadata changed" { + current.CopyRectangular = false + } + if err := driver.Resize(301, 120); err != nil { + t.Fatal(err) + } + return "rows\n" + } + config := Config{Title: "column callback handoff", Width: 300, Height: 120} + config.Paint = func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{X: 10, Y: 10, Width: 220, Height: 30}, "editor", gfx.HitOptions{Role: gfx.RoleTextField, Multiline: true}) + } + config.TextInput = func(TextInputContext) *TextInput { return current } + var err error + driver, err = NewDriver(config, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + if err := driver.Click(20, 20); err != nil { + t.Fatal(err) + } + driver.SetClipboard("sentinel") + if handled, err := driver.ShortcutChord(gfx.ModifierControl, action); !handled || err != nil { + t.Fatalf("shortcut %c: handled=%v err=%v", action, handled, err) + } + if incoming.String() != "abc" || incoming.Selection() != (text.Range{Start: 1, End: 2}) { + t.Fatalf("old clipboard callback edited the replacement: text=%q selection=%+v", incoming.String(), incoming.Selection()) + } + if mode != "same cached input" { + assertClipboardTextFormat(t, "sentinel", false) + if oldEvents != 0 { + t.Fatalf("retired callback received %d edits", oldEvents) + } + } else { + assertClipboardTextFormat(t, "rows\n", true) + wantEvents := 0 + if action == 'x' { + wantEvents = 1 + } + if oldEvents != wantEvents { + t.Fatalf("same cached owner received %d edits, want %d", oldEvents, wantEvents) + } + } + }) + } + } +} diff --git a/app/clipboard_rectangular_windows.go b/app/clipboard_rectangular_windows.go new file mode 100644 index 000000000..e610deba1 --- /dev/null +++ b/app/clipboard_rectangular_windows.go @@ -0,0 +1,11 @@ +package app + +import windowsplatform "github.com/vivaui/viva/internal/platform/windows" + +func nativeSetRectangularClipboardText(value string) error { + return windowsplatform.SetClipboardRectangularText(value) +} + +func nativeClipboardTextWithFormat() (string, bool, error) { + return windowsplatform.ClipboardTextWithFormat() +} diff --git a/app/composition_dispatch_test.go b/app/composition_dispatch_test.go index d859e7b8c..07939c18c 100644 --- a/app/composition_dispatch_test.go +++ b/app/composition_dispatch_test.go @@ -49,6 +49,10 @@ func TestNativeTextEventAdapterPreservesTaggedFields(t *testing.T) { if got := appTextEvent(event); got != want { t.Fatalf("native event adaptation = %+v, want %+v", got, want) } + paste := platform.TextEvent{Kind: platform.TextPaste, Text: "column\r\n", Rectangular: true} + if got := appTextEvent(paste); got != (TextEvent{Kind: TextPaste, Text: "column\r\n", Rectangular: true}) { + t.Fatalf("native column paste adaptation = %+v", got) + } } func TestTextStateOfTentativeCompositionSnapshot(t *testing.T) { diff --git a/app/driver.go b/app/driver.go index db2655304..8e243db95 100644 --- a/app/driver.go +++ b/app/driver.go @@ -76,11 +76,12 @@ type Driver struct { openedWith [2]string hasOpenedWith bool // openedInBrowser is the file OpenPathInBrowser was last given. - openedInBrowser string - hasOpenedInBrowser bool - releases []func() - closed bool - appearanceOpen bool + openedInBrowser string + hasOpenedInBrowser bool + releases []func() + closed bool + appearanceOpen bool + clipboardRectangular bool system driverSystem openFilesResponses [driverOpenFilesQueueSize]driverOpenFilesResponse @@ -148,8 +149,7 @@ func NewDriver(config Config, canvas *gfx.Canvas) (*Driver, error) { return nil, err } driver.painter.setClipboardText = func(value string) { - driver.clipboard, driver.system.clipboardImage, driver.system.clipboardFiles = value, nil, nil - driver.system.clipboardHTML = "" + driver.SetClipboard(value) } driver.painter.setCursor = func(Cursor) error { return nil } driver.painter.setCursorImage = func(*gfx.CursorImage) error { return nil } @@ -908,12 +908,19 @@ func (driver *Driver) ShortcutChord(modifiers gfx.Modifiers, character rune) (bo } func (driver *Driver) clipboardEdit(action byte) error { - event, changed, err := platform.TextClipboardEvent(driver.painter.nativeText.ClipboardState(action), driver.painter.nativeText.Secure, action, - func() (string, error) { return driver.clipboard, nil }, - func(value string) error { driver.SetClipboard(value); return nil }) + input := driver.painter.nativeText + rectangular := false + event, changed, err := platform.TextClipboardEvent(input.ClipboardState(action), input.Secure, action, + func() (string, error) { rectangular = driver.clipboardRectangular; return driver.clipboard, nil }, + func(value string) error { + driver.SetClipboard(value) + driver.clipboardRectangular = input.CopyRectangular + return nil + }) if err != nil || !changed { return err } + event.Rectangular = event.Kind == platform.TextPaste && action == 'v' && rectangular return driver.textEvent(event) } @@ -959,6 +966,7 @@ func (driver *Driver) Clipboard() string { return driver.clipboard } func (driver *Driver) SetClipboard(value string) { driver.clipboard, driver.system.clipboardImage, driver.system.clipboardFiles = value, nil, nil driver.system.clipboardHTML = "" + driver.clipboardRectangular = false } // LastOpenedURL returns the most recent target passed to OpenURL while this diff --git a/app/driver_system.go b/app/driver_system.go index 163b0f834..640cf64dc 100644 --- a/app/driver_system.go +++ b/app/driver_system.go @@ -88,6 +88,24 @@ func driverSetClipboardText(value string) (error, bool) { return nil, true } +func driverSetRectangularClipboardText(value string) (error, bool) { + system := activeDriverSystem.Load() + if system == nil { + return nil, false + } + system.driver.SetClipboard(value) + system.driver.clipboardRectangular = true + return nil, true +} + +func driverClipboardTextWithFormat() (string, bool, error, bool) { + system := activeDriverSystem.Load() + if system == nil { + return "", false, nil, false + } + return system.driver.clipboard, system.driver.clipboardRectangular, nil, true +} + // SetClipboardHTML makes the driver's private clipboard hold both flavours of a // rich copy, as SetClipboardHTML does on the system clipboard: html beside alt // as the plain text, replacing the image and the files. An empty html writes @@ -95,6 +113,7 @@ func driverSetClipboardText(value string) (error, bool) { func (driver *Driver) SetClipboardHTML(html, alt string) { driver.system.clipboardHTML = html driver.clipboard, driver.system.clipboardImage, driver.system.clipboardFiles = alt, nil, nil + driver.clipboardRectangular = false } // ClipboardHTML is the rich flavour the driver's private clipboard holds, "" @@ -592,6 +611,7 @@ func (driver *Driver) SetClipboardImage(png []byte) error { driver.system.clipboardImage = append([]byte(nil), png...) driver.system.clipboardFiles = nil driver.clipboard, driver.system.clipboardHTML = "", "" + driver.clipboardRectangular = false return nil } @@ -633,4 +653,5 @@ func (driver *Driver) SetClipboardFiles(paths []string) { names = append(names, filepath.Base(path)...) } driver.clipboard, driver.system.clipboardHTML = string(names), "" + driver.clipboardRectangular = false } diff --git a/app/driver_system_unsupported.go b/app/driver_system_unsupported.go index 809e936d4..6ea68a8f2 100644 --- a/app/driver_system_unsupported.go +++ b/app/driver_system_unsupported.go @@ -8,6 +8,10 @@ func driverClipboardText() (string, error, bool) { return "", nil, false } func driverSetClipboardText(string) (error, bool) { return nil, false } +func driverSetRectangularClipboardText(string) (error, bool) { return nil, false } + +func driverClipboardTextWithFormat() (string, bool, error, bool) { return "", false, nil, false } + func driverSetPrimarySelection(string) (error, bool) { return nil, false } func driverPrimarySelection() (string, error, bool) { return "", nil, false } diff --git a/app/painter.go b/app/painter.go index 79f7cd59b..948ad6bda 100644 --- a/app/painter.go +++ b/app/painter.go @@ -205,10 +205,19 @@ func newPainterWithClock(canvas *gfx.Canvas, config *Config, clock func() time.D } painter.onTextEvent = painter.applyTextEvent painter.clipboardText = func() string { - if painter.activeText == nil || painter.activeText.CopyText == nil { + active := painter.activeText + if active == nil || active.CopyText == nil { return "" } - return painter.activeText.CopyText() + epoch := painter.textEpoch + override, rectangular := painter.nativeText.CopyOverride, painter.nativeText.CopyRectangular + value := active.CopyText() + // A reentrant provider must not copy old text or apply Cut to its replacement. + if painter.activeText != active || painter.textEpoch != epoch || + painter.nativeText.CopyOverride != override || painter.nativeText.CopyRectangular != rectangular { + return "" + } + return value } if config.WindowMode == WindowCustomTitlebar && controlsDrawnByViva { painter.controls = newWindowControls(config) @@ -1331,6 +1340,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { AltSendsEscape: input.AltSendsEscape, KeyReleases: context.Terminal && input.KeyReleases, DisableIME: input.DisableIME, MonoFace: input.MonoFace, CellWidth: cellWidth, Baseline: baseline, NavigationKeys: input.NavigationKeys || context.NavigationKeys, CopyOverride: input.CopyOverride, + CopyRectangular: input.CopyRectangular, CopyText: painter.clipboardText, HideNativeOverlays: input.HideNativeOverlays || context.HideNativeOverlays, Color: platform.Color{ @@ -1426,6 +1436,11 @@ func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextS if !painter.nativeText.Multiline && !painter.nativeText.Terminal && (event.Kind == platform.TextPaste || event.Kind == platform.TextInsert) && event.Text != "" { appEvent.Text = text.SingleLine(event.Text) + if appEvent.Text != event.Text { + // Folding removed the line structure, so the column shape the + // clipboard declared no longer describes the text the app receives. + appEvent.Rectangular = false + } if appEvent.Text == "" && !explicit { return painter.nativeText.State, nil } @@ -1475,7 +1490,7 @@ func samePlatformTextInput(left, right platform.TextInput) bool { left.Alignment == right.Alignment && left.Layer == right.Layer && left.Multiline == right.Multiline && left.Secure == right.Secure && left.Terminal == right.Terminal && left.MonoFace == right.MonoFace && left.CellWidth == right.CellWidth && left.Baseline == right.Baseline && left.AltSendsEscape == right.AltSendsEscape && left.KeyReleases == right.KeyReleases && left.DisableIME == right.DisableIME && left.NavigationKeys == right.NavigationKeys && - left.CopyOverride == right.CopyOverride && + left.CopyOverride == right.CopyOverride && left.CopyRectangular == right.CopyRectangular && left.HideNativeOverlays == right.HideNativeOverlays && left.Placed == right.Placed && left.CaretX == right.CaretX && left.CaretY == right.CaretY && left.CaretWidth == right.CaretWidth && left.CaretHeight == right.CaretHeight && diff --git a/app/text_input.go b/app/text_input.go index 0c3d79cd3..c11aeaa9d 100644 --- a/app/text_input.go +++ b/app/text_input.go @@ -109,7 +109,9 @@ const ( // Text is the text the event applies to, and MarkedSelection, when the input // method is composing, is a range into Text rather than into the document. type TextEvent struct { - Kind TextEventKind + Kind TextEventKind + // Rectangular marks a text paste as a column selection. + Rectangular bool Text string Selection TextRange MarkedSelection TextRange @@ -186,7 +188,10 @@ type TextInput struct { // on Cut. It never falls back to the native selection while CopyOverride is set. // Editing still uses State or Editor. CopyOverride bool - CopyText func() string + // CopyRectangular requests column-selection clipboard metadata on Windows. + // It does not alter the editor's selection or evaluate CopyText during paint. + CopyRectangular bool + CopyText func() string // AltSendsEscape asks printable Alt/Option chords on a terminal to arrive as // raw key events with the unmodified character in KeyEvent.Text. Terminal // encoders can then send the conventional Escape-prefixed Meta sequence. @@ -272,7 +277,7 @@ func platformTextState(state TextState) platform.TextState { func appTextEvent(event platform.TextEvent) TextEvent { return TextEvent{ - Kind: TextEventKind(event.Kind), Text: event.Text, + Kind: TextEventKind(event.Kind), Text: event.Text, Rectangular: event.Rectangular, Selection: appTextRange(event.Selection), MarkedSelection: appTextRange(event.MarkedSelection), Replacement: appTextRange(event.Replacement), @@ -295,6 +300,7 @@ func (event TextEvent) apply(editor *text.Editor) bool { return platform.TextEvent{ Kind: platform.TextEventKind(event.Kind), Text: event.Text, + Rectangular: event.Rectangular, Selection: platformTextRange(event.Selection), MarkedSelection: platformTextRange(event.MarkedSelection), Replacement: platformTextRange(event.Replacement), diff --git a/docs/system-integrations.md b/docs/system-integrations.md index 7864a0cf7..664bd3a23 100644 --- a/docs/system-integrations.md +++ b/docs/system-integrations.md @@ -10,6 +10,7 @@ synchronous forms report `ErrAsyncRequired`, `ErrSecretStoreUnavailable` or | Capability | macOS | Windows | Linux/X11 | WebAssembly browser | | --- | --- | --- | --- | --- | | Read/write text clipboard | `NSPasteboard` | Unicode Win32 clipboard | X11 `CLIPBOARD`, `UTF8_STRING` with `STRING` read fallback; text above 128 KiB is served and read in pieces (INCR); handed to the clipboard manager when the owning window closes, if the desktop has one | synchronous calls return `ErrAsyncRequired`; `ClipboardTextAsync` and `SetClipboardTextAsync` use the Clipboard API and require a user gesture | +| Column-selection clipboard (`SetRectangularClipboardText`, `ClipboardTextWithFormat`; `TextInput.CopyRectangular`, `TextEvent.Rectangular`) | no platform format; reads report `false` | Unicode text beside `MSDEVColumnSelect` (presence) and `Borland IDE Block Type` (one byte, `0x02`); an advertised marker whose data cannot be read is pasted as stream text | reads report `false` | reads report `false` | | Rich copy (`SetClipboardHTML`, html + plain alt) | `NSPasteboard`: `public.html` beside `public.utf8-plain-text` | registered `HTML Format` (CF_HTML, with its header of byte offsets) beside `CF_UNICODETEXT` | X11 `CLIPBOARD`: `text/html` target beside `UTF8_STRING`; the GTK shell serves the same pair through `gtk_clipboard_set_with_data` | synchronous calls return `ErrAsyncRequired`; `SetClipboardHTMLAsync` writes one `ClipboardItem` with both MIME flavours and needs a user gesture | | Copied files (`ClipboardFiles`, returns `[]string`) | the pasteboard's file URLs, file reference URLs resolved to paths; promised files have no path and are not listed | the `CF_HDROP` list (UTF-16 form) | X11 `CLIPBOARD`: `x-special/gnome-copied-files` (Nautilus, Nemo, Caja, Thunar) or `text/uri-list` (Dolphin, most toolkits); the GTK shell asks GTK for `text/uri-list` | `ErrUnsupported` | | Primary selection (`SetPrimarySelection`, `PrimarySelection`) | `ErrUnsupported` | `ErrUnsupported` | X11 `PRIMARY`: selected text, pasted with a middle click | `ErrUnsupported` | diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 68642d24c..a8b6fac94 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -877,6 +877,8 @@ type TextInput struct { MonoFace gfx.MonoFace // CopyOverride makes Copy/Cut use CopyText instead of the native selection. CopyOverride bool + // CopyRectangular requests column-selection clipboard metadata on Windows. + CopyRectangular bool // CopyText is evaluated only for a non-secure Copy/Cut action. A nil callback // or empty result leaves the clipboard and document unchanged. CopyText func() string @@ -1044,7 +1046,9 @@ const ( // TextEvent contains rune-indexed ranges. MarkedSelection is relative to Text. type TextEvent struct { - Kind TextEventKind + Kind TextEventKind + // Rectangular belongs to the same snapshot as the pasted text. + Rectangular bool Text string Selection text.Range MarkedSelection text.Range diff --git a/internal/platform/windows/clipboard_rectangular_windows.go b/internal/platform/windows/clipboard_rectangular_windows.go new file mode 100644 index 000000000..6b16f9c38 --- /dev/null +++ b/internal/platform/windows/clipboard_rectangular_windows.go @@ -0,0 +1,108 @@ +package windows + +import ( + "syscall" + "unsafe" +) + +// These IDs are initialized only by a clipboard operation, under clipboardMu. +var columnSelectFormat, borlandBlockFormat uintptr + +func rectangularClipboardFormats() (uintptr, uintptr, error) { + if columnSelectFormat == 0 { + name, err := syscall.UTF16PtrFromString("MSDEVColumnSelect") + if err != nil { + return 0, 0, err + } + format, _, err := registerClipboardFormat.Call(uintptr(unsafe.Pointer(name))) + if format == 0 { + return 0, 0, windowsCallError("register column clipboard format", err) + } + columnSelectFormat = format + } + if borlandBlockFormat == 0 { + name, err := syscall.UTF16PtrFromString("Borland IDE Block Type") + if err != nil { + return 0, 0, err + } + format, _, err := registerClipboardFormat.Call(uintptr(unsafe.Pointer(name))) + if format == 0 { + return 0, 0, windowsCallError("register Borland clipboard format", err) + } + borlandBlockFormat = format + } + return columnSelectFormat, borlandBlockFormat, nil +} + +// SetClipboardRectangularText writes Unicode text and both Scintilla column markers. +func SetClipboardRectangularText(value string) error { + return setClipboardText(value, true) +} + +// ClipboardTextWithFormat reads text and its markers while the clipboard is open. +func ClipboardTextWithFormat() (string, bool, error) { + clipboardMu.Lock() + defer clipboardMu.Unlock() + if opened, _, err := openClipboard.Call(0); opened == 0 { + return "", false, windowsCallError("open clipboard", err) + } + defer closeClipboard.Call() + if available, _, _ := clipboardFormatAvailable.Call(clipboardUnicodeText); available == 0 { + return "", false, nil + } + value, err := clipboardTextOpen() + if err != nil { + return "", false, err + } + column, borland, err := rectangularClipboardFormats() + if err != nil { + return "", false, err + } + if available, _, _ := clipboardFormatAvailable.Call(column); available != 0 { + return value, true, nil + } + if available, _, _ := clipboardFormatAvailable.Call(borland); available == 0 { + return value, false, nil + } + handle, _, _ := clipboardData.Call(borland) + if handle == 0 { + // The format is advertised but carries no data: its owner is gone, or + // it renders on request and did not. The text itself was read fine, so + // paste it as stream text instead of failing the whole paste, the rule + // Scintilla's reader applies to a missing marker. + return value, false, nil + } + return value, borlandClipboardMarker(handle), nil +} + +// borlandClipboardMarker reports whether the Borland block declares a column +// selection. A block that cannot be sized or locked is not a column marker; +// the text is pasted as stream text, as Scintilla does. +func borlandClipboardMarker(handle uintptr) bool { + if size, _, _ := globalSize.Call(handle); size != 1 { + return false + } + memory, _, _ := globalLock.Call(handle) + if memory == 0 { + return false + } + defer globalUnlock.Call(handle) + return *(*byte)(pointer(memory)) == 0x02 +} + +func allocateColumnClipboardMarker(value byte) (uintptr, error) { + handle, _, err := globalAlloc.Call(globalMoveable|globalZeroInit, 1) + if handle == 0 { + return 0, windowsCallError("allocate column clipboard marker", err) + } + if value != 0 { + memory, _, err := globalLock.Call(handle) + if memory == 0 { + globalFree.Call(handle) + return 0, windowsCallError("lock column clipboard marker", err) + } + *(*byte)(pointer(memory)) = value + globalUnlock.Call(handle) + } + return handle, nil +} diff --git a/internal/platform/windows/clipboard_rectangular_windows_test.go b/internal/platform/windows/clipboard_rectangular_windows_test.go new file mode 100644 index 000000000..1618f53ea --- /dev/null +++ b/internal/platform/windows/clipboard_rectangular_windows_test.go @@ -0,0 +1,409 @@ +package windows + +import ( + "errors" + "os" + "runtime" + "syscall" + "testing" + "unsafe" + + "github.com/vivaui/viva/gfx" + inputpkg "github.com/vivaui/viva/internal/input" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +func columnClipboardWindow(t *testing.T) *windowState { + t.Helper() + if os.Getenv("VIVA_WINDOWS_CLIPBOARD") == "" { + t.Skip("set VIVA_WINDOWS_CLIPBOARD=1 on a task-owned clipboard") + } + runtime.LockOSThread() + t.Cleanup(runtime.UnlockOSThread) + state := &windowState{window: staticWindow(t), ready: true, textEnabled: true, application: &windowsApplication{windows: 1}} + previous := active.Load() + active.Store(state) + t.Cleanup(func() { active.Store(previous) }) + t.Cleanup(func() { _ = SetClipboardText("") }) + return state +} + +func columnClipboardFormat(t *testing.T, name string) uintptr { + t.Helper() + value, err := syscall.UTF16PtrFromString(name) + if err != nil { + t.Fatal(err) + } + format, _, err := registerClipboardFormat.Call(uintptr(unsafe.Pointer(value))) + if format == 0 { + t.Fatalf("register %s: %v", name, err) + } + return format +} + +func addColumnClipboardMarker(t *testing.T, window uintptr, name string, data []byte) { + t.Helper() + format := columnClipboardFormat(t, name) + if opened, _, err := openClipboard.Call(window); opened == 0 { + t.Fatalf("open marker fixture: %v", err) + } + defer closeClipboard.Call() + if data == nil { + // Scintilla advertises MSDEV by presence, using delayed-rendered NULL data. + setClipboardData.Call(format, 0) + } else if err := setClipboardBlock(format, data); err != nil { + t.Fatal(err) + } + if available, _, _ := clipboardFormatAvailable.Call(format); available == 0 { + t.Fatalf("fixture has no %s format", name) + } +} + +func TestColumnClipboardNativeWritesUnicodeAndBothMarkers(t *testing.T) { + state := columnClipboardWindow(t) + const value = "\u00e9\r\n\u6f22\r\n" + if err := SetClipboardRectangularText(value); err != nil { + t.Fatal(err) + } + if got, rectangular, err := ClipboardTextWithFormat(); err != nil || got != value || !rectangular { + t.Fatalf("column snapshot = %q, rectangular=%v, err=%v", got, rectangular, err) + } + for _, name := range []string{"MSDEVColumnSelect", "Borland IDE Block Type"} { + if available, _, _ := clipboardFormatAvailable.Call(columnClipboardFormat(t, name)); available == 0 { + t.Fatalf("column copy omitted %s", name) + } + } + if opened, _, err := openClipboard.Call(state.window); opened == 0 { + t.Fatalf("open Borland payload: %v", err) + } + data, err := clipboardBytes(columnClipboardFormat(t, "Borland IDE Block Type"), 32) + closeClipboard.Call() + if err != nil || len(data) != 1 || data[0] != 0x02 { + t.Fatalf("Borland payload = %x, err=%v; want one byte 02", data, err) + } + if err := SetClipboardRectangularText("invalid\x00column"); err == nil { + t.Fatal("NUL-bearing native column text was accepted") + } + if got, rectangular, err := ClipboardTextWithFormat(); err != nil || got != value || !rectangular { + t.Fatalf("refused write changed the clipboard: %q/%v/%v", got, rectangular, err) + } + if err := SetClipboardText("plain"); err != nil { + t.Fatal(err) + } + if got, rectangular, err := ClipboardTextWithFormat(); err != nil || got != "plain" || rectangular { + t.Fatalf("plain text retained column metadata: %q/%v/%v", got, rectangular, err) + } + for _, name := range []string{"MSDEVColumnSelect", "Borland IDE Block Type"} { + if available, _, _ := clipboardFormatAvailable.Call(columnClipboardFormat(t, name)); available != 0 { + t.Fatalf("plain copy retained %s", name) + } + } +} + +func TestColumnClipboardNativeReadsIndependentMarkers(t *testing.T) { + for _, test := range []struct { + name, format string + data []byte + rectangular bool + }{ + {name: "unmarked"}, + {name: "MSDEV data", format: "MSDEVColumnSelect", data: []byte{0}, rectangular: true}, + {name: "MSDEV delayed data", format: "MSDEVColumnSelect", rectangular: true}, + {name: "Borland column", format: "Borland IDE Block Type", data: []byte{2}, rectangular: true}, + {name: "Borland stream", format: "Borland IDE Block Type", data: []byte{1}}, + {name: "Borland oversized", format: "Borland IDE Block Type", data: []byte{2, 0}}, + } { + t.Run(test.name, func(t *testing.T) { + state := columnClipboardWindow(t) + const value = "source\r\n\u6f22\r\n" + if err := SetClipboardText(value); err != nil { + t.Fatal(err) + } + if test.format != "" { + addColumnClipboardMarker(t, state.window, test.format, test.data) + } + if got, rectangular, err := ClipboardTextWithFormat(); err != nil || got != value || rectangular != test.rectangular { + t.Fatalf("independent clipboard = %q, rectangular=%v, err=%v; want rectangular=%v", got, rectangular, err, test.rectangular) + } + }) + } +} + +func TestColumnClipboardNativeKeyboardRoutesTheSameSnapshot(t *testing.T) { + for _, action := range []byte{'c', 'x', 'v'} { + t.Run(string(action), func(t *testing.T) { + state := columnClipboardWindow(t) + const value = "row\r\n\u00e9\r\n" + stop := errors.New("stop after actual clipboard delivery") + var events []platform.TextEvent + copies := 0 + state.textState = platform.TextState{Value: "primary"} + state.textInput = platform.TextInput{State: state.textState, Multiline: true, CopyOverride: true, CopyRectangular: true, + CopyText: func() string { copies++; return value }, + OnEvent: func(event platform.TextEvent) (platform.TextState, error) { + events = append(events, event) + return state.textState, stop + }} + if action == 'v' { + if err := SetClipboardText(value); err != nil { + t.Fatal(err) + } + addColumnClipboardMarker(t, state.window, "MSDEVColumnSelect", nil) + } + if !state.textKey(uintptr(action-'a'+'A'), 0, inputpkg.ModifierControl) { + t.Fatal("native clipboard shortcut was not handled") + } + if action == 'c' || action == 'x' { + if got, rectangular, err := ClipboardTextWithFormat(); err != nil || got != value || !rectangular || copies != 1 { + t.Fatalf("native copy = %q/%v/%v, calls=%d", got, rectangular, err, copies) + } + } + if action == 'c' { + if len(events) != 0 || state.err != nil { + t.Fatalf("copy delivered an edit: events=%+v err=%v", events, state.err) + } + return + } + if len(events) != 1 || state.err != stop || events[0].Kind != platform.TextPaste { + t.Fatalf("clipboard delivery = %+v, err=%v", events, state.err) + } + want := "" + if action == 'v' { + want = value + } + if events[0].Text != want || events[0].Rectangular != (action == 'v') { + t.Fatalf("native paste metadata/text diverged: %+v", events[0]) + } + }) + } +} + +func TestColumnClipboardNativeCallbackCannotUseAnObsoleteTarget(t *testing.T) { + for _, mode := range []string{"geometry", "replacement", "metadata", "destroyed"} { + for _, action := range []byte{'c', 'x'} { + t.Run(mode+"/"+string(action), func(t *testing.T) { + state := columnClipboardWindow(t) + if mode == "destroyed" { + window := state.window + windowStates.Store(window, state) + t.Cleanup(func() { windowStates.Delete(window) }) + } + state.config.DynamicTextInput = true + incoming := text.NewEditor("abc") + incoming.SetSelection(text.Range{Start: 1, End: 2}) + oldEvents, newEvents := 0, 0 + stop := errors.New("stop after live Cut delivery") + state.textState = platform.TextState{Value: "outgoing"} + state.textInput = platform.TextInput{Target: gfx.Item(1), Width: 120, Height: 24, FontSize: 13, + Placed: true, CaretHeight: 1, State: state.textState, CopyOverride: true, CopyRectangular: true, + OnEvent: func(platform.TextEvent) (platform.TextState, error) { + oldEvents++ + return state.textState, stop + }} + state.textInput.CopyText = func() string { + if mode == "destroyed" { + windowProc(state.window, wmDestroy, 0, 0) + return "rows\r\n" + } + next := state.textInput + switch mode { + case "geometry": + next.X++ + case "metadata": + next.CopyRectangular = false + case "replacement": + next.Target, next.State = gfx.Item(2), platform.EditorState(incoming) + next.CopyOverride, next.CopyRectangular, next.CopyText = false, false, nil + next.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + newEvents++ + event.Apply(incoming) + return platform.EditorState(incoming), stop + } + } + if _, _, err := state.applyTextInputUpdateWithCancel(platform.TextInputUpdate{Changed: true, Input: &next}, func() { + t.Fatal("non-composing clipboard fixture unexpectedly canceled IME") + }); err != nil { + t.Fatal(err) + } + return "rows\r\n" + } + if err := SetClipboardText("sentinel"); err != nil { + t.Fatal(err) + } + if !state.textKey(uintptr(action-'a'+'A'), 0, inputpkg.ModifierControl) { + t.Fatal("clipboard key was not consumed") + } + if incoming.String() != "abc" || incoming.Selection() != (text.Range{Start: 1, End: 2}) || newEvents != 0 { + t.Fatalf("clipboard callback entered new owner: text=%q selection=%+v events=%d", incoming.String(), incoming.Selection(), newEvents) + } + want, wantEvents := "sentinel", 0 + var wantError error + if mode == "geometry" { + want = "rows\r\n" + if action == 'x' { + wantEvents, wantError = 1, stop + } + } + if got, err := ClipboardText(); err != nil || got != want || oldEvents != wantEvents || state.err != wantError { + t.Fatalf("stale clipboard action: text=%q err=%v oldEvents=%d stateErr=%v; want %q/%d/%v", got, err, oldEvents, state.err, want, wantEvents, wantError) + } + if mode == "destroyed" && (state.window != 0 || state.textEnabled || state.application.windows != 0) { + t.Fatal("closed clipboard callback retained live native input") + } + }) + } + } +} + +func TestColumnClipboardNativeBusyClipboardNeverCuts(t *testing.T) { + state := columnClipboardWindow(t) + incoming := text.NewEditor("abc") + incoming.SetSelection(text.Range{Start: 1, End: 2}) + state.textState = platform.EditorState(incoming) + events := 0 + state.textInput = platform.TextInput{State: state.textState, CopyOverride: true, CopyRectangular: true, + CopyText: func() string { return "rows\r\n" }, + OnEvent: func(event platform.TextEvent) (platform.TextState, error) { + events++ + event.Apply(incoming) + return platform.EditorState(incoming), errors.New("unexpected Cut") + }} + if err := SetClipboardText("sentinel"); err != nil { + t.Fatal(err) + } + ready := make(chan error, 1) + release, done := make(chan struct{}), make(chan struct{}) + go func() { + defer close(done) + runtime.LockOSThread() + defer runtime.UnlockOSThread() + class, err := syscall.UTF16PtrFromString("STATIC") + if err != nil { + ready <- err + return + } + window, _, err := createWindow.Call(0, uintptr(unsafe.Pointer(class)), 0, wsPopup, 0, 0, 1, 1, 0, 0, 0, 0) + if window == 0 { + ready <- windowsCallError("create clipboard holder", err) + return + } + defer destroyWindow.Call(window) + if opened, _, err := openClipboard.Call(window); opened == 0 { + ready <- windowsCallError("hold clipboard fixture", err) + return + } + ready <- nil + <-release + closeClipboard.Call() + }() + released := false + defer func() { + if !released { + close(release) + <-done + } + }() + if err := <-ready; err != nil { + t.Fatal(err) + } + if err := SetClipboardRectangularText("blocked"); err == nil { + t.Fatal("rectangular write ignored an externally held clipboard") + } + if _, _, err := ClipboardTextWithFormat(); err == nil { + t.Fatal("formatted read guessed data from a busy clipboard") + } + if !state.textKey('X', 0, inputpkg.ModifierControl) { + t.Fatal("failed Cut key was not consumed") + } + close(release) + <-done + released = true + if got, err := ClipboardText(); err != nil || got != "sentinel" || events != 0 || state.err != nil || + incoming.String() != "abc" || incoming.Selection() != (text.Range{Start: 1, End: 2}) { + t.Fatalf("busy clipboard Cut mutated state: clipboard=%q/%v events=%d stateErr=%v text=%q selection=%+v", got, err, events, state.err, incoming.String(), incoming.Selection()) + } +} + +func TestColumnClipboardNativeUnreadableMarkerPastesAsStream(t *testing.T) { + for _, msdev := range []bool{false, true} { + name := "unreadable Borland" + if msdev { + name = "MSDEV has priority" + } + t.Run(name, func(t *testing.T) { + state := columnClipboardWindow(t) + if err := SetClipboardText("unchanged"); err != nil { + t.Fatal(err) + } + addColumnClipboardMarker(t, state.window, "Borland IDE Block Type", nil) + if msdev { + addColumnClipboardMarker(t, state.window, "MSDEVColumnSelect", nil) + } + value, rectangular, err := ClipboardTextWithFormat() + if msdev { + if err != nil || value != "unchanged" || !rectangular { + t.Fatalf("valid MSDEV marker consulted broken Borland data: %q/%v/%v", value, rectangular, err) + } + } else if err != nil || value != "unchanged" || rectangular { + t.Fatalf("unreadable marker was not pasted as stream text: %q/%v/%v", value, rectangular, err) + } + if !msdev { + events := 0 + state.textInput = platform.TextInput{OnEvent: func(event platform.TextEvent) (platform.TextState, error) { + events++ + if event.Kind != platform.TextPaste || event.Text != "unchanged" || event.Rectangular { + t.Errorf("paste event = %+v; want the clipboard text pasted as a stream", event) + } + // The fixture has no text engine to paint the paste into; the + // event is the assertion, so stop before the frame. + return state.textState, errors.New("stop the fixture paste") + }} + if !state.textKey('V', 0, inputpkg.ModifierControl) || events != 1 { + t.Fatalf("unreadable marker did not deliver a stream Paste: events=%d", events) + } + } + if plain, err := ClipboardText(); err != nil || plain != "unchanged" { + t.Fatalf("marker read failure changed ordinary clipboard behavior: %q/%v", plain, err) + } + }) + } +} + +func TestColumnClipboardNativeDiscardedMarkerIsNotGuessed(t *testing.T) { + for _, test := range []struct { + name string + size uintptr + value byte + rectangular bool + }{ + {name: "discarded"}, + {name: "column", size: 1, value: 2, rectangular: true}, + {name: "stream", size: 1, value: 1}, + {name: "oversized", size: 2, value: 2}, + } { + t.Run(test.name, func(t *testing.T) { + // A zero-sized movable allocation has a handle but no readable data. + handle, _, err := globalAlloc.Call(globalMoveable|globalZeroInit, test.size) + if handle == 0 { + t.Fatalf("allocate marker: %v", err) + } + defer globalFree.Call(handle) + if test.size != 0 { + memory, _, err := globalLock.Call(handle) + if memory == 0 { + t.Fatalf("lock marker: %v", err) + } + *(*byte)(pointer(memory)) = test.value + globalUnlock.Call(handle) + } + if size, _, _ := globalSize.Call(handle); size != test.size { + t.Fatalf("marker size = %d; want %d", size, test.size) + } + rectangular := borlandClipboardMarker(handle) + if rectangular != test.rectangular { + t.Fatalf("marker = rectangular %v; want rectangular %v", rectangular, test.rectangular) + } + }) + } +} diff --git a/internal/platform/windows/keys_windows.go b/internal/platform/windows/keys_windows.go index a6336b814..e6b48b5dc 100644 --- a/internal/platform/windows/keys_windows.go +++ b/internal/platform/windows/keys_windows.go @@ -205,10 +205,31 @@ func (state *windowState) textKey(first, second uintptr, mods input.Modifiers) b repeat := second&(1<<30) != 0 editKey := platform.KeyEvent{Key: normalizedKey(first), Modifiers: mods, Repeat: repeat, Text: shortcutText(first)} if action := platform.TextClipboardAction(editKey); action != 0 { - event, changed, err := platform.TextClipboardEvent(state.textInput.ClipboardState(action), state.textInput.Secure, action, ClipboardText, SetClipboardText) + window, revision := state.window, state.textRevision + input := state.textInput + current := func() bool { + return state.window == window && state.textEnabled && state.textRevision == revision && + state.textInput.CopyOverride == input.CopyOverride && state.textInput.CopyRectangular == input.CopyRectangular + } + clipboard := input.ClipboardState(action) + if !current() { + return true + } + rectangular := false + read := func() (string, error) { + value, column, err := ClipboardTextWithFormat() + rectangular = column + return value, err + } + write := SetClipboardText + if input.CopyRectangular { + write = SetClipboardRectangularText + } + event, changed, err := platform.TextClipboardEvent(clipboard, input.Secure, action, read, write) if err != nil { messageBeep.Call(0) // a busy clipboard must not close the window or delete a selection - } else if changed { + } else if changed && current() { + event.Rectangular = event.Kind == platform.TextPaste && action == 'v' && rectangular state.handleTextEvent(event) } return true diff --git a/internal/platform/windows/system_windows.go b/internal/platform/windows/system_windows.go index 710e13dcd..007cecbdd 100644 --- a/internal/platform/windows/system_windows.go +++ b/internal/platform/windows/system_windows.go @@ -139,6 +139,10 @@ func ClipboardText() (string, error) { return "", windowsCallError("open clipboard", callErr) } defer closeClipboard.Call() + return clipboardTextOpen() +} + +func clipboardTextOpen() (string, error) { handle, _, callErr := clipboardData.Call(clipboardUnicodeText) if handle == 0 { return "", windowsCallError("read clipboard", callErr) @@ -314,13 +318,40 @@ func clipboardBytes(format uintptr, limit int) ([]byte, error) { return append([]byte(nil), unsafe.Slice((*byte)(pointer(memory)), int(size))...), nil } -func SetClipboardText(value string) error { +func SetClipboardText(value string) error { return setClipboardText(value, false) } + +func setClipboardText(value string, rectangular bool) error { encoded, err := syscall.UTF16FromString(value) if err != nil { return fmt.Errorf("windows: encode clipboard text: %w", err) } clipboardMu.Lock() defer clipboardMu.Unlock() + var columnFormat, borlandFormat, columnMarker, borlandMarker uintptr + if rectangular { + columnFormat, borlandFormat, err = rectangularClipboardFormats() + if err != nil { + return err + } + columnMarker, err = allocateColumnClipboardMarker(0) + if err != nil { + return err + } + defer func() { + if columnMarker != 0 { + globalFree.Call(columnMarker) + } + }() + borlandMarker, err = allocateColumnClipboardMarker(0x02) + if err != nil { + return err + } + defer func() { + if borlandMarker != 0 { + globalFree.Call(borlandMarker) + } + }() + } bytes := uintptr(len(encoded) * 2) handle, _, callErr := globalAlloc.Call(globalMoveable|globalZeroInit, bytes) if handle == 0 { @@ -353,6 +384,16 @@ func SetClipboardText(value string) error { return windowsCallError("write clipboard", callErr) } transferred = true + if rectangular { + if result, _, err := setClipboardData.Call(columnFormat, columnMarker); result == 0 { + return windowsCallError("write column clipboard marker", err) + } + columnMarker = 0 + if result, _, err := setClipboardData.Call(borlandFormat, borlandMarker); result == 0 { + return windowsCallError("write Borland clipboard marker", err) + } + borlandMarker = 0 + } return nil } From 74b6fc7d1799f8d7375dc4c8fb056f1a6c93a0b1 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:14:50 +0800 Subject: [PATCH 05/13] fix(app): keep handled pointer events out of caret placement --- app/app.go | 3 +- app/painter.go | 6 +- app/painter_handled_caret_bench_test.go | 50 ++++++ app/painter_handled_caret_test.go | 166 ++++++++++++++++++ benchmarks/ci.sh | 2 +- gfx/input.go | 4 +- internal/platform/web/painter.go | 13 +- .../web/painter_handled_caret_test.go | 86 +++++++++ 8 files changed, 323 insertions(+), 7 deletions(-) create mode 100644 app/painter_handled_caret_bench_test.go create mode 100644 app/painter_handled_caret_test.go create mode 100644 internal/platform/web/painter_handled_caret_test.go diff --git a/app/app.go b/app/app.go index 427853d90..3bf0e8b1e 100644 --- a/app/app.go +++ b/app/app.go @@ -131,7 +131,8 @@ type Config struct { // be coalesced to the latest queued position, as the platform does natively, // so a handler follows the coordinates rather than the number of calls. // Returning Repaint asks for one synchronous paint; Handled suppresses the - // click that press would complete. + // click that press would complete and default caret placement for the event, + // ending any pending default selection drag. OnPointer func(event gfx.PointerEvent) gfx.EventResult // OnKey receives normalized keyboard events for the focused hit target. // Handled suppresses built-in traversal, activation, and Escape dismissal. diff --git a/app/painter.go b/app/painter.go index 948ad6bda..1ee870c63 100644 --- a/app/painter.go +++ b/app/painter.go @@ -399,7 +399,10 @@ func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.Eve } painter.pointer.NoteHandled(gfx.PointerEventKind(event.Kind), result.Handled) focusChanged = painter.applyEventResult(result) - if painter.placeCaret(event) { + if result.Handled { + // A handler owns this selection; the default drag must not resume. + painter.placing = false + } else if painter.placeCaret(event) { result.Repaint = true } return result, focusChanged, edgeChanged @@ -450,6 +453,7 @@ func (painter *painter) placeCaret(event platform.PointerEvent) bool { switch event.Kind { case platform.PointerDown: painter.placing, painter.placeAnchor = true, index + selection.Selection.Start = index painter.placeUnit, painter.placeUnitRange = 0, text.Range{} switch { case event.ClickCount >= 3: diff --git a/app/painter_handled_caret_bench_test.go b/app/painter_handled_caret_bench_test.go new file mode 100644 index 000000000..5908e8350 --- /dev/null +++ b/app/painter_handled_caret_bench_test.go @@ -0,0 +1,50 @@ +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +func BenchmarkPointerCaretOwnership(b *testing.B) { + for _, events := range []bool{false, true} { + provider := "editor" + if events { + provider = "events" + } + b.Run(provider, func(b *testing.B) { + for _, handled := range []bool{false, true} { + name := "default" + if handled { + name = "handled" + } + b.Run(name, func(b *testing.B) { + fixture := newHandledCaretFixture(b, events) + if handled { + fixture.handled = gfx.PointerDown + } + gesture := [...]platform.PointerEvent{ + {Kind: platform.PointerDown, X: 10, Y: 10, Button: gfx.PointerButtonPrimary, ClickCount: 1}, + {Kind: platform.PointerMove, X: 30, Y: 10, Button: gfx.PointerButtonPrimary, ClickCount: 1}, + {Kind: platform.PointerUp, X: 30, Y: 10, Button: gfx.PointerButtonPrimary, ClickCount: 1}, + } + b.ReportAllocs() + for b.Loop() { + for _, event := range gesture { + if _, err := fixture.painter.pointerEvent(event); err != nil { + b.Fatal(err) + } + } + } + b.ReportMetric(float64(fixture.placement.calls)/float64(b.N), "placements/op") + // The baseline overwrites handled selections. Permanent tests + // assert the repair; the paired workload checks common state. + if fixture.editor.String() != "ab cd\nef" || fixture.editor.CanUndo() { + b.Fatal("pointer gesture changed text or history") + } + }) + } + }) + } +} diff --git a/app/painter_handled_caret_test.go b/app/painter_handled_caret_test.go new file mode 100644 index 000000000..e9cfe3d5d --- /dev/null +++ b/app/painter_handled_caret_test.go @@ -0,0 +1,166 @@ +package app + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +type handledCaretPlacement struct{ calls int } + +func (placement *handledCaretPlacement) OffsetAt(point gfx.Point) (int, bool) { + placement.calls++ + return int(point.X / 10), true +} + +func (*handledCaretPlacement) CaretBounds() (gfx.Rect, bool) { + return gfx.Rect{Width: 1, Height: 20}, true +} + +type handledCaretFixture struct { + painter *painter + editor *text.Editor + placement handledCaretPlacement + handled gfx.PointerEventKind + paints int + writes int +} + +func newHandledCaretFixture(t testing.TB, events bool) *handledCaretFixture { + t.Helper() + fixture := &handledCaretFixture{editor: text.NewEditor("ab cd\nef")} + field := gfx.Item(7) + config := Config{Title: "caret ownership", Width: 120, Height: 40} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + fixture.paints++ + bounds := gfx.Rect{Width: size.Width, Height: size.Height} + canvas.HitWithOptions(field, bounds, "Text", gfx.HitOptions{ + Role: gfx.RoleTextField, TextBounds: bounds, Autofocus: true, Placement: &fixture.placement, + }) + } + config.TextInput = func(TextInputContext) *TextInput { + if !events { + return &TextInput{Editor: fixture.editor} + } + return &TextInput{State: TextStateOf(fixture.editor), OnEvent: func(event TextEvent) (TextState, error) { + fixture.writes++ + event.Apply(fixture.editor) + return TextStateOf(fixture.editor), nil + }} + } + config.OnPointer = func(event gfx.PointerEvent) gfx.EventResult { + if event.Kind != fixture.handled { + return gfx.EventResult{} + } + fixture.editor.SetSelection(text.Range{Start: 6, End: 8}) + return gfx.EventResult{Handled: true, Repaint: true, Focus: field} + } + var canvas gfx.Canvas + fixture.painter = newTestPainter(t, &canvas, config) + return fixture +} + +func (fixture *handledCaretFixture) pointer(t testing.TB, kind platform.PointerEventKind, x float32, clicks int) { + t.Helper() + _, err := fixture.painter.pointerEvent(platform.PointerEvent{ + Kind: kind, X: x, Y: 10, Button: gfx.PointerButtonPrimary, ClickCount: clicks, + }) + if err != nil { + t.Fatal(err) + } +} + +func TestHandledPointerOwnsCaretPlacement(t *testing.T) { + for _, events := range []bool{false, true} { + provider := "editor" + if events { + provider = "events" + } + t.Run(provider, func(t *testing.T) { + for _, phase := range []struct { + name string + kind platform.PointerEventKind + }{{"press", platform.PointerDown}, {"move", platform.PointerMove}, {"release", platform.PointerUp}} { + t.Run(phase.name, func(t *testing.T) { + fixture := newHandledCaretFixture(t, events) + if phase.kind != platform.PointerDown { + fixture.pointer(t, platform.PointerDown, 10, 1) + } + if phase.kind == platform.PointerUp { + fixture.pointer(t, platform.PointerMove, 30, 1) + } + fixture.handled = gfx.PointerEventKind(phase.kind) + calls, writes, paints := fixture.placement.calls, fixture.writes, fixture.paints + fixture.pointer(t, phase.kind, 40, 1) + want := text.Range{Start: 6, End: 8} + if got := fixture.editor.Selection(); got != want { + t.Fatalf("handled %s replaced custom selection: got %+v, want %+v", phase.name, got, want) + } + if fixture.placement.calls != calls || fixture.writes != writes { + t.Fatalf("handled %s invoked default placement: calls %d -> %d, writes %d -> %d", phase.name, calls, fixture.placement.calls, writes, fixture.writes) + } + if fixture.paints <= paints || fixture.painter.focus.Focused() != gfx.Item(7) { + t.Fatal("handled pointer lost repaint or focus") + } + fixture.handled = 0 + fixture.pointer(t, platform.PointerMove, 50, 1) + fixture.pointer(t, platform.PointerUp, 50, 1) + if fixture.editor.Selection() != want || fixture.placement.calls != calls || fixture.writes != writes { + t.Fatal("retired default drag resumed after takeover") + } + fixture.pointer(t, platform.PointerDown, 20, 1) + if got := fixture.editor.Selection(); got != (text.Range{Start: 2, End: 2}) { + t.Fatalf("new unhandled press = %+v, want caret 2", got) + } + fixture.pointer(t, platform.PointerMove, 40, 1) + fixture.pointer(t, platform.PointerUp, 40, 1) + if got := fixture.editor.Selection(); got != (text.Range{Start: 2, End: 4}) { + t.Fatalf("new unhandled drag = %+v, want 2..4", got) + } + if fixture.editor.String() != "ab cd\nef" || fixture.editor.CanUndo() { + t.Fatal("pointer selection changed text or history") + } + }) + } + }) + } +} + +func TestUnhandledPointerCaretPlacementControls(t *testing.T) { + for _, events := range []bool{false, true} { + provider := "editor" + if events { + provider = "events" + } + t.Run(provider, func(t *testing.T) { + t.Run("drag", func(t *testing.T) { + fixture := newHandledCaretFixture(t, events) + fixture.pointer(t, platform.PointerDown, 10, 1) + if got := fixture.editor.Selection(); got != (text.Range{Start: 1, End: 1}) { + t.Fatalf("ordinary press = %+v, want caret 1", got) + } + fixture.pointer(t, platform.PointerMove, 30, 1) + fixture.pointer(t, platform.PointerUp, 30, 1) + if got := fixture.editor.Selection(); got != (text.Range{Start: 1, End: 3}) { + t.Fatalf("ordinary drag = %+v, want 1..3", got) + } + }) + for _, click := range []struct { + name string + count int + want text.Range + }{{"word", 2, text.Range{Start: 0, End: 2}}, {"line", 3, text.Range{Start: 0, End: 6}}} { + t.Run(click.name, func(t *testing.T) { + fixture := newHandledCaretFixture(t, events) + fixture.pointer(t, platform.PointerDown, 10, click.count) + fixture.pointer(t, platform.PointerUp, 10, click.count) + if got := fixture.editor.Selection(); got != click.want { + t.Fatalf("%d-click selection = %+v, want %+v", click.count, got, click.want) + } + }) + } + }) + } +} diff --git a/benchmarks/ci.sh b/benchmarks/ci.sh index 2a9c980f7..d90eca4ca 100755 --- a/benchmarks/ci.sh +++ b/benchmarks/ci.sh @@ -25,4 +25,4 @@ run ./internal/input 'Benchmark(HitTest10KMiss|FocusNext10K)$' run ./text 'Benchmark(CursorMoveMixedText|ReplaceComposition|TypingWithUndoHistory)$' run ./ui 'Benchmark(WrapRows|WrapLines|DrawIcon)$' run ./components 'Benchmark(CheckboxPaint|MarkdownLayout)$' -run ./app 'BenchmarkPainter(LabelledPage|SteadyStateRepaint|IconPageHoverToggle|ModalToggle)$' +run ./app 'Benchmark(Painter(LabelledPage|SteadyStateRepaint|IconPageHoverToggle|ModalToggle)|PointerCaretOwnership)$' diff --git a/gfx/input.go b/gfx/input.go index 2889cffda..ad5a30819 100644 --- a/gfx/input.go +++ b/gfx/input.go @@ -277,8 +277,8 @@ type FileDropEvent struct { // for one synchronous paint. Focus moves focus to one focusable hit, including // a hit the event reveals in that paint; Blur clears focus and takes precedence // over Focus. Handled suppresses the runtime's click (what Clicked reads), activation, -// escape, or window-scroll behavior for that event. ClipboardText, when -// non-empty, asks the active runtime to copy the text without making +// escape, window-scroll, or default caret-placement behavior for that event. +// ClipboardText, when non-empty, asks the active runtime to copy the text without making // application code depend on a platform clipboard. type EventResult struct { Focus ID diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index 4c98bc095..4d489520f 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -729,7 +729,12 @@ func (p *painter) pointerStep(event gfx.PointerEvent) (result gfx.EventResult, f } p.pointer.NoteHandled(event.Kind, result.Handled) focusChanged = p.applyEventResult(result) - placed = p.placeCaret(event) + if result.Handled { + // A handler owns this selection; the default drag must not resume. + p.placing = false + } else { + placed = p.placeCaret(event) + } switch event.Kind { case gfx.PointerUp: if id, ok := p.pointer.Click(); ok && !result.Handled { @@ -810,11 +815,15 @@ func (p *painter) placeCaret(event gfx.PointerEvent) bool { } value := p.textInput.State.Value index := utf8.RuneCountInString(value[:max(0, min(offset, len(value)))]) + start := p.placeAnchor if event.Kind == gfx.PointerDown { + // The press starts a fresh selection at the caret; the anchor only + // seeds the drag that follows. p.placing, p.placeAnchor = true, index + start = index } next, err := p.textInput.OnEvent(platform.TextEvent{ - Kind: platform.TextSetSelection, Selection: text.Range{Start: p.placeAnchor, End: index}, + Kind: platform.TextSetSelection, Selection: text.Range{Start: start, End: index}, }) if err != nil { return false diff --git a/internal/platform/web/painter_handled_caret_test.go b/internal/platform/web/painter_handled_caret_test.go new file mode 100644 index 000000000..99902095c --- /dev/null +++ b/internal/platform/web/painter_handled_caret_test.go @@ -0,0 +1,86 @@ +//go:build js && wasm + +package web + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/text" +) + +type handledCaretPlacement struct{ calls int } + +func (placement *handledCaretPlacement) OffsetAt(point gfx.Point) (int, bool) { + placement.calls++ + return int(point.X / 10), true +} + +func (*handledCaretPlacement) CaretBounds() (gfx.Rect, bool) { return gfx.Rect{}, false } + +// A handler that returns Handled owns the selection for that pointer event; the +// runtime must not place a default caret over it, on wasm as on the native +// backends. +func TestHandledPointerOwnsPlacedEditorCaret(t *testing.T) { + phases := []struct { + name string + kind gfx.PointerEventKind + }{ + {"press", gfx.PointerDown}, + {"move", gfx.PointerMove}, + {"release", gfx.PointerUp}, + } + for _, phase := range phases { + t.Run(phase.name, func(t *testing.T) { + var canvas gfx.Canvas + editor := text.NewEditor("ab cd") + placement := &handledCaretPlacement{} + field := gfx.Item(1) + handled := phase.kind + config := Config{ + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(field, gfx.Rect{Width: 100, Height: 40}, "source", gfx.HitOptions{ + Role: gfx.RoleTextField, Multiline: true, + HideNativeOverlays: true, Placement: placement, + }) + }, + TextInput: EditorInputs(func(id gfx.ID) (*text.Editor, bool) { return editor, id == field }), + OnPointer: func(event gfx.PointerEvent) gfx.EventResult { + if event.Kind != handled { + return gfx.EventResult{} + } + editor.SetSelection(text.Range{Start: 3, End: 5}) + return gfx.EventResult{Handled: true, Repaint: true} + }, + } + painter := newPainter(&canvas, &config) + painter.width, painter.height = 100, 40 + painter.repaint() + if phase.kind != gfx.PointerDown { + painter.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: 5, Y: 10}) + } + if phase.kind == gfx.PointerUp { + painter.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerMove, X: 20, Y: 10}) + } + calls := placement.calls + painter.pointerEvent(gfx.PointerEvent{ + Kind: phase.kind, Button: gfx.PointerButtonPrimary, X: 40, Y: 10, + }) + want := text.Range{Start: 3, End: 5} + if got := editor.Selection(); got != want { + t.Fatalf("handled %s replaced the custom selection: got %+v, want %+v", phase.name, got, want) + } + if placement.calls != calls { + t.Fatalf("handled %s invoked default placement: calls %d -> %d", phase.name, calls, placement.calls) + } + // The handled event ended any default drag, so a later unhandled + // move has nothing to resume and must leave the app's selection. + handled = 0 + painter.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerMove, X: 50, Y: 10}) + painter.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerUp, Button: gfx.PointerButtonPrimary, X: 50, Y: 10}) + if got := editor.Selection(); got != want { + t.Fatalf("a later unhandled move resumed the default drag: got %+v, want %+v", got, want) + } + }) + } +} From 8f8f38d5c07076866f560fa3cdda7f2983565260 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:15:12 +0800 Subject: [PATCH 06/13] feat(darwin): forward opt-in tentative composition phases --- internal/platform/darwin/callback.go | 220 ++++++- .../composition_tentative_darwin_test.go | 42 ++ internal/platform/darwin/native.h | 3 + internal/platform/darwin/native.m | 179 +++++- internal/platform/darwin/platform.go | 86 +-- .../platform/darwin/testdata/dock_reopen.m | 5 + internal/platform/darwin/testdata/file_drop.m | 5 + .../platform/darwin/testdata/live_resize.m | 5 + .../platform/darwin/testdata/modifier_taps.m | 5 + .../testdata/tentative_bridge_darwin.go | 185 ++++++ .../testdata/tentative_bridge_darwin_test.go | 602 ++++++++++++++++++ .../platform/darwin/testdata/text_selection.m | 5 + .../platform/darwin/testdata/traffic_lights.m | 5 + .../platform/darwin/testdata/window_close.m | 5 + .../platform/darwin/testdata/window_size.m | 5 + 15 files changed, 1279 insertions(+), 78 deletions(-) create mode 100644 internal/platform/darwin/composition_tentative_darwin_test.go create mode 100644 internal/platform/darwin/testdata/tentative_bridge_darwin.go create mode 100644 internal/platform/darwin/testdata/tentative_bridge_darwin_test.go diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index f584c0fe4..de788876f 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -704,6 +704,19 @@ func presentTextInput(state *runState, view unsafe.Pointer, update TextInputUpda state.setTextInput(update.Input) return nil } + settledComposition := false + if state.sameCompositionOwner(update.Input) && state.textState.Composing && !update.Input.State.Composing { + if err := state.deliverCompositionCancel(view, false); err != nil { + return err + } + if !state.sameCompositionOwner(update.Input) { + return nil + } + resolved := *update.Input + resolved.State = state.textState + update.Input = &resolved + settledComposition = true + } var native C.viva_text_input_config var memory unsafe.Pointer @@ -717,11 +730,16 @@ func presentTextInput(state *runState, view unsafe.Pointer, update TextInputUpda // A field that grows, scrolls or moves keeps the input method's // composition: the text event already installed the acknowledged state, // so only the place the editor and its caret occupy changed. - keepComposition := state.textInputKeepsComposition(update.Input) + keepComposition := !settledComposition && state.textInputKeepsComposition(update.Input) previousHandler := state.textHandler previousState := state.textState previousInput := state.textInput previousActive := state.textInputActive + previousComposition := state.textComposition + var previousCompositionState nativeTextComposition + if previousComposition != nil { + previousCompositionState = *previousComposition + } state.setTextInput(update.Input) var status C.int if keepComposition { @@ -734,6 +752,10 @@ func presentTextInput(state *runState, view unsafe.Pointer, update TextInputUpda state.textState = previousState state.textInput = previousInput state.textInputActive = previousActive + state.textComposition = previousComposition + if previousComposition != nil { + *previousComposition = previousCompositionState + } if status == 3 { return &resourceError{"darwin: failed to rebuild the text input texture"} } @@ -785,6 +807,47 @@ func presentAccessibility(view unsafe.Pointer, nodes []AccessibilityNode) error return nil } +// Only enabled tentative inputs need state-push reconciliation and callback +// generations. Legacy fields retain no sidecar allocation. +type nativeTextComposition struct { + epoch uint64 + depth int + pending bool +} + +func (state *runState) sameCompositionOwner(next *TextInput) bool { + return state.textInputActive && next != nil && state.textState.TentativeComposition && next.State.TentativeComposition && + state.textInput.Target == next.Target && state.textState.CompositionIdentity == next.State.CompositionIdentity +} + +func (state *runState) compositionCurrent(composition *nativeTextComposition, epoch uint64) bool { + return !state.closed && state.textInputActive && state.textComposition == composition && composition.epoch == epoch +} + +func (state *runState) deliverCompositionCancel(view unsafe.Pointer, redraw bool) error { + if state.closed || !state.textInputActive || state.textHandler == nil || !state.textState.TentativeComposition || !state.textState.Composing { + return nil + } + return deliverTextInputEvent(state, view, TextEvent{ + Kind: TextSetMarked, CompositionPhase: text.CompositionCancel, + }, redraw, view != nil) +} + +func (state *runState) compositionLost(view unsafe.Pointer) error { + if composition := state.textComposition; composition != nil && composition.depth > 0 { + composition.pending = true + return nil + } + return state.deliverCompositionCancel(view, true) +} + +//export vivaTextCompositionLost +func vivaTextCompositionLost(handle C.uintptr_t, view unsafe.Pointer, reason C.int) { + if state, ok := runStateFor(handle); ok && !state.closed && reason == 1 { + _ = state.compositionLost(view) + } +} + //export vivaTextInput func vivaTextInput( handle C.uintptr_t, @@ -798,79 +861,166 @@ func vivaTextInput( replacementLength C.int64_t, command C.int, ) { - state := cgo.Handle(handle).Value().(*runState) - defer func() { - if recovered := recover(); recovered != nil { - platform.ReportFault("darwin: AppKit callback", recovered) - state.err = fmt.Errorf("darwin: text input handler panicked: %v", recovered) - C.viva_view_close(view) - } - }() - - if state.textHandler == nil { - state.err = fmt.Errorf("darwin: native text event without a handler") - C.viva_view_close(view) + state, ok := runStateFor(handle) + if !ok || state.closed { return } - value := "" if utf8Length > 0 { value = C.GoStringN((*C.char)(unsafe.Pointer(utf8)), C.int(utf8Length)) } - event := TextEvent{ - Kind: TextEventKind(kind), - Text: value, - Command: TextCommand(command), + event := TextEvent{Kind: TextEventKind(kind), Text: value, Command: TextCommand(command)} + if event.Kind == TextSetSelection { + event.Selection = utf16Range(state.textState.Value, int(selectedStart), int(selectedLength)) + } + if event.Kind == TextSetMarked { + event.MarkedSelection = utf16Range(value, int(selectedStart), int(selectedLength)) + } + if replacementStart >= 0 { + event.HasReplacement = true + event.Replacement = utf16Range(state.textState.Value, int(replacementStart), int(replacementLength)) } + _ = deliverTextInputEvent(state, view, event, true, false) +} + +//export vivaCompositionInput +func vivaCompositionInput( + handle C.uintptr_t, + view unsafe.Pointer, + kind C.int, + utf8 *C.uchar, + utf8Length C.size_t, + selectedStart C.int64_t, + selectedLength C.int64_t, + replacementStart C.int64_t, + replacementLength C.int64_t, + command C.int, + compositionPhase C.int, + replacementUTF16Start C.int64_t, + replacementUTF16Length C.int64_t, + hasReplacementUTF16 C.int, +) { + state, ok := runStateFor(handle) + if !ok || state.closed { + return + } + value := "" + if utf8Length > 0 { + value = C.GoStringN((*C.char)(unsafe.Pointer(utf8)), C.int(utf8Length)) + } + event := TextEvent{Kind: TextEventKind(kind), Text: value, Command: TextCommand(command)} if event.Kind == TextSetSelection { - event.Selection = utf16Range( - state.textState.Value, - int(selectedStart), - int(selectedLength), - ) + event.Selection = utf16Range(state.textState.Value, int(selectedStart), int(selectedLength)) } if event.Kind == TextSetMarked { event.MarkedSelection = utf16Range(value, int(selectedStart), int(selectedLength)) } if replacementStart >= 0 { event.HasReplacement = true - event.Replacement = utf16Range( - state.textState.Value, - int(replacementStart), - int(replacementLength), - ) + event.Replacement = utf16Range(state.textState.Value, int(replacementStart), int(replacementLength)) + } + if state.textState.TentativeComposition && compositionPhase != 0 { + event.CompositionPhase = text.CompositionPhase(compositionPhase) + if hasReplacementUTF16 != 0 { + event.HasReplacementUTF16 = true + event.ReplacementUTF16 = text.UTF16Range{Start: int(replacementUTF16Start), Length: int(replacementUTF16Length)} + } + } + _ = deliverTextInputEvent(state, view, event, true, false) +} + +func deliverTextInputEvent(state *runState, view unsafe.Pointer, event TextEvent, redraw, forceUpdate bool) (err error) { + defer func() { + if recovered := recover(); recovered != nil { + platform.ReportFault("darwin: AppKit callback", recovered) + state.err = fmt.Errorf("darwin: text input handler panicked: %v", recovered) + err = state.err + C.viva_view_close(view) + } + }() + + if state.textHandler == nil { + state.err = fmt.Errorf("darwin: native text event without a handler") + C.viva_view_close(view) + return state.err + } + + if state.textState.TentativeComposition && state.textComposition == nil { + state.textComposition = &nativeTextComposition{} + } + composition := state.textComposition + var epoch uint64 + if composition != nil { + composition.epoch++ + epoch = composition.epoch } previous := state.textState next, err := state.textHandler(event) + if (composition != nil && !state.compositionCurrent(composition, epoch)) || + (composition == nil && state.textComposition != nil) { + return nil + } if err == nil { err = validateTextState(next) } plan := planTextEvent(state.textInputActive && state.textInput.Terminal, previous, next) + plan.update = plan.update || forceUpdate next = next.WithoutRedraw() // a one-shot request, not editor state + endsComposition := !next.TentativeComposition || event.CompositionPhase != text.CompositionNone && event.CompositionPhase != text.CompositionUpdate if err == nil && plan.update { - err = updateText(view, next, state.redrawHandler == nil) + if composition != nil { + composition.depth++ + } + err = updateText(view, next, endsComposition, !redraw || state.redrawHandler == nil) + if composition != nil { + composition.depth-- + } if isResourceError(err) { // The editor's texture could not be made: make the window's // resources again and type into the editor once more. if recoverErr := state.recoverResources(view, err); recoverErr != nil { err = recoverErr } else { + if composition != nil && !state.compositionCurrent(composition, epoch) { + return nil + } state.rebuildNextFrame = true - err = updateText(view, next, state.redrawHandler == nil) + if composition != nil { + composition.depth++ + } + err = updateText(view, next, endsComposition, !redraw || state.redrawHandler == nil) + if composition != nil { + composition.depth-- + } } } } if err != nil { + if composition != nil { + composition.pending = false + } state.err = err C.viva_view_close(view) - return + return err + } + if composition != nil { + if !state.compositionCurrent(composition, epoch) { + return nil + } + if composition.pending { + composition.pending = false + return state.deliverCompositionCancel(view, redraw) + } } state.textState = next if state.textInputActive { state.textInput.State = next } - if state.redrawHandler != nil && plan.render { + if !next.TentativeComposition { + state.textComposition = nil + } + if redraw && state.redrawHandler != nil && plan.render { state.textEventRedraw = plan.render frame, redrawErr := state.redrawHandler() if redrawErr == nil { @@ -880,8 +1030,10 @@ func vivaTextInput( if redrawErr != nil { state.err = redrawErr C.viva_view_close(view) + return redrawErr } } + return nil } func utf16Range(value string, start, length int) text.Range { @@ -898,7 +1050,7 @@ func utf16Range(value string, start, length int) text.Range { } } -func updateText(view unsafe.Pointer, state TextState, render bool) error { +func updateText(view unsafe.Pointer, state TextState, endsComposition, render bool) error { editor := text.NewEditor(state.Value) selectedStart := editor.RuneIndexToUTF16(state.Selection.Start) selectedEnd := editor.RuneIndexToUTF16(state.Selection.End) @@ -918,6 +1070,8 @@ func updateText(view unsafe.Pointer, state TextState, render bool) error { C.size_t(markedStart), C.size_t(markedEnd-markedStart), C.int(boolInt(state.Composing)), + C.int(boolInt(state.TentativeComposition)), + C.int(boolInt(endsComposition)), C.int(boolInt(render)), ) if status == 3 { diff --git a/internal/platform/darwin/composition_tentative_darwin_test.go b/internal/platform/darwin/composition_tentative_darwin_test.go new file mode 100644 index 000000000..fb1d1ad05 --- /dev/null +++ b/internal/platform/darwin/composition_tentative_darwin_test.go @@ -0,0 +1,42 @@ +package darwin + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "runtime" + "testing" +) + +// VIVA_TENTATIVE_BENCH=1 runs the same native bridge overlay's paired input and +// owner benchmarks instead of the native behavior tests. +func TestNativeTentativeCompositionBridge(t *testing.T) { + directory, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + replacements := make(map[string]string) + for _, name := range []string{"tentative_bridge_darwin.go", "tentative_bridge_darwin_test.go"} { + replacements[filepath.Join(directory, name)] = filepath.Join(directory, "testdata", name) + } + data, err := json.Marshal(struct{ Replace map[string]string }{Replace: replacements}) + if err != nil { + t.Fatal(err) + } + overlay := filepath.Join(t.TempDir(), "overlay.json") + if err := os.WriteFile(overlay, data, 0o600); err != nil { + t.Fatal(err) + } + command := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "test", "-race", "-overlay", overlay, + "-run", "^TestDarwinTentativeProbe", "-count=1", "-v", ".") + if os.Getenv("VIVA_TENTATIVE_BENCH") == "1" { + command = exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "test", "-overlay", overlay, + "-run", "^$", "-bench", "^BenchmarkDarwinTentativeProbe", "-benchmem", "-benchtime=200ms", "-count=5", ".") + } + output, err := command.CombinedOutput() + if err != nil { + t.Fatalf("native tentative composition bridge: %v\n%s", err, output) + } + t.Logf("%s", output) +} diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 4cc50c82e..e42b13054 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -78,6 +78,7 @@ typedef struct { size_t marked_start; size_t marked_length; int has_marked_text; + int tentative_composition; int multiline; int enabled; int secure; @@ -468,6 +469,8 @@ int viva_view_update_text( size_t marked_start, size_t marked_length, int has_marked_text, + int tentative_composition, + int ends_composition, int render ); int viva_view_update_text_input(void *view, viva_text_input_config text_input); diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 44fe66e21..443d89117 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -437,6 +437,38 @@ int viva_plan_composite( VIVA_TEXT_DELETE_TO_LINE_END = 28, }; +/* The existing opt-in text.CompositionPhase values. */ +enum { + VIVA_COMPOSITION_NONE = 0, + VIVA_COMPOSITION_UPDATE, + VIVA_COMPOSITION_RESULT, + VIVA_COMPOSITION_COMMIT, + VIVA_COMPOSITION_CANCEL, + VIVA_COMPOSITION_EMPTY_COMMIT, +}; + +static int viva_text_composition_phase(int kind, NSUInteger length, BOOL marked, NSRange replacement) { + switch (kind) { + case VIVA_TEXT_SET_MARKED: + return length > 0 ? VIVA_COMPOSITION_UPDATE : marked ? VIVA_COMPOSITION_CANCEL : VIVA_COMPOSITION_NONE; + case VIVA_TEXT_INSERT: + if (marked) { + return length > 0 ? VIVA_COMPOSITION_RESULT : VIVA_COMPOSITION_EMPTY_COMMIT; + } + return length == 0 && replacement.location != NSNotFound ? VIVA_COMPOSITION_EMPTY_COMMIT : VIVA_COMPOSITION_NONE; + case VIVA_TEXT_UNMARK: + return marked ? VIVA_COMPOSITION_COMMIT : VIVA_COMPOSITION_NONE; + case VIVA_TEXT_CANCEL_COMPOSITION: + return marked ? VIVA_COMPOSITION_CANCEL : VIVA_COMPOSITION_NONE; + default: + return VIVA_COMPOSITION_NONE; + } +} + +static int64_t viva_text_raw_coordinate(NSUInteger value) { + return value > (NSUInteger)INT64_MAX ? INT64_MAX : (int64_t)value; +} + extern void vivaPointerEvent( uintptr_t callbackHandle, void *view, @@ -580,7 +612,25 @@ extern void vivaTextInput( int command ); +extern void vivaCompositionInput( + uintptr_t callbackHandle, + void *view, + int kind, + const unsigned char *utf8, + size_t utf8Length, + int64_t selectedStart, + int64_t selectedLength, + int64_t replacementStart, + int64_t replacementLength, + int command, + int compositionPhase, + int64_t replacementUTF16Start, + int64_t replacementUTF16Length, + int hasReplacementUTF16 +); + extern unsigned char *vivaCopyText(uintptr_t callbackHandle, void *view, size_t *length); +extern void vivaTextCompositionLost(uintptr_t callbackHandle, void *view, int reason); extern int vivaPressAt( uintptr_t callbackHandle, @@ -3855,6 +3905,9 @@ @interface VivaMetalView : NSView { // one's (platform.TextInput.DisableIME): keys never reach the host's text // system and no composition session is opened. BOOL _textDisableIME; + BOOL _tentativeComposition; + BOOL _discardingComposition; + uint64_t _textInputGeneration; BOOL _interpretingKey; BOOL _interpretedConsumed; BOOL _interpretedInsert; @@ -3937,7 +3990,9 @@ - (int)updateText:(const unsigned char *)utf8 length:(NSUInteger)length selectedRange:(NSRange)selectedRange markedRange:(NSRange)markedRange - hasMarkedText:(BOOL)hasMarkedText; + hasMarkedText:(BOOL)hasMarkedText + tentativeComposition:(BOOL)tentativeComposition + endsComposition:(BOOL)endsComposition; - (int)updateTextInput:(viva_text_input_config)textInput; - (int)updateTextInput:(viva_text_input_config)textInput keepComposition:(BOOL)keep; - (void)setTitlebarHeight:(CGFloat)height; @@ -3947,6 +4002,8 @@ - (void)restartCaretBlink; - (void)stopCaretBlink; - (void)shutdownTextInput; - (void)detachCallbacks; +- (void)notifyCompositionLost; +- (void)endOwnedNativeComposition; - (BOOL)rebuildTextTexture; - (BOOL)rebuildTextLabels; - (viva_editor_line)newTextLine; @@ -4095,6 +4152,7 @@ - (instancetype)initWithFrame:(NSRect)frame _selectedRange = NSMakeRange(textInput.selected_start, textInput.selected_length); _markedRange = NSMakeRange(textInput.marked_start, textInput.marked_length); _hasMarkedText = textInput.has_marked_text != 0; + _tentativeComposition = textInput.tentative_composition != 0; if (_textInputEnabled) { _text = [[NSString alloc] initWithBytes:textInput.utf8 length:textInput.utf8_length @@ -4278,9 +4336,13 @@ - (BOOL)acceptsFirstResponder { // A page taking the keyboard is the window losing it as far as the keys that were down go. - (BOOL)resignFirstResponder { + uint64_t generation = _textInputGeneration; if (_callbackHandle != 0 && _keyEventsEnabled && self.window.isKeyWindow) { vivaFocusLost(_callbackHandle, self); } + if (_textInputGeneration == generation && _textInputEnabled && _tentativeComposition) { + [self endOwnedNativeComposition]; + } return YES; } @@ -4994,6 +5056,7 @@ - (void)syncSecureEventInput { } - (void)keyWindowChanged:(NSNotification *)notification { + uint64_t generation = _textInputGeneration; [self syncSecureEventInput]; if ([notification.name isEqualToString:NSWindowDidBecomeKeyNotification] && notification.object == self.window && _callbackHandle != 0) { @@ -5005,6 +5068,10 @@ - (void)keyWindowChanged:(NSNotification *)notification { notification.object == self.window && _callbackHandle != 0 && _keyEventsEnabled) { vivaFocusLost(_callbackHandle, self); } + if (_textInputGeneration == generation && [notification.name isEqualToString:NSWindowDidResignKeyNotification] && + notification.object == self.window && _textInputEnabled && _tentativeComposition) { + [self endOwnedNativeComposition]; + } } - (viva_editor_line)newTextLine { @@ -5063,7 +5130,30 @@ - (void)restartCaretBlink { [[NSRunLoop mainRunLoop] addTimer:_caretTimer forMode:NSRunLoopCommonModes]; } +- (void)notifyCompositionLost { + if (_callbackHandle != 0 && _textInputEnabled && _tentativeComposition) { + vivaTextCompositionLost(_callbackHandle, self, 1); + } +} + +- (void)endOwnedNativeComposition { + if (!_hasMarkedText || !_tentativeComposition) { + return; + } + uint64_t generation = _textInputGeneration; + _hasMarkedText = NO; + _markedRange = NSMakeRange(0, 0); + BOOL previousDiscarding = _discardingComposition; + _discardingComposition = YES; + [self.inputContext discardMarkedText]; + _discardingComposition = previousDiscarding; + if (_textInputGeneration == generation) { + [self notifyCompositionLost]; + } +} + - (void)shutdownTextInput { + _textInputGeneration++; BOOL wasEnabled = _textInputEnabled; _textInputEnabled = NO; [self syncSecureEventInput]; @@ -5077,6 +5167,7 @@ - (void)shutdownTextInput { _textAltSendsEscape = NO; _textKeyReleases = NO; _textDisableIME = NO; + _tentativeComposition = NO; } - (void)detachCallbacks { @@ -5535,6 +5626,7 @@ - (int)updateTextInput:(viva_text_input_config)textInput keepComposition:(BOOL)k BOOL wasEnabled = _textInputEnabled; keep = keep && wasEnabled && textInput.enabled != 0; if (!keep) { + _textInputGeneration++; _textInputEnabled = NO; [self syncSecureEventInput]; _textSelectionDragging = NO; @@ -5557,6 +5649,7 @@ - (int)updateTextInput:(viva_text_input_config)textInput keepComposition:(BOOL)k _textAltSendsEscape = NO; _textKeyReleases = NO; _textDisableIME = NO; + _tentativeComposition = NO; [_text release]; _text = [@"" retain]; [_textColor release]; @@ -5601,6 +5694,7 @@ - (int)updateTextInput:(viva_text_input_config)textInput keepComposition:(BOOL)k // A surface that runs the other machine's input method has no composition // of this one to mirror. _hasMarkedText = textInput.has_marked_text != 0 && !_textDisableIME; + _tentativeComposition = textInput.tentative_composition != 0; _textInputMultiline = textInput.multiline != 0; _textPlaced = textInput.placed != 0; _textNavigationKeys = textInput.navigation_keys != 0; @@ -5658,7 +5752,9 @@ - (int)updateText:(const unsigned char *)utf8 length:(NSUInteger)length selectedRange:(NSRange)selectedRange markedRange:(NSRange)markedRange - hasMarkedText:(BOOL)hasMarkedText { + hasMarkedText:(BOOL)hasMarkedText + tentativeComposition:(BOOL)tentativeComposition + endsComposition:(BOOL)endsComposition { if (!_textInputEnabled || (utf8 == NULL && length > 0)) { return 1; } @@ -5668,16 +5764,27 @@ - (int)updateText:(const unsigned char *)utf8 if (replacement == nil) { return 2; } + BOOL lostComposition = _hasMarkedText && _tentativeComposition && tentativeComposition && !hasMarkedText && !endsComposition; [_text release]; _text = replacement; _selectedRange = viva_clamp_range(selectedRange, _text.length); _markedRange = viva_clamp_range(markedRange, _text.length); _hasMarkedText = hasMarkedText; + _tentativeComposition = tentativeComposition; _caretVisible = YES; if (![self rebuildTextTexture]) { + if (lostComposition) { + // The editor's texture is gone, but the composition it lost is not: + // record it before the early return, because the retry re-evaluates + // against the state this call already installed. + [self notifyCompositionLost]; + } return 3; } [self restartCaretBlink]; + if (lostComposition) { + [self notifyCompositionLost]; + } return 0; } @@ -5686,7 +5793,7 @@ - (void)emitTextKind:(int)kind selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange command:(int)command { - if (_callbackHandle == 0 || !_textInputEnabled) { + if (_discardingComposition || _callbackHandle == 0 || !_textInputEnabled) { return; } if (_interpretingKey) { @@ -5701,14 +5808,53 @@ - (void)emitTextKind:(int)kind _interpretedConsumed = YES; } NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding]; + int phase = _tentativeComposition ? viva_text_composition_phase(kind, text.length, _hasMarkedText, replacementRange) : VIVA_COMPOSITION_NONE; + // AppKit names ranges in the view text, which still holds the preedit; the + // phased engine applies a replacement to the text after the tentative + // rollback. A range that names the marked text is the composition + // continuing or committing, so the engine must act on the composition + // itself; a range beyond it shifts left by the preedit. + NSRange phasedReplacement = replacementRange; + if (phase != VIVA_COMPOSITION_NONE && _hasMarkedText && phasedReplacement.location != NSNotFound) { + NSRange marked = _markedRange; + NSUInteger markedEnd = marked.location + marked.length; + NSUInteger end = phasedReplacement.length > NSUIntegerMax - phasedReplacement.location + ? NSUIntegerMax + : phasedReplacement.location + phasedReplacement.length; + BOOL namesComposition = phasedReplacement.location >= marked.location && end <= markedEnd; + BOOL caretInComposition = phasedReplacement.length == 0 && + phasedReplacement.location >= marked.location && phasedReplacement.location <= markedEnd; + if (namesComposition || caretInComposition) { + phasedReplacement = NSMakeRange(NSNotFound, 0); + } else { + NSUInteger start = phasedReplacement.location >= markedEnd + ? phasedReplacement.location - marked.length + : phasedReplacement.location; + NSUInteger stop = end >= markedEnd + ? end - marked.length + : end > marked.location ? marked.location : end; + if (stop < start) { + stop = start; + } + phasedReplacement = NSMakeRange(start, stop - start); + } + } int64_t replacementStart = -1; int64_t replacementLength = 0; - if (replacementRange.location != NSNotFound) { + if (phase == VIVA_COMPOSITION_NONE && replacementRange.location != NSNotFound) { replacementStart = (int64_t)replacementRange.location; replacementLength = (int64_t)replacementRange.length; } + BOOL raw = phase != VIVA_COMPOSITION_NONE && phasedReplacement.location != NSNotFound; viva_text_event_count++; - vivaTextInput( + if (phase == VIVA_COMPOSITION_NONE) { + vivaTextInput(_callbackHandle, self, kind, + data.length > 0 ? data.bytes : NULL, data.length, + (int64_t)selectedRange.location, (int64_t)selectedRange.length, + replacementStart, replacementLength, command); + return; + } + vivaCompositionInput( _callbackHandle, self, kind, @@ -5718,7 +5864,11 @@ - (void)emitTextKind:(int)kind (int64_t)selectedRange.length, replacementStart, replacementLength, - command + command, + phase, + raw ? viva_text_raw_coordinate(phasedReplacement.location) : 0, + raw ? viva_text_raw_coordinate(phasedReplacement.length) : 0, + raw ? 1 : 0 ); } @@ -5872,7 +6022,16 @@ - (void)selectTextRange:(NSRange)range { return; } if (_hasMarkedText) { - [self.inputContext discardMarkedText]; + if (_tentativeComposition) { + uint64_t generation = _textInputGeneration; + [self endOwnedNativeComposition]; + if (_textInputGeneration != generation || !_textInputEnabled) { + return; + } + range = viva_clamp_range(range, _text.length); + } else { + [self.inputContext discardMarkedText]; + } } [self emitTextKind:VIVA_TEXT_SET_SELECTION text:@"" @@ -7739,6 +7898,8 @@ int viva_view_update_text( size_t marked_start, size_t marked_length, int has_marked_text, + int tentative_composition, + int ends_composition, int render ) { if (view == NULL) { @@ -7750,7 +7911,9 @@ int viva_view_update_text( length:utf8_length selectedRange:NSMakeRange(selected_start, selected_length) markedRange:NSMakeRange(marked_start, marked_length) - hasMarkedText:has_marked_text != 0]; + hasMarkedText:has_marked_text != 0 + tentativeComposition:tentative_composition != 0 + endsComposition:ends_composition != 0]; if (status == 0 && render != 0) { [(VivaMetalView *)view render]; } diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index eeda0a4b2..fdf658132 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -167,6 +167,7 @@ type runState struct { textInput TextInput textInputActive bool textEventRedraw bool + textComposition *nativeTextComposition // web hosts the pages of the window when the application asked for any. web *webState webReady func() @@ -232,17 +233,27 @@ func (window *nativeWindow) MoveTo(origin gfx.Point) { } func (state *runState) setTextInput(input *TextInput) { + keepComposition := state.textComposition != nil && input != nil && input.State.TentativeComposition && state.textInputKeepsComposition(input) if input == nil { state.textHandler = nil state.textState = TextState{} state.textInput = TextInput{} state.textInputActive = false + state.textComposition = nil return } state.textHandler = input.OnEvent state.textState = input.State state.textInput = *input state.textInputActive = true + if !input.State.TentativeComposition { + state.textComposition = nil + } else if state.textComposition == nil { + state.textComposition = &nativeTextComposition{} + } else if !keepComposition { + state.textComposition.epoch++ + state.textComposition.pending = false + } } func (state *runState) textInputAlreadyUpdated(input *TextInput) bool { @@ -811,43 +822,44 @@ func makeNativeTextInput(input TextInput, value unsafe.Pointer) C.viva_text_inpu markedStart := editor.RuneIndexToUTF16(input.State.Composition.Start) markedEnd := editor.RuneIndexToUTF16(input.State.Composition.End) return C.viva_text_input_config{ - utf8: (*C.uchar)(value), - utf8_length: C.size_t(len(input.State.Value)), - copy_override: C.int(boolInt(input.CopyOverride)), - x: C.float(input.X), - y: C.float(input.Y), - width: C.float(input.Width), - height: C.float(input.Height), - font_size: C.float(input.FontSize), - font_weight: C.float(input.Weight), - alignment: C.int(input.Alignment), - red: C.float(input.Color.Red), - green: C.float(input.Color.Green), - blue: C.float(input.Color.Blue), - alpha: C.float(input.Color.Alpha), - selected_start: C.size_t(selectedStart), - selected_length: C.size_t(selectedEnd - selectedStart), - marked_start: C.size_t(markedStart), - marked_length: C.size_t(markedEnd - markedStart), - has_marked_text: C.int(boolInt(input.State.Composing)), - multiline: C.int(boolInt(input.Multiline)), - secure: C.int(boolInt(input.Secure)), - terminal: C.int(boolInt(input.Terminal)), - hide_native_overlays: C.int(boolInt(input.HideNativeOverlays)), - mono_face: C.int(input.MonoFace), - cell_width: C.float(input.CellWidth), - baseline: C.float(input.Baseline), - alt_sends_escape: C.int(boolInt(input.AltSendsEscape)), - key_releases: C.int(boolInt(input.KeyReleases)), - disable_ime: C.int(boolInt(input.DisableIME)), - navigation_keys: C.int(boolInt(input.NavigationKeys)), - placed: C.int(boolInt(input.Placed)), - layer: C.uint16_t(input.Layer), - caret_x: C.float(input.CaretX), - caret_y: C.float(input.CaretY), - caret_width: C.float(input.CaretWidth), - caret_height: C.float(input.CaretHeight), - enabled: 1, + utf8: (*C.uchar)(value), + utf8_length: C.size_t(len(input.State.Value)), + copy_override: C.int(boolInt(input.CopyOverride)), + x: C.float(input.X), + y: C.float(input.Y), + width: C.float(input.Width), + height: C.float(input.Height), + font_size: C.float(input.FontSize), + font_weight: C.float(input.Weight), + alignment: C.int(input.Alignment), + red: C.float(input.Color.Red), + green: C.float(input.Color.Green), + blue: C.float(input.Color.Blue), + alpha: C.float(input.Color.Alpha), + selected_start: C.size_t(selectedStart), + selected_length: C.size_t(selectedEnd - selectedStart), + marked_start: C.size_t(markedStart), + marked_length: C.size_t(markedEnd - markedStart), + has_marked_text: C.int(boolInt(input.State.Composing)), + tentative_composition: C.int(boolInt(input.State.TentativeComposition)), + multiline: C.int(boolInt(input.Multiline)), + secure: C.int(boolInt(input.Secure)), + terminal: C.int(boolInt(input.Terminal)), + hide_native_overlays: C.int(boolInt(input.HideNativeOverlays)), + mono_face: C.int(input.MonoFace), + cell_width: C.float(input.CellWidth), + baseline: C.float(input.Baseline), + alt_sends_escape: C.int(boolInt(input.AltSendsEscape)), + key_releases: C.int(boolInt(input.KeyReleases)), + disable_ime: C.int(boolInt(input.DisableIME)), + navigation_keys: C.int(boolInt(input.NavigationKeys)), + placed: C.int(boolInt(input.Placed)), + layer: C.uint16_t(input.Layer), + caret_x: C.float(input.CaretX), + caret_y: C.float(input.CaretY), + caret_width: C.float(input.CaretWidth), + caret_height: C.float(input.CaretHeight), + enabled: 1, } } diff --git a/internal/platform/darwin/testdata/dock_reopen.m b/internal/platform/darwin/testdata/dock_reopen.m index 4a0530299..45a84f734 100644 --- a/internal/platform/darwin/testdata/dock_reopen.m +++ b/internal/platform/darwin/testdata/dock_reopen.m @@ -29,6 +29,11 @@ void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, size_t length, int64_t start, int64_t selectedLength, int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } // Exercise the native delegate without showing windows or activating the test. diff --git a/internal/platform/darwin/testdata/file_drop.m b/internal/platform/darwin/testdata/file_drop.m index 083248f72..bb3652505 100644 --- a/internal/platform/darwin/testdata/file_drop.m +++ b/internal/platform/darwin/testdata/file_drop.m @@ -49,6 +49,11 @@ void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, size_t length, int64_t start, int64_t selectedLength, int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } // What AppKit hands a drop target: where the pointer is and what is dragged. diff --git a/internal/platform/darwin/testdata/live_resize.m b/internal/platform/darwin/testdata/live_resize.m index e7bb23487..bcef9abb4 100644 --- a/internal/platform/darwin/testdata/live_resize.m +++ b/internal/platform/darwin/testdata/live_resize.m @@ -33,6 +33,11 @@ void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, size_t length, int64_t start, int64_t selectedLength, int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } int main(void) { diff --git a/internal/platform/darwin/testdata/modifier_taps.m b/internal/platform/darwin/testdata/modifier_taps.m index b3da63d29..298f97bca 100644 --- a/internal/platform/darwin/testdata/modifier_taps.m +++ b/internal/platform/darwin/testdata/modifier_taps.m @@ -42,6 +42,11 @@ void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, size_t length, int64_t start, int64_t selectedLength, int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } diff --git a/internal/platform/darwin/testdata/tentative_bridge_darwin.go b/internal/platform/darwin/testdata/tentative_bridge_darwin.go new file mode 100644 index 000000000..f05712445 --- /dev/null +++ b/internal/platform/darwin/testdata/tentative_bridge_darwin.go @@ -0,0 +1,185 @@ +package darwin + +/* +#include +#include +#include +#include +#include +#include +#include +#include "native.h" + +typedef struct { unsigned long start, length; } tentative_range; +static int tentative_activations, tentative_deactivations, tentative_discards; +static int tentative_discard_unmarks; +static id tentative_context_view; +static BOOL tentative_true(id object, SEL selector) { return YES; } +static void tentative_noop(id object, SEL selector) {} +static void tentative_activate(id object, SEL selector) { tentative_activations++; } +static void tentative_deactivate(id object, SEL selector) { tentative_deactivations++; } +static void tentative_discard(id object, SEL selector) { + tentative_discards++; + if (tentative_discard_unmarks) { + ((void (*)(id, SEL))objc_msgSend)(tentative_context_view, sel_registerName("unmarkText")); + } +} +static id tentative_context(id object, SEL selector) { + tentative_context_view = object; + static id context; + if (!context) { + Class kind = objc_allocateClassPair(objc_getClass("NSObject"), "VivaTentativeBridgeContext", 0); + class_addMethod(kind, sel_registerName("activate"), (IMP)tentative_activate, "v@:"); + class_addMethod(kind, sel_registerName("deactivate"), (IMP)tentative_deactivate, "v@:"); + class_addMethod(kind, sel_registerName("discardMarkedText"), (IMP)tentative_discard, "v@:"); + class_addMethod(kind, sel_registerName("invalidateCharacterCoordinates"), (IMP)tentative_noop, "v@:"); + objc_registerClassPair(kind); + context = ((id (*)(id, SEL))objc_msgSend)((id)kind, sel_registerName("alloc")); + context = ((id (*)(id, SEL))objc_msgSend)(context, sel_registerName("init")); + } + return context; +} +static void tentative_write(id object, const char *name, const void *value, size_t size) { + Ivar field = class_getInstanceVariable(object_getClass(object), name); + if (field == NULL) { abort(); } + memcpy((char *)object + ivar_getOffset(field), value, size); +} +static void *tentative_create(uintptr_t handle) { + Class kind = objc_getClass("VivaTentativeBridgeView"); + if (!kind) { + kind = objc_allocateClassPair(objc_getClass("VivaMetalView"), "VivaTentativeBridgeView", 0); + class_addMethod(kind, sel_registerName("rebuildTextTexture"), (IMP)tentative_true, "B@:"); + class_addMethod(kind, sel_registerName("inputContext"), (IMP)tentative_context, "@@:"); + class_addMethod(kind, sel_registerName("restartCaretBlink"), (IMP)tentative_noop, "v@:"); + class_addMethod(kind, sel_registerName("stopCaretBlink"), (IMP)tentative_noop, "v@:"); + class_addMethod(kind, sel_registerName("syncSecureEventInput"), (IMP)tentative_noop, "v@:"); + class_addMethod(kind, sel_registerName("render"), (IMP)tentative_noop, "v@:"); + objc_registerClassPair(kind); + } + id object = ((id (*)(id, SEL))objc_msgSend)((id)kind, sel_registerName("alloc")); + object = ((id (*)(id, SEL))objc_msgSend)(object, sel_registerName("init")); + BOOL dynamic = YES; + tentative_write(object, "_dynamicTextInput", &dynamic, sizeof(dynamic)); + tentative_write(object, "_callbackHandle", &handle, sizeof(handle)); + return object; +} +static CFStringRef tentative_string(const char *value) { + return CFStringCreateWithCString(NULL, value, kCFStringEncodingUTF8); +} +static void tentative_mark(void *view, const char *value, unsigned long start, unsigned long length, unsigned long replacementStart, unsigned long replacementLength, int hasReplacement) { + CFStringRef string = tentative_string(value); + tentative_range selection = {start, length}; + tentative_range replacement = {hasReplacement ? replacementStart : LONG_MAX, replacementLength}; + ((void (*)(id, SEL, id, tentative_range, tentative_range))objc_msgSend)((id)view, + sel_registerName("setMarkedText:selectedRange:replacementRange:"), (id)string, selection, replacement); + CFRelease(string); +} +static void tentative_insert(void *view, const char *value, unsigned long start, unsigned long length, int hasReplacement) { + CFStringRef string = tentative_string(value); + tentative_range replacement = {hasReplacement ? start : LONG_MAX, length}; + ((void (*)(id, SEL, id, tentative_range))objc_msgSend)((id)view, + sel_registerName("insertText:replacementRange:"), (id)string, replacement); + CFRelease(string); +} +static void tentative_unmark(void *view) { + ((void (*)(id, SEL))objc_msgSend)((id)view, sel_registerName("unmarkText")); +} +static void tentative_cancel(void *view) { + ((void (*)(id, SEL, SEL))objc_msgSend)((id)view, sel_registerName("doCommandBySelector:"), sel_registerName("cancelOperation:")); +} +static void tentative_select(void *view, unsigned long start, unsigned long length) { + tentative_range selection = {start, length}; + ((void (*)(id, SEL, tentative_range))objc_msgSend)((id)view, sel_registerName("selectTextRange:"), selection); +} +static void tentative_command(void *view) { + ((void (*)(id, SEL, SEL))objc_msgSend)((id)view, sel_registerName("doCommandBySelector:"), sel_registerName("moveWordLeft:")); +} +static void tentative_resign(void *view) { + ((BOOL (*)(id, SEL))objc_msgSend)((id)view, sel_registerName("resignFirstResponder")); +} +static void tentative_detach(void *view) { + ((void (*)(id, SEL))objc_msgSend)((id)view, sel_registerName("detachCallbacks")); +} +static void tentative_unmark_on_discard(int enabled) { tentative_discard_unmarks = enabled; } +static const char *tentative_text(void *pointer) { + id object = (id)pointer; + id value = object_getIvar(object, class_getInstanceVariable(object_getClass(object), "_text")); + return ((const char *(*)(id, SEL))objc_msgSend)(value, sel_registerName("UTF8String")); +} +static int tentative_marked(void *pointer) { + id object = (id)pointer; + BOOL marked; + Ivar field = class_getInstanceVariable(object_getClass(object), "_hasMarkedText"); + memcpy(&marked, (char *)object + ivar_getOffset(field), sizeof(marked)); + return marked != NO; +} +static void tentative_destroy(void *view) { + uintptr_t handle = 0; + tentative_write((id)view, "_callbackHandle", &handle, sizeof(handle)); + ((void (*)(id, SEL))objc_msgSend)((id)view, sel_registerName("release")); +} +static void tentative_reset_counts(void) { tentative_activations = tentative_deactivations = tentative_discards = 0; } +static int tentative_activate_count(void) { return tentative_activations; } +static int tentative_deactivate_count(void) { return tentative_deactivations; } +static int tentative_discard_count(void) { return tentative_discards; } +static size_t tentative_view_size(void) { return class_getInstanceSize(objc_getClass("VivaMetalView")); } +static void tentative_benchmark_insert(void *view) { + id pool = ((id (*)(id, SEL))objc_msgSend)((id)objc_getClass("NSAutoreleasePool"), sel_registerName("alloc")); + pool = ((id (*)(id, SEL))objc_msgSend)(pool, sel_registerName("init")); + tentative_range replacement = {LONG_MAX, 0}; + ((void (*)(id, SEL, id, tentative_range))objc_msgSend)((id)view, + sel_registerName("insertText:replacementRange:"), (id)CFSTR("x"), replacement); + ((void (*)(id, SEL))objc_msgSend)(pool, sel_registerName("drain")); +} +*/ +import "C" + +import ( + "runtime/cgo" + "unsafe" +) + +func tentativeBridgeView(state *runState) (unsafe.Pointer, func()) { + handle := cgo.NewHandle(state) + view := C.tentative_create(C.uintptr_t(handle)) + return view, func() { + C.tentative_destroy(view) + handle.Delete() + } +} + +func tentativeBridgeMark(view unsafe.Pointer, value string, selectedStart, selectedLength, replacementStart, replacementLength int, hasReplacement bool) { + string := C.CString(value) + defer C.free(unsafe.Pointer(string)) + C.tentative_mark(view, string, C.ulong(selectedStart), C.ulong(selectedLength), C.ulong(replacementStart), C.ulong(replacementLength), C.int(boolInt(hasReplacement))) +} + +func tentativeBridgeInsert(view unsafe.Pointer, value string, start, length int, hasReplacement bool) { + string := C.CString(value) + defer C.free(unsafe.Pointer(string)) + C.tentative_insert(view, string, C.ulong(start), C.ulong(length), C.int(boolInt(hasReplacement))) +} + +func tentativeBridgeUnmark(view unsafe.Pointer) { C.tentative_unmark(view) } +func tentativeBridgeCancel(view unsafe.Pointer) { C.tentative_cancel(view) } +func tentativeBridgeSelect(view unsafe.Pointer, start, length int) { + C.tentative_select(view, C.ulong(start), C.ulong(length)) +} +func tentativeBridgeCommand(view unsafe.Pointer) { C.tentative_command(view) } +func tentativeBridgeResign(view unsafe.Pointer) { C.tentative_resign(view) } +func tentativeBridgeDetach(view unsafe.Pointer) { C.tentative_detach(view) } +func tentativeBridgeUnmarkOnDiscard(enabled bool) { + C.tentative_unmark_on_discard(C.int(boolInt(enabled))) +} +func tentativeBridgeText(view unsafe.Pointer) string { return C.GoString(C.tentative_text(view)) } +func tentativeBridgeMarked(view unsafe.Pointer) bool { return C.tentative_marked(view) != 0 } +func resetTentativeBridgeCounts() { C.tentative_reset_counts() } +func tentativeBridgeCounts() (int, int, int) { + return int(C.tentative_activate_count()), int(C.tentative_deactivate_count()), int(C.tentative_discard_count()) +} + +func tentativeBridgeSizes() (int, int) { + return int(C.sizeof_viva_text_input_config), int(C.tentative_view_size()) +} + +func tentativeBridgeBenchmarkInsert(view unsafe.Pointer) { C.tentative_benchmark_insert(view) } diff --git a/internal/platform/darwin/testdata/tentative_bridge_darwin_test.go b/internal/platform/darwin/testdata/tentative_bridge_darwin_test.go new file mode 100644 index 000000000..2b8b4bde1 --- /dev/null +++ b/internal/platform/darwin/testdata/tentative_bridge_darwin_test.go @@ -0,0 +1,602 @@ +package darwin + +import ( + "encoding/json" + "reflect" + "testing" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +type tentativeBridgeProbe struct { + editor *text.Editor + state *runState + view unsafe.Pointer + events []TextEvent +} + +func newTentativeBridgeProbe(t testing.TB, value string, enabled bool) *tentativeBridgeProbe { + t.Helper() + probe := &tentativeBridgeProbe{editor: text.NewEditor(value), state: &runState{}} + probe.editor.MoveTo(probe.editor.RuneCount(), false) + if enabled && !probe.editor.EnableTentativeComposition() { + t.Fatal("tentative capability refused") + } + view, cleanup := tentativeBridgeView(probe.state) + probe.view = view + t.Cleanup(cleanup) + input := TextInput{Target: gfx.IDFromBits(7), Width: 100, Height: 20, FontSize: 12, State: platform.EditorState(probe.editor)} + input.OnEvent = func(event TextEvent) (TextState, error) { + probe.events = append(probe.events, event) + event.Apply(probe.editor) + return platform.EditorState(probe.editor), nil + } + if err := presentTextInput(probe.state, view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + return probe +} + +func (probe *tentativeBridgeProbe) assertState(t *testing.T, want string) { + t.Helper() + if probe.editor.String() != want || probe.state.textState != platform.EditorState(probe.editor) || probe.state.textInput.State != probe.state.textState || tentativeBridgeText(probe.view) != want { + t.Fatalf("native acknowledgment: editor=%q bridge=%+v input=%+v native=%q; want %q", probe.editor.String(), probe.state.textState, probe.state.textInput.State, tentativeBridgeText(probe.view), want) + } + if probe.state.err != nil { + t.Fatal(probe.state.err) + } +} + +func TestDarwinTentativeProbeTerminalPhases(t *testing.T) { + for _, test := range []struct { + name string + phase text.CompositionPhase + want string + }{ + {"result", text.CompositionResult, "abcZ"}, + {"commit", text.CompositionCommit, "abcx"}, + {"cancel", text.CompositionCancel, "abc"}, + {"empty commit", text.CompositionEmptyCommit, "abc"}, + {"empty update", text.CompositionCancel, "abc"}, + } { + t.Run(test.name, func(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + probe.assertState(t, "abcx") + if len(probe.events) != 1 || probe.events[0].CompositionPhase != text.CompositionUpdate { + t.Errorf("real marked update lost phase: %+v", probe.events) + } + switch test.name { + case "result": + tentativeBridgeInsert(probe.view, "Z", 0, 0, false) + case "commit": + tentativeBridgeUnmark(probe.view) + case "cancel": + tentativeBridgeCancel(probe.view) + case "empty commit": + tentativeBridgeInsert(probe.view, "", 0, 0, false) + case "empty update": + tentativeBridgeMark(probe.view, "", 0, 0, 0, 0, false) + } + probe.assertState(t, test.want) + if len(probe.events) != 2 || probe.events[1].CompositionPhase != test.phase { + t.Fatalf("native terminal phase = %+v; want %v", probe.events, test.phase) + } + if _, composing := probe.editor.Composition(); composing { + t.Fatal("native terminal stranded a live composition") + } + if test.phase == text.CompositionResult || test.phase == text.CompositionCommit { + if !probe.editor.Undo() || probe.editor.String() != "abc" || probe.editor.CanUndo() { + t.Fatalf("native terminal source Undo = %q", probe.editor.String()) + } + } else if probe.editor.CanUndo() { + t.Fatal("native cancellation fabricated ordinary history") + } + }) + } +} + +func TestDarwinTentativeProbeRawResultAfterRollback(t *testing.T) { + probe := newTentativeBridgeProbe(t, "A\U0001d11eBC", true) + probe.editor.MoveTo(0, false) + input := probe.state.textInput + input.State = platform.EditorState(probe.editor) + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + probe.assertState(t, "xA\U0001d11eBC") + // AppKit names the view text, preedit included: index 4 is the "B" the + // result replaces once the tentative "x" is rolled back. + tentativeBridgeInsert(probe.view, "Z", 4, 1, true) + probe.assertState(t, "A\U0001d11eZC") + result := probe.events[len(probe.events)-1] + if !result.HasReplacementUTF16 || result.ReplacementUTF16 != (text.UTF16Range{Start: 3, Length: 1}) || result.CompositionPhase != text.CompositionResult { + t.Fatalf("raw native replacement provenance lost: %+v", result) + } + for _, want := range []string{"A\U0001d11eC", "A\U0001d11eBC"} { + if !probe.editor.Undo() || probe.editor.String() != want { + t.Fatalf("raw native result Undo = %q; want %q", probe.editor.String(), want) + } + } +} + +func TestDarwinTentativeProbeMarkedRangeContinuationUpdates(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + probe.editor.MoveTo(1, false) + input := probe.state.textInput + input.State = platform.EditorState(probe.editor) + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + tentativeBridgeMark(probe.view, "x", 1, 0, 1, 0, false) + probe.assertState(t, "axbc") + // AppKit reports the marked text in view coordinates when it continues the + // composition. That is the same composition, not an out-of-band replacement, + // so the update must land instead of being refused. + tentativeBridgeMark(probe.view, "xy", 2, 0, 1, 1, true) + probe.assertState(t, "axybc") + if last := probe.events[len(probe.events)-1]; last.CompositionPhase != text.CompositionUpdate || last.HasReplacementUTF16 { + t.Fatalf("continuation event = %+v; want an update that acts on the composition", last) + } +} + +func TestDarwinTentativeProbeMarkedRangeResultUsesTheComposition(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + probe.editor.MoveTo(1, false) + input := probe.state.textInput + input.State = platform.EditorState(probe.editor) + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + tentativeBridgeMark(probe.view, "x", 1, 0, 1, 0, false) + probe.assertState(t, "axbc") + // Committing with a range that names the preedit replaces the composition, + // not whatever runes sat at that offset before it was inserted. + tentativeBridgeInsert(probe.view, "Z", 1, 1, true) + probe.assertState(t, "aZbc") + last := probe.events[len(probe.events)-1] + if last.CompositionPhase != text.CompositionResult || last.HasReplacementUTF16 { + t.Fatalf("commit event = %+v; want a result that acts on the composition", last) + } +} + +func TestDarwinTentativeProbeLegacyAndOrdinaryInput(t *testing.T) { + for _, enabled := range []bool{false, true} { + name := "legacy" + if enabled { + name = "enabled ordinary" + } + t.Run(name, func(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", enabled) + tentativeBridgeInsert(probe.view, "Z", 0, 0, false) + probe.assertState(t, "abcZ") + if len(probe.events) != 1 || probe.events[0].CompositionPhase != text.CompositionNone || probe.events[0].HasReplacementUTF16 { + t.Fatalf("ordinary input acquired composition facts: %+v", probe.events) + } + if !enabled { + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + tentativeBridgeInsert(probe.view, "Y", 0, 0, false) + probe.assertState(t, "abcZY") + for _, event := range probe.events { + if event.CompositionPhase != text.CompositionNone || event.HasReplacementUTF16 { + t.Fatalf("disabled owner received tentative facts: %+v", event) + } + } + } + }) + } +} + +func TestDarwinTentativeProbePresentationRefreshKeepsContext(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + before := append([]TextEvent(nil), probe.events...) + resetTentativeBridgeCounts() + for _, change := range []func(*TextInput){ + func(input *TextInput) { input.X++ }, + func(input *TextInput) { input.Width++ }, + func(input *TextInput) { input.FontSize++ }, + } { + input := probe.state.textInput + change(&input) + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + probe.assertState(t, "abcx") + } + activate, deactivate, discard := tentativeBridgeCounts() + if activate != 0 || deactivate != 0 || discard != 0 || !reflect.DeepEqual(before, probe.events) { + t.Fatalf("refresh restarted native context: activate=%d deactivate=%d discard=%d events=%+v", activate, deactivate, discard, probe.events) + } +} + +func TestDarwinTentativeProbeRawRangeBoundaries(t *testing.T) { + maximum := int(^uint(0) >> 1) + for _, test := range []struct { + name string + start, length int + raw text.UTF16Range + hasRaw bool + want string + }{ + {"not found", maximum, 0, text.UTF16Range{}, false, "a\U0001d11ebZ"}, + {"split surrogate", 2, 0, text.UTF16Range{Start: 2}, true, "a\U0001d11ebZ"}, + {"past end", 100, 99, text.UTF16Range{Start: 99, Length: 99}, true, "a\U0001d11ebZ"}, + {"unsigned start", -2, 1, text.UTF16Range{Start: maximum, Length: 1}, true, "a\U0001d11ebZ"}, + {"unsigned length", 1, -2, text.UTF16Range{Start: 1, Length: maximum}, true, "aZ"}, + } { + t.Run(test.name, func(t *testing.T) { + probe := newTentativeBridgeProbe(t, "a\U0001d11eb", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + tentativeBridgeInsert(probe.view, "Z", test.start, test.length, true) + probe.assertState(t, test.want) + last := probe.events[len(probe.events)-1] + if last.HasReplacementUTF16 != test.hasRaw || last.ReplacementUTF16 != test.raw { + t.Fatalf("native raw range = %+v; want %+v available=%v", last, test.raw, test.hasRaw) + } + }) + } +} + +func TestDarwinTentativeProbeExplicitEmptyCommit(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeInsert(probe.view, "", 1, 1, true) + probe.assertState(t, "ac") + if len(probe.events) != 1 || probe.events[0].CompositionPhase != text.CompositionEmptyCommit || !probe.events[0].HasReplacementUTF16 { + t.Fatalf("explicit native empty commit = %+v", probe.events) + } + if !probe.editor.Undo() || probe.editor.String() != "abc" || probe.editor.CanUndo() { + t.Fatalf("empty commit Undo = %q", probe.editor.String()) + } +} + +func TestDarwinTentativeProbeDeferredLossKeepsFinalAcknowledgment(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + probe.state.textHandler = func(event TextEvent) (TextState, error) { + probe.events = append(probe.events, event) + if event.CompositionPhase == text.CompositionCancel { + event.Apply(probe.editor) + return platform.EditorState(probe.editor), nil + } + next := platform.EditorState(probe.editor) + next.Composing = false + next.Composition = text.Range{} + return next, nil + } + probe.state.textInput.OnEvent = probe.state.textHandler + tentativeBridgeCommand(probe.view) + probe.assertState(t, "abc") + if len(probe.events) != 3 || probe.events[1].Kind != TextCommandEvent || probe.events[2].CompositionPhase != text.CompositionCancel || probe.editor.CanUndo() { + t.Fatalf("native state loss did not cancel exactly once: %+v", probe.events) + } +} + +func TestDarwinTentativeProbeSameOwnerPresentationLoss(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + input := probe.state.textInput + input.X++ + input.State.Composing = false + input.State.Composition = text.Range{} + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + probe.assertState(t, "abc") + if len(probe.events) != 2 || probe.events[1].CompositionPhase != text.CompositionCancel || probe.editor.CanUndo() { + t.Fatalf("same-owner presentation loss = %+v", probe.events) + } + if probe.state.textInput.X != input.X { + t.Fatal("resolved cancellation lost the incoming presentation") + } +} + +func TestDarwinTentativeProbeNewOwnerDoesNotReceiveOldCancel(t *testing.T) { + for _, target := range []uint64{7, 8} { + t.Run(map[uint64]string{7: "same target", 8: "different target"}[target], func(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + probe.editor.ApplyComposition(text.CompositionEvent{Phase: text.CompositionCancel}) + nextEditor := text.NewEditor("abc") + nextEditor.MoveTo(3, false) + if !nextEditor.EnableTentativeComposition() || !nextEditor.ApplyComposition(text.CompositionEvent{Phase: text.CompositionUpdate, Text: "x", Selected: text.Range{Start: 1, End: 1}}) { + t.Fatal("new owner refused the real tentative") + } + input := probe.state.textInput + input.Target = gfx.IDFromBits(target) + input.State = platform.EditorState(nextEditor) + if input.State.CompositionIdentity == probe.state.textState.CompositionIdentity { + t.Fatal("distinct editor capability reused the old identity") + } + var nextEvents []TextEvent + input.OnEvent = func(event TextEvent) (TextState, error) { + nextEvents = append(nextEvents, event) + event.Apply(nextEditor) + return platform.EditorState(nextEditor), nil + } + resetTentativeBridgeCounts() + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + activate, deactivate, discard := tentativeBridgeCounts() + if activate != 1 || deactivate != 1 || discard != 1 || len(nextEvents) != 0 || probe.editor.String() != "abc" || probe.state.textState != platform.EditorState(nextEditor) || tentativeBridgeText(probe.view) != "abcx" { + t.Fatalf("new owner inherited old callbacks: events=%+v old=%q state=%+v native=%q context=%d/%d/%d", nextEvents, probe.editor.String(), probe.state.textState, tentativeBridgeText(probe.view), activate, deactivate, discard) + } + tentativeBridgeInsert(probe.view, "Z", 0, 0, false) + if nextEditor.String() != "abcZ" || probe.editor.String() != "abc" || len(nextEvents) != 1 || nextEvents[0].CompositionPhase != text.CompositionResult { + t.Fatalf("new owner Result = %q old=%q events=%+v", nextEditor.String(), probe.editor.String(), nextEvents) + } + }) + } +} + +func TestDarwinTentativeProbeNestedAcknowledgmentWins(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + old := probe.state.textState + probe.state.textHandler = func(event TextEvent) (TextState, error) { + probe.events = append(probe.events, event) + event.Apply(probe.editor) + if event.CompositionPhase == text.CompositionResult { + tentativeBridgeUnmark(probe.view) + return old, nil + } + return platform.EditorState(probe.editor), nil + } + probe.state.textInput.OnEvent = probe.state.textHandler + tentativeBridgeInsert(probe.view, "Z", 0, 0, false) + probe.assertState(t, "abcZ") + if len(probe.events) != 3 || probe.events[2].CompositionPhase != text.CompositionCommit || !probe.editor.Undo() || probe.editor.String() != "abc" || probe.editor.CanUndo() { + t.Fatalf("nested acknowledgment changed source history: %+v text=%q", probe.events, probe.editor.String()) + } +} + +func TestDarwinTentativeProbeRefusedLossRestoresNativeMark(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + probe.state.textHandler = func(event TextEvent) (TextState, error) { + probe.events = append(probe.events, event) + next := platform.EditorState(probe.editor) + if event.CompositionPhase != text.CompositionCancel { + next.Composing = false + next.Composition = text.Range{} + } + return next, nil + } + probe.state.textInput.OnEvent = probe.state.textHandler + tentativeBridgeCommand(probe.view) + probe.assertState(t, "abcx") + if !tentativeBridgeMarked(probe.view) || len(probe.events) != 3 || probe.events[2].CompositionPhase != text.CompositionCancel || !probe.editor.TentativeCompositionActive() { + t.Fatalf("refused loss desynchronized native preedit: marked=%v events=%+v", tentativeBridgeMarked(probe.view), probe.events) + } +} + +func TestDarwinTentativeProbeFocusLossCancelsOnce(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + tentativeBridgeUnmarkOnDiscard(true) + t.Cleanup(func() { tentativeBridgeUnmarkOnDiscard(false) }) + tentativeBridgeResign(probe.view) + tentativeBridgeResign(probe.view) + probe.assertState(t, "abc") + if len(probe.events) != 2 || probe.events[1].CompositionPhase != text.CompositionCancel || probe.editor.CanUndo() { + t.Fatalf("native focus loss committed or repeated preedit: %+v", probe.events) + } +} + +func TestDarwinTentativeProbeSelectionCancelsBeforeCoordinates(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + tentativeBridgeUnmarkOnDiscard(true) + t.Cleanup(func() { tentativeBridgeUnmarkOnDiscard(false) }) + tentativeBridgeSelect(probe.view, 4, 0) + probe.assertState(t, "abc") + if len(probe.events) != 3 || probe.events[1].CompositionPhase != text.CompositionCancel || probe.events[2].Kind != TextSetSelection || probe.events[2].Selection != (text.Range{Start: 3, End: 3}) || probe.editor.CanUndo() { + t.Fatalf("native selection retained stale coordinates or committed preedit: %+v", probe.events) + } +} + +func TestDarwinTentativeProbeSelectionCannotFollowAReplacementOwner(t *testing.T) { + for _, name := range []string{"same target", "different target", "passive owner"} { + t.Run(name, func(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + nextEditor := text.NewEditor("replacement") + nextEditor.SetSelection(text.Range{Start: 1, End: 3}) + if name != "passive owner" && !nextEditor.EnableTentativeComposition() { + t.Fatal("next owner refused tentative composition") + } + want := platform.EditorState(nextEditor) + var nextEvents []TextEvent + probe.state.textHandler = func(event TextEvent) (TextState, error) { + probe.events = append(probe.events, event) + event.Apply(probe.editor) + if event.CompositionPhase == text.CompositionCancel { + input := probe.state.textInput + if name == "different target" { + input.Target = gfx.IDFromBits(8) + } + input.State = want + input.OnEvent = func(event TextEvent) (TextState, error) { + nextEvents = append(nextEvents, event) + event.Apply(nextEditor) + return platform.EditorState(nextEditor), nil + } + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + } + return platform.EditorState(probe.editor), nil + } + probe.state.textInput.OnEvent = probe.state.textHandler + tentativeBridgeSelect(probe.view, 4, 0) + if len(nextEvents) != 0 || platform.EditorState(nextEditor) != want || probe.state.textState != want || probe.state.textInput.State != want || tentativeBridgeText(probe.view) != want.Value { + t.Fatalf("old selection reached replacement owner: events=%+v editor=%+v bridge=%+v native=%q", nextEvents, platform.EditorState(nextEditor), probe.state.textState, tentativeBridgeText(probe.view)) + } + if probe.editor.String() != "abc" || probe.editor.CompositionActive() || probe.editor.CanUndo() || probe.state.err != nil { + t.Fatalf("old owner was not canceled: text=%q events=%+v error=%v", probe.editor.String(), probe.events, probe.state.err) + } + }) + } +} + +func TestDarwinTentativeProbeDetachIsSilent(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + tentativeBridgeDetach(probe.view) + if len(probe.events) != 1 || !probe.editor.TentativeCompositionActive() || tentativeBridgeMarked(probe.view) { + t.Fatalf("native detach fabricated owner settlement: events=%+v editor=%q marked=%v", probe.events, probe.editor.String(), tentativeBridgeMarked(probe.view)) + } +} + +func TestDarwinTentativeProbeLayout(t *testing.T) { + config, view := tentativeBridgeSizes() + sidecar := uintptr(0) + if field, ok := reflect.TypeFor[runState]().FieldByName("textComposition"); ok { + sidecar = field.Type.Elem().Size() + } + data, err := json.Marshal(struct { + RunState, TextEvent, TextState, TextInput, NativeConfig, NativeView, EnabledSidecar uintptr + }{unsafe.Sizeof(runState{}), unsafe.Sizeof(TextEvent{}), unsafe.Sizeof(TextState{}), unsafe.Sizeof(TextInput{}), uintptr(config), uintptr(view), sidecar}) + if err != nil { + t.Fatal(err) + } + t.Logf("VIVA_LAYOUT %s", data) +} + +func TestDarwinTentativeProbeRejectedUpdatePreservesOwner(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + before := platform.EditorState(probe.editor) + tentativeBridgeMark(probe.view, "bad", 3, 0, 1, 1, true) + probe.assertState(t, "abcx") + if platform.EditorState(probe.editor) != before || !tentativeBridgeMarked(probe.view) || !probe.editor.TentativeCompositionActive() { + t.Fatal("rejected native update changed the tentative boundary") + } + input := probe.state.textInput + input.State.Selection = text.Range{Start: -1, End: 0} + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err == nil { + t.Fatal("invalid native presentation was accepted") + } + probe.assertState(t, "abcx") + if !tentativeBridgeMarked(probe.view) || platform.EditorState(probe.editor) != before { + t.Fatal("rejected presentation retired the current native owner") + } +} + +func TestDarwinTentativeProbePassiveSnapshotKeepsLegacyInput(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + probe.editor.ApplyComposition(text.CompositionEvent{Phase: text.CompositionCancel}) + probe.editor.DisableTentativeComposition() + input := probe.state.textInput + input.State = platform.EditorState(probe.editor) + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + tentativeBridgeMark(probe.view, "y", 1, 0, 0, 0, false) + tentativeBridgeInsert(probe.view, "Z", 0, 0, false) + probe.assertState(t, "abcZ") + for _, event := range probe.events[1:] { + if event.CompositionPhase != text.CompositionNone || event.HasReplacementUTF16 { + t.Fatalf("passive snapshot kept a tagged native route: %+v", event) + } + } + if probe.state.textState.TentativeComposition || probe.editor.TentativeCompositionEnabled() { + t.Fatal("passive native input fabricated a successful capability") + } +} + +func TestDarwinTentativeProbeLossCanReplaceOwner(t *testing.T) { + probe := newTentativeBridgeProbe(t, "abc", true) + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + nextEditor := text.NewEditor("next") + nextEditor.MoveTo(4, false) + if !nextEditor.EnableTentativeComposition() || !nextEditor.ApplyComposition(text.CompositionEvent{Phase: text.CompositionUpdate, Text: "y", Selected: text.Range{Start: 1, End: 1}}) { + t.Fatal("next owner refused a tentative") + } + var nextEvents []TextEvent + probe.state.textHandler = func(event TextEvent) (TextState, error) { + probe.events = append(probe.events, event) + if event.CompositionPhase == text.CompositionCancel { + event.Apply(probe.editor) + input := probe.state.textInput + input.Target = gfx.IDFromBits(8) + input.State = platform.EditorState(nextEditor) + input.OnEvent = func(event TextEvent) (TextState, error) { + nextEvents = append(nextEvents, event) + event.Apply(nextEditor) + return platform.EditorState(nextEditor), nil + } + if err := presentTextInput(probe.state, probe.view, TextInputUpdate{Changed: true, Input: &input}); err != nil { + t.Fatal(err) + } + return platform.EditorState(probe.editor), nil + } + next := platform.EditorState(probe.editor) + next.Composing = false + next.Composition = text.Range{} + return next, nil + } + probe.state.textInput.OnEvent = probe.state.textHandler + tentativeBridgeCommand(probe.view) + if probe.editor.String() != "abc" || probe.state.textState != platform.EditorState(nextEditor) || probe.state.textInput.Target != gfx.IDFromBits(8) || tentativeBridgeText(probe.view) != "nexty" || len(nextEvents) != 0 { + t.Fatalf("loss acknowledgment overwrote new owner: old=%q current=%+v native=%q nextEvents=%+v", probe.editor.String(), probe.state.textState, tentativeBridgeText(probe.view), nextEvents) + } +} + +func BenchmarkDarwinTentativeProbeInput(b *testing.B) { + for _, enabled := range []bool{false, true} { + name := "legacy" + if enabled { + name = "tentative" + } + b.Run(name, func(b *testing.B) { + probe := newTentativeBridgeProbe(b, "abc", enabled) + if enabled { + tentativeBridgeMark(probe.view, "x", 1, 0, 0, 0, false) + } + value := probe.editor.String() + probe.state.textHandler = func(event TextEvent) (TextState, error) { + if event.Kind != TextInsert || event.Text != "x" { + b.Fatalf("native benchmark received %+v", event) + } + return probe.state.textState, nil + } + probe.state.textInput.OnEvent = probe.state.textHandler + b.ReportAllocs() + for b.Loop() { + tentativeBridgeBenchmarkInsert(probe.view) + } + if probe.state.err != nil || tentativeBridgeText(probe.view) != value || probe.editor.String() != value { + b.Fatalf("native benchmark lost its fixed acknowledgment: %v native=%q editor=%q", probe.state.err, tentativeBridgeText(probe.view), probe.editor.String()) + } + }) + } +} + +func BenchmarkDarwinTentativeProbeOwner(b *testing.B) { + for _, enabled := range []bool{false, true} { + name := "legacy" + if enabled { + name = "tentative" + } + b.Run(name, func(b *testing.B) { + editor := text.NewEditor("abc") + if enabled && !editor.EnableTentativeComposition() { + b.Fatal("capability refused") + } + input := TextInput{Target: gfx.IDFromBits(7), State: platform.EditorState(editor)} + state := &runState{} + b.ReportAllocs() + for b.Loop() { + state.setTextInput(&input) + state.setTextInput(nil) + } + }) + } +} diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m index 2d80e91ea..b93799e28 100644 --- a/internal/platform/darwin/testdata/text_selection.m +++ b/internal/platform/darwin/testdata/text_selection.m @@ -91,6 +91,11 @@ void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, size_t length, int64_t start, int64_t selectedLength, int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} static NSUInteger copyRequests; diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index 88e7eaf94..b79ca0e04 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -32,6 +32,11 @@ void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, size_t length, int64_t start, int64_t selectedLength, int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } // A custom-titlebar window that is never ordered front: nothing appears on screen. diff --git a/internal/platform/darwin/testdata/window_close.m b/internal/platform/darwin/testdata/window_close.m index ea8733b7a..b55067003 100644 --- a/internal/platform/darwin/testdata/window_close.m +++ b/internal/platform/darwin/testdata/window_close.m @@ -40,6 +40,11 @@ void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, size_t length, int64_t start, int64_t selectedLength, int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } void vivaWindowClosed(uintptr_t handle) { diff --git a/internal/platform/darwin/testdata/window_size.m b/internal/platform/darwin/testdata/window_size.m index 9c9c1facb..89e42ea56 100644 --- a/internal/platform/darwin/testdata/window_size.m +++ b/internal/platform/darwin/testdata/window_size.m @@ -33,6 +33,11 @@ void vivaWindowFullscreen(uintptr_t handle, void *view, int fullscreen) {} void vivaTextInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, size_t length, int64_t start, int64_t selectedLength, int64_t replacementStart, int64_t replacementLength, int command) {} +void vivaCompositionInput(uintptr_t handle, void *view, int kind, const unsigned char *utf8, + size_t length, int64_t start, int64_t selectedLength, + int64_t replacementStart, int64_t replacementLength, int command, + int phase, int64_t rawStart, int64_t rawLength, int hasRaw) {} +void vivaTextCompositionLost(uintptr_t handle, void *view, int reason) {} unsigned char *vivaCopyText(uintptr_t handle, void *view, size_t *length) { *length = 0; return NULL; } static BOOL near(CGFloat a, CGFloat b) { return fabs(a - b) < 0.5; } From 7e8f0d9a965891b17a63506ce5ee1d22f35a5a70 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Mon, 16 Nov 2026 10:15:55 +0800 Subject: [PATCH 07/13] test(update): pin the recovery launch and its arguments The assertion merged with #310 only checked that the script mentions Restore; Launch, which an empty Launch body would still satisfy. Assert the helper definition, the forwarded argument list and both rollback paths. Based on the stronger assertion from #311 by 1lck. --- update/install_windows_test.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/update/install_windows_test.go b/update/install_windows_test.go index bbdd53c6e..47913be0a 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -244,7 +244,10 @@ func TestPayloadHelperScriptKeepsABackupAndRestores(t *testing.T) { "Copy-Item -LiteralPath $_.FullName -Destination $dest -Force", "Start-Process -FilePath $exe -PassThru", "$p.HasExited -and $p.ExitCode -ne 0", - "Restore; Launch", + "function Launch {", + "Start-Process -FilePath $exe -ArgumentList", + "if ($p.HasExited -and $p.ExitCode -ne 0) { Restore; Launch; exit 1 }", + "} catch { Restore; Launch; exit 1 }", "Remove-Item -Recurse -Force $payload", "exit 0", } { From 10c5b9230466e87e2d2b51b6bea456b8a944f094 Mon Sep 17 00:00:00 2001 From: Dean Cen Date: Mon, 16 Nov 2026 14:13:41 +0800 Subject: [PATCH 08/13] fix(update): launch Windows helpers without DETACHED_PROCESS --- update/install_windows.go | 20 ++++++++------ update/install_windows_test.go | 49 +++++++++++++++++++++------------- 2 files changed, 42 insertions(+), 27 deletions(-) diff --git a/update/install_windows.go b/update/install_windows.go index a39ca3a80..9f9028b95 100644 --- a/update/install_windows.go +++ b/update/install_windows.go @@ -19,8 +19,12 @@ import ( // signed, and a signature that exists but does not verify is refused. const ( - // detachedProcess starts the helper without a console of its own. - detachedProcess = 0x00000008 + // createNoWindow starts the helper with a console of its own that no window + // shows. It must not be DETACHED_PROCESS: Windows PowerShell 5.1 exits at + // once when it is started without a console, so the helper would never run + // the script, and the update would quit the application without replacing + // it or starting it again. + createNoWindow = 0x08000000 // powerShellExecutable is the Windows PowerShell host that runs the helper. powerShellExecutable = "powershell.exe" ) @@ -365,13 +369,13 @@ func startHelper(parentPID int, installer, executable string, args []string) err return nil } -// helperSysProcAttr gives the helper its own process group and no console, so -// it survives the application that is about to quit. +// helperSysProcAttr gives the helper a console of its own that no window shows, +// so it survives the application that is about to quit. It must not create a new +// process group: that disables Ctrl+C for every process in the group, including +// the application the helper starts and the console programs that application +// hosts. func helperSysProcAttr() *syscall.SysProcAttr { - return &syscall.SysProcAttr{ - CreationFlags: detachedProcess | syscall.CREATE_NEW_PROCESS_GROUP, - HideWindow: true, - } + return &syscall.SysProcAttr{CreationFlags: createNoWindow} } // helperCommand is the PowerShell invocation that carries script. diff --git a/update/install_windows_test.go b/update/install_windows_test.go index 47913be0a..a1b3c2b28 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -11,7 +11,6 @@ import ( "path/filepath" "slices" "strings" - "syscall" "testing" "time" "unsafe" @@ -159,19 +158,6 @@ func TestHelperCommand(t *testing.T) { } } -func TestHelperSysProcAttr(t *testing.T) { - attributes := helperSysProcAttr() - if !attributes.HideWindow { - t.Error("helper does not hide its window") - } - if attributes.CreationFlags&detachedProcess == 0 { - t.Error("helper is not detached from the console") - } - if attributes.CreationFlags&syscall.CREATE_NEW_PROCESS_GROUP == 0 { - t.Error("helper does not start in its own process group") - } -} - func TestCheckWritable(t *testing.T) { directory := t.TempDir() if err := checkWritable(directory); err != nil { @@ -307,11 +293,9 @@ func copyWindowsFile(t *testing.T, source, destination string) []byte { func runPayloadHelper(t *testing.T, script string, wantExit int) { t.Helper() - path := filepath.Join(t.TempDir(), "helper.ps1") - if err := os.WriteFile(path, []byte(script), 0o600); err != nil { - t.Fatal(err) - } - command := exec.Command("powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", path) + name, arguments := helperCommand(script) + command := exec.Command(name, arguments...) + command.SysProcAttr = helperSysProcAttr() output, err := command.CombinedOutput() if wantExit == 0 { if err != nil { @@ -373,6 +357,33 @@ func TestPayloadHelperReplacesTheApplication(t *testing.T) { } } +func TestStartPayloadHelperInstallsWithoutOutputPipes(t *testing.T) { + payload, install := t.TempDir(), t.TempDir() + executable := filepath.Join(install, "app.exe") + copyWindowsFile(t, systemExecutable(t, "cmd.exe"), executable) + want := copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, "app.exe")) + if err := startPayloadHelper(999999, payload, install, executable, nil); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(15 * time.Second) + for { + if _, err := os.Stat(payload); os.IsNotExist(err) { + break + } + if time.Now().After(deadline) { + t.Fatal("the detached helper did not finish installing the payload") + } + time.Sleep(50 * time.Millisecond) + } + got, err := os.ReadFile(executable) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatal("the detached helper did not install the new executable") + } +} + func TestPayloadHelperReplacesARunningExecutable(t *testing.T) { payload := t.TempDir() install := t.TempDir() From 71d93128c9698f2eca63b6cd8df54c75697705f9 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:26:37 +0800 Subject: [PATCH 09/13] test(darwin): serialize posted-drain assertions on the main queue --- internal/platform/darwin/post_darwin_test.go | 50 +++++++++++++------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/internal/platform/darwin/post_darwin_test.go b/internal/platform/darwin/post_darwin_test.go index d21847b73..27a9283ab 100644 --- a/internal/platform/darwin/post_darwin_test.go +++ b/internal/platform/darwin/post_darwin_test.go @@ -2,31 +2,49 @@ package darwin -import "testing" +import ( + "testing" + "time" +) + +func postedDrainResult(t *testing.T, run func() []int) []int { + t.Helper() + result := make(chan []int, 1) + // TestMain serves the native queue. Keep the manual drain on that same + // thread, so a scheduled native drain cannot consume these callbacks first. + Post(func() { result <- run() }) + select { + case seen := <-result: + return seen + case <-time.After(5 * time.Second): + t.Fatal("posted main-thread drain did not complete") + return nil + } +} func TestPostedFunctionsDrainInOrder(t *testing.T) { - postQueue.Lock() - postQueue.pending = nil - postQueue.Unlock() - var seen []int - Post(func() { seen = append(seen, 1) }) - Post(func() { seen = append(seen, 2) }) - vivaApplicationDrain() + seen := postedDrainResult(t, func() []int { + var seen []int + Post(func() { seen = append(seen, 1) }) + Post(func() { seen = append(seen, 2) }) + vivaApplicationDrain() + return seen + }) if len(seen) != 2 || seen[0] != 1 || seen[1] != 2 { t.Fatalf("seen = %v, want [1 2]", seen) } } func TestAFunctionPostedWhileDrainingRunsInTheSameDrain(t *testing.T) { - postQueue.Lock() - postQueue.pending = nil - postQueue.Unlock() - var seen []int - Post(func() { - seen = append(seen, 1) - Post(func() { seen = append(seen, 2) }) + seen := postedDrainResult(t, func() []int { + var seen []int + Post(func() { + seen = append(seen, 1) + Post(func() { seen = append(seen, 2) }) + }) + vivaApplicationDrain() + return seen }) - vivaApplicationDrain() if len(seen) != 2 || seen[0] != 1 || seen[1] != 2 { t.Fatalf("seen = %v, want [1 2]", seen) } From 93552320e2ad04fd6a40f11c4c54eb8e80bfe968 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:26:50 +0800 Subject: [PATCH 10/13] fix(linux): publish accessibility on the first window and resize --- .github/workflows/text-input.yml | 16 +- internal/platform/contract.go | 8 +- internal/platform/linux/atspi_linux.go | 16 +- .../platform/linux/atspi_native_linux_test.go | 138 ++++++++++++++ .../linux/atspi_resize_native_linux_test.go | 178 ++++++++++++++++++ internal/platform/linux/window_linux.go | 3 + 6 files changed, 344 insertions(+), 15 deletions(-) create mode 100644 internal/platform/linux/atspi_native_linux_test.go create mode 100644 internal/platform/linux/atspi_resize_native_linux_test.go diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index 2d21a3b37..80ce917ed 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -104,12 +104,22 @@ jobs: git rev-parse HEAD go version go test ./internal/platform/windows -run '^TestColumnClipboardNative' -count=1 -v -timeout=90s - - name: GTK native probe dependencies + - name: Linux native probe dependencies if: runner.os == 'Linux' run: | sudo apt-get update - sudo apt-get install -y --no-install-recommends libgtk-3-0t64 xvfb xauth dbus-x11 - dpkg-query -W libgtk-3-0t64 xvfb xauth dbus-x11 + sudo apt-get install -y --no-install-recommends libgtk-3-0t64 xvfb xauth dbus-x11 at-spi2-core + dpkg-query -W libgtk-3-0t64 xvfb xauth dbus-x11 at-spi2-core + - name: AT-SPI native lifecycle + if: runner.os == 'Linux' + run: | + binary="$RUNNER_TEMP/viva-atspi.test" + profile="$(mktemp -d "$RUNNER_TEMP/viva-atspi.XXXXXX")" + trap 'rm -rf "$profile" "$binary"' EXIT + go test -c -o "$binary" ./internal/platform/linux + mkdir -p "$profile"/{home,config,cache,data,runtime} + chmod 0700 "$profile/runtime" + xvfb-run -a env HOME="$profile/home" XDG_CONFIG_HOME="$profile/config" XDG_CACHE_HOME="$profile/cache" XDG_DATA_HOME="$profile/data" XDG_RUNTIME_DIR="$profile/runtime" VIVA_ATSPI_NATIVE_ROOT="$profile" VIVA_ATSPI_NATIVE=1 NO_AT_BRIDGE=1 dbus-run-session -- "$binary" -test.run='^TestAtspiNative(FirstWindowPolling|ResizePublishesFrames)$' -test.count=1 -test.v -test.timeout=45s - name: GTK native composition lifecycle if: runner.os == 'Linux' run: dbus-run-session -- xvfb-run -a env VIVA_GTK_IME_NATIVE=1 GTK_IM_MODULE=gtk-im-context-simple GDK_BACKEND=x11 NO_AT_BRIDGE=1 G_DEBUG=fatal-criticals go test -tags vivagtk ./internal/platform/linux -run '^(TestGTKNativeComposition|TestGTKNativeTentative.*|TestGTKNativeSameTargetOwnership)$' -count=1 -v -timeout=90s diff --git a/internal/platform/contract.go b/internal/platform/contract.go index a8b6fac94..2beef8ef8 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -558,9 +558,11 @@ type AccessibilitySelection struct { // Frame is the complete renderer state for one repaint. type Frame struct { - Update render.Update - Rectangles []render.Rectangle - TextLabels []TextLabel + Update render.Update + Rectangles []render.Rectangle + TextLabels []TextLabel + // Accessibility, when non-nil, replaces the window's accessibility tree; an empty + // non-nil slice clears it. Nil leaves the current tree as it is. Accessibility []AccessibilityNode TextInput TextInputUpdate // NativeViews, when non-nil, replaces the places the window shows its native views (see diff --git a/internal/platform/linux/atspi_linux.go b/internal/platform/linux/atspi_linux.go index a3b1fece3..46f8c7155 100644 --- a/internal/platform/linux/atspi_linux.go +++ b/internal/platform/linux/atspi_linux.go @@ -96,17 +96,20 @@ func (host *atspiHost) engaged() bool { } // atspiOpened is called when a window has opened. The first one makes the -// application ask the desktop whether accessibility is on. It returns the host. -func atspiOpened(host *atspiHost, owner atspiOwner, target atspiShell) *atspiHost { +// application ask the desktop whether accessibility is on. +func (services *desktopServices) atspiOpened(target atspiShell) { if os.Getenv("VIVA_ACCESSIBILITY") == "0" { - return host + return } + host, owner := services.atspi, services.host first := false if host == nil { host, first = &atspiHost{ windows: make(map[atspiShell]*atspiWindow), latest: make(map[atspiShell][]platform.AccessibilityNode), }, true + // The loop reads its services when rebuilding the descriptor set. + services.atspi = host } host.latest[target] = target.atspiConfig().Accessibility if first { @@ -114,13 +117,12 @@ func atspiOpened(host *atspiHost, owner atspiOwner, target atspiShell) *atspiHos } if !host.engaged() { delete(host.latest, target) - return host + return } if host.bridge != nil && host.windows[target] == nil { host.attach(owner, target) } owner.rebuildPoll() - return host } // probe asks the session bus about accessibility and connects, or waits. @@ -300,10 +302,6 @@ func (application *linuxApplication) atspiShells() []atspiShell { return targets } -func (services *desktopServices) atspiOpened(shell atspiShell) { - services.atspi = atspiOpened(services.atspi, services.host, shell) -} - func (services *desktopServices) atspiFrame(shell atspiShell, nodes []platform.AccessibilityNode) { services.atspi.frame(shell, nodes) } diff --git a/internal/platform/linux/atspi_native_linux_test.go b/internal/platform/linux/atspi_native_linux_test.go new file mode 100644 index 000000000..2e936076b --- /dev/null +++ b/internal/platform/linux/atspi_native_linux_test.go @@ -0,0 +1,138 @@ +package linux + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/vivaui/viva/internal/dbus" + "github.com/vivaui/viva/internal/platform" +) + +type atspiInitialPollHost struct { + fakeBusHost + services *desktopServices + descriptors []int +} + +func (host *atspiInitialPollHost) rebuildPoll() { + host.descriptors = append(host.descriptors, host.services.atspi.fd()) +} + +type atspiInitialPollShell struct{ config platform.Config } + +// restoreA11yStatus puts the session's org.a11y.Status values back when the +// test ends. These tests switch accessibility on; an opt-in run on a developer +// session must not leave the desktop's settings changed. +func restoreA11yStatus(t *testing.T, connection *dbus.Conn, names ...string) { + t.Helper() + values := make(map[string]bool, len(names)) + for _, name := range names { + var request dbus.Encoder + request.String(a11yStatus) + request.String(name) + reply, err := connection.Call(a11yBusName, a11yBusPath, dbusProperties, dbusPropertiesGet, "ss", request.Bytes()) + if err != nil { + t.Fatalf("read %s: %v", name, err) + } + args := reply.Args() + if args.Signature() != "b" { + t.Fatalf("read %s: signature %q", name, args.Signature()) + } + values[name] = args.Bool() + } + t.Cleanup(func() { + for _, name := range names { + var request dbus.Encoder + request.String(a11yStatus) + request.String(name) + request.Variant("b") + request.Bool(values[name]) + if _, err := connection.Call(a11yBusName, a11yBusPath, dbusProperties, "Set", "ssv", request.Bytes()); err != nil { + t.Errorf("restore %s: %v", name, err) + } + } + }) +} + +func (shell *atspiInitialPollShell) atspiConfig() *platform.Config { return &shell.config } +func (*atspiInitialPollShell) atspiGeometry() (int, int, float32) { return 0, 0, 1 } +func (*atspiInitialPollShell) atspiPresent(platform.Frame) error { return nil } + +// The first window must publish the bridge or watcher before its loop rebuilds +// the descriptor set. A live connection which nobody polls cannot serve readers +// or notice that accessibility was enabled later. +func TestAtspiNativeFirstWindowPolling(t *testing.T) { + if os.Getenv("VIVA_ATSPI_NATIVE") != "1" { + t.Skip("set VIVA_ATSPI_NATIVE=1 with a private AT-SPI session bus") + } + root := os.Getenv("VIVA_ATSPI_NATIVE_ROOT") + if root == "" || !filepath.IsAbs(root) || !strings.HasPrefix(os.Getenv("XDG_CONFIG_HOME"), root+string(os.PathSeparator)) { + t.Fatal("native accessibility tests require a private HOME/XDG profile") + } + t.Setenv("VIVA_ACCESSIBILITY", "") + connection, err := dbus.DialSession() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { connection.Close() }) + restoreA11yStatus(t, connection, "IsEnabled", "ScreenReaderEnabled") + setStatus := func(name string, value bool) { + t.Helper() + var request dbus.Encoder + request.String(a11yStatus) + request.String(name) + request.Variant("b") + request.Bool(value) + if _, err := connection.Call(a11yBusName, a11yBusPath, dbusProperties, "Set", "ssv", request.Bytes()); err != nil { + t.Fatal(err) + } + } + for _, enabled := range []bool{true, false} { + name := "watcher" + if enabled { + name = "bridge" + } + t.Run(name, func(t *testing.T) { + setStatus("ScreenReaderEnabled", false) + setStatus("IsEnabled", enabled) + services := &desktopServices{} + owner := &atspiInitialPollHost{services: services} + services.host = owner + t.Cleanup(services.atspiClose) + services.atspiOpened(&atspiInitialPollShell{config: platform.Config{Title: "First accessibility window"}}) + if services.atspi == nil || services.atspi.fd() < 0 { + t.Fatal("the real private accessibility connection did not open") + } + if enabled && services.atspi.bridge == nil || !enabled && services.atspi.watcher == nil { + t.Fatal("the native connection did not use the requested bridge/watcher mode") + } + fd := services.atspi.fd() + if len(owner.descriptors) == 0 || owner.descriptors[len(owner.descriptors)-1] != fd { + t.Fatalf("first window opened descriptor %d but the loop observed %v", fd, owner.descriptors) + } + }) + } + t.Run("forced off", func(t *testing.T) { + t.Setenv("VIVA_ACCESSIBILITY", "0") + services := &desktopServices{} + owner := &atspiInitialPollHost{services: services} + services.host = owner + services.atspiOpened(&atspiInitialPollShell{}) + if services.atspi != nil || len(owner.descriptors) != 0 { + t.Fatal("forced-off accessibility created a host or changed polling") + } + }) + t.Run("no service", func(t *testing.T) { + t.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path="+filepath.Join(root, "absent-bus")) + services := &desktopServices{} + owner := &atspiInitialPollHost{services: services} + services.host = owner + t.Cleanup(services.atspiClose) + services.atspiOpened(&atspiInitialPollShell{}) + if services.atspi.fd() != -1 || len(owner.descriptors) != 0 { + t.Fatal("an unavailable accessibility service left a polled descriptor") + } + }) +} diff --git a/internal/platform/linux/atspi_resize_native_linux_test.go b/internal/platform/linux/atspi_resize_native_linux_test.go new file mode 100644 index 000000000..42621011f --- /dev/null +++ b/internal/platform/linux/atspi_resize_native_linux_test.go @@ -0,0 +1,178 @@ +package linux + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/dbus" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" +) + +func TestAtspiNativeResizePublishesFrames(t *testing.T) { + if os.Getenv("VIVA_ATSPI_NATIVE") != "1" { + t.Skip("set VIVA_ATSPI_NATIVE=1 with a private X11/AT-SPI session") + } + root := os.Getenv("VIVA_ATSPI_NATIVE_ROOT") + if root == "" || !filepath.IsAbs(root) || !strings.HasPrefix(os.Getenv("HOME"), root+string(os.PathSeparator)) || !strings.HasPrefix(os.Getenv("XDG_CONFIG_HOME"), root+string(os.PathSeparator)) { + t.Fatal("native accessibility tests require a private HOME/XDG profile") + } + t.Setenv("VIVA_ACCESSIBILITY", "") + t.Setenv("VIVA_SOFTWARE_RENDERING", "1") + t.Setenv("VIVA_SCALE", "1") + session, err := dbus.DialSession() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { session.Close() }) + restoreA11yStatus(t, session, "IsEnabled") + var status dbus.Encoder + status.String(a11yStatus) + status.String("IsEnabled") + status.Variant("b") + status.Bool(true) + if _, err := session.Call(a11yBusName, a11yBusPath, dbusProperties, "Set", "ssv", status.Bytes()); err != nil { + t.Fatal(err) + } + address, err := atspiAddress(session) + if err != nil { + t.Fatal(err) + } + for _, test := range []struct { + name string + children int + extent [4]int32 + }{ + {"changed", 1, [4]int32{0, 0, 640, 400}}, + {"nil preserves", 1, [4]int32{0, 0, 1280, 800}}, + {"empty clears", 0, [4]int32{}}, + } { + t.Run(test.name, func(t *testing.T) { + resized := make(chan platform.Size, 1) + result := make(chan error, 1) + config := platform.Config{ + Title: "AT-SPI resize", Width: 1280, Height: 800, WindowMode: platform.WindowFrameless, + ClearColor: platform.Color{Alpha: 1}, + Rectangles: []render.Rectangle{{Kind: scene.KindRectangle, Bounds: scene.Rect{Width: 1280, Height: 800}, Color: scene.Color{Green: .5, Alpha: 1}}}, + Accessibility: []platform.AccessibilityNode{{ID: gfx.Item(1), Role: platform.A11yRoleGroup, Label: "Content", Width: 1280, Height: 800}}, + } + config.OnResize = func(size platform.Size) (platform.Frame, error) { + if size.Width != 640 || size.Height != 400 { + return platform.Frame{}, nil + } + select { + case resized <- size: + default: + } + switch test.name { + case "nil preserves": + return platform.Frame{}, nil + case "empty clears": + return platform.Frame{Accessibility: []platform.AccessibilityNode{}}, nil + default: + return platform.Frame{Accessibility: []platform.AccessibilityNode{{ID: gfx.Item(1), Role: platform.A11yRoleGroup, Label: "Content", Width: size.Width, Height: size.Height}}}, nil + } + } + err := RunApplication(func(application platform.Application) error { + control, err := application.OpenWindow(config) + if err != nil { + return err + } + state := control.(*nativeWindow).state + if _, ok := state.renderer.(*cpuWindowRenderer); !ok { + return fmt.Errorf("native regression requires the CPU window renderer") + } + host := state.application.atspi + if host == nil || host.bridge == nil || host.windows[state] == nil { + return fmt.Errorf("the real window did not join the private accessibility bridge") + } + name, frame := host.bridge.unique, host.bridge.framePath(host.windows[state]) + go func() { + result <- atspiProbeResize(address, name, frame, control.(platform.WindowSizer), resized, test.children, test.extent) + application.Quit() + }() + return nil + }) + if err != nil { + t.Fatal(err) + } + if err := <-result; err != nil { + t.Fatal(err) + } + }) + } +} + +func atspiProbeResize(address, name, frame string, window platform.WindowSizer, resized <-chan platform.Size, children int, extent [4]int32) error { + client, err := dbus.Dial(address) + if err != nil { + return err + } + defer client.Close() + initial, err := atspiNativeChildren(client, name, frame) + if err != nil { + return err + } + if len(initial) != 1 { + return fmt.Errorf("initial accessibility children = %d; want 1", len(initial)) + } + if got, err := atspiNativeExtent(client, initial[0]); err != nil || got != ([4]int32{0, 0, 1280, 800}) { + return fmt.Errorf("initial accessibility extent = %v/%v; want [0 0 1280 800]", got, err) + } + if err := window.SetSize(640, 400); err != nil { + return err + } + select { + case <-resized: + case <-time.After(5 * time.Second): + return fmt.Errorf("the actual X11 resize did not reach OnResize") + } + next, err := atspiNativeChildren(client, name, frame) + if err != nil { + return err + } + if len(next) != children { + return fmt.Errorf("resized accessibility children = %d; want %d", len(next), children) + } + if children != 0 { + if got, err := atspiNativeExtent(client, next[0]); err != nil || got != extent { + return fmt.Errorf("resized accessibility extent = %v/%v; want %v", got, err, extent) + } + } + return nil +} + +func atspiNativeChildren(client *dbus.Conn, name, frame string) ([]atspiRef, error) { + reply, err := client.Call(name, frame, atspiIfaceAccessible, "GetChildren", "", nil) + if err != nil { + return nil, err + } + defer reply.CloseFDs() + args := reply.Args() + end := args.ArrayLength(8) + var children []atspiRef + for args.Pos() < end && args.Err() == nil { + children = append(children, readRef(args)) + } + return children, args.Err() +} + +func atspiNativeExtent(client *dbus.Conn, node atspiRef) ([4]int32, error) { + var request dbus.Encoder + request.Uint32(1) // window coordinates + reply, err := client.Call(node.Name, node.Path, atspiIfaceComponent, "GetExtents", "u", request.Bytes()) + if err != nil { + return [4]int32{}, err + } + defer reply.CloseFDs() + args := reply.Args() + args.Align(8) + extent := [4]int32{args.Int32(), args.Int32(), args.Int32(), args.Int32()} + return extent, args.Err() +} diff --git a/internal/platform/linux/window_linux.go b/internal/platform/linux/window_linux.go index 9dd1c8b1f..1a0eede9e 100644 --- a/internal/platform/linux/window_linux.go +++ b/internal/platform/linux/window_linux.go @@ -1135,6 +1135,9 @@ func (state *linuxWindowState) resized() error { if config.OnResize != nil { frame, err := config.OnResize(win.logicalSize()) if err == nil { + if frame.Accessibility != nil { + state.application.atspiFrame(state, frame.Accessibility) + } var merged platform.Frame var dirty bool merged, dirty, err = state.text.prepare(frame) From 9260f72ef95d80d75dba9c5e0c5c927531fd137e Mon Sep 17 00:00:00 2001 From: szmcdull Date: Mon, 16 Nov 2026 14:27:04 +0800 Subject: [PATCH 11/13] fix(linux): maximize both axes from the title bar --- .github/workflows/ci.yml | 4 ++ .../platform/linux/window_controls_linux.go | 13 ++++++- .../linux/window_controls_linux_test.go | 38 +++++++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 65d8418b3..d435ec192 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -122,6 +122,10 @@ jobs: run: | go vet -tags vivagtk ./app ./internal/platform/linux go test -tags vivagtk ./internal/platform/linux -run '^TestGTK(WaylandAlwaysOnTopReportsUnsupported|ClipboardFileWriteReportsUnsupportedWithoutASetter)$' -count=1 + # The Linux package is not part of the sharded run (it drives X11), so the + # titlebar contracts that do not need a server name their tests here. + - name: Titlebar and window contracts + run: go test ./internal/platform/linux -run '^TestMaximizeButtonSetsBothDirections$' -count=1 -v - name: Native X11 global shortcut env: VIVA_NATIVE_GLOBAL_SHORTCUT_TEST: '1' diff --git a/internal/platform/linux/window_controls_linux.go b/internal/platform/linux/window_controls_linux.go index 632723fc0..a3e0c9cdf 100644 --- a/internal/platform/linux/window_controls_linux.go +++ b/internal/platform/linux/window_controls_linux.go @@ -25,7 +25,8 @@ const ( // the eight edges are 0 to 7, clockwise from the top left (moveResizeDirection). moveResizeMove = 8 - netWMStateToggle = 2 + netWMStateRemove = 0 + netWMStateAdd = 1 iconicState = 3 sourceApp = 1 @@ -151,10 +152,18 @@ func (win *window) minimize() { win.sendToRoot(win.frame.changeStateAtom, [5]uint32{iconicState}) } +// toggleMaximize asks for both directions together. _NET_WM_STATE_TOGGLE flips +// each atom on its own, so a window already maximized on one axis would end up +// maximized on the other axis only. Adding both atoms maximizes; removing both +// restores. func (win *window) toggleMaximize() { win.frame.maximizePending = true win.frame.maximizeTarget = !win.frame.maximized - win.sendToRoot(win.frame.stateAtom, [5]uint32{netWMStateToggle, win.frame.maximizedVertical, win.frame.maximizedHorizontal, sourceApp}) + action := uint32(netWMStateRemove) + if win.frame.maximizeTarget { + action = netWMStateAdd + } + win.sendToRoot(win.frame.stateAtom, [5]uint32{action, win.frame.maximizedVertical, win.frame.maximizedHorizontal, sourceApp}) } func (win *window) setMaximized(maximized bool) bool { diff --git a/internal/platform/linux/window_controls_linux_test.go b/internal/platform/linux/window_controls_linux_test.go index 611e92c79..bbf5e0682 100644 --- a/internal/platform/linux/window_controls_linux_test.go +++ b/internal/platform/linux/window_controls_linux_test.go @@ -1,7 +1,9 @@ package linux import ( + "encoding/binary" "testing" + "unsafe" "github.com/vivaui/viva/internal/platform" ) @@ -19,6 +21,42 @@ func TestEdgesMapToXMoveResizeDirections(t *testing.T) { } } +func TestMaximizeButtonSetsBothDirections(t *testing.T) { + var words [5]uint32 + win := &window{ + api: &xcbAPI{ + sendEvent: func(_ uintptr, _ uint8, _, _ uint32, data *byte) xcbVoidCookie { + message := (*xcbClientEvent)(unsafe.Pointer(data)) + for index := range words { + words[index] = binary.LittleEndian.Uint32(message.Data[index*4:]) + } + return xcbVoidCookie{} + }, + flush: func(uintptr) int32 { return 0 }, + }, + screen: &xcbScreen{Root: 1}, + frame: frameState{ + stateAtom: 10, + maximizedVertical: 20, + maximizedHorizontal: 30, + }, + } + + // EWMH 5.7: data.l[0] is the action (0 remove, 1 add), l[1] and l[2] are + // the properties it applies to, l[3] is the source indication (1 for a + // normal application). The literals are the protocol's, not this package's. + win.toggleMaximize() + if words != [5]uint32{1, 20, 30, 1, 0} { + t.Fatalf("maximize message = %v, want both directions added", words) + } + + win.frame.maximized = true + win.toggleMaximize() + if words != [5]uint32{0, 20, 30, 1, 0} { + t.Fatalf("restore message = %v, want both directions removed", words) + } +} + func TestADoubleClickNeedsTwoClosePressesInTime(t *testing.T) { var win window press := func(time uint32, x, y int16) bool { From 47dabd4bb9f17ad1708e6d87e8169d240bdc4f44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=A0=B9=E6=AD=A3=E8=8B=97=E7=BA=A2=E7=9A=84=E7=A4=BE?= =?UTF-8?q?=E4=BC=9A=E4=B8=BB=E4=B9=89=E6=8E=A5=E7=8F=AD=E4=BA=BA?= <41796094+yangziyu1230@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:27:23 +0800 Subject: [PATCH 12/13] feat(fonts): choose interface and fixed-pitch weights on Windows --- .github/workflows/ci.yml | 2 +- app/font_weights.go | 64 ++++++++ app/fonts.go | 35 ++-- app/system_darwin.go | 4 + app/system_js.go | 1 + app/system_linux.go | 4 + app/system_unsupported.go | 1 + app/system_windows.go | 5 +- gfx/text_engine.go | 37 ++++- .../platform/windows/direct_gdi_windows.go | 2 +- .../windows/direct_gdi_windows_test.go | 26 +++ .../platform/windows/direct_ink_windows.go | 6 +- internal/platform/windows/direct_windows.go | 2 +- .../platform/windows/font_weights_windows.go | 60 +++++++ .../windows/font_weights_windows_test.go | 112 +++++++++++++ .../platform/windows/fonts_direct_windows.go | 153 ++++++++++++++++++ .../windows/fonts_direct_windows_test.go | 65 ++++++++ internal/platform/windows/fonts_windows.go | 24 ++- .../windows/ink_overflow_windows_test.go | 2 +- internal/platform/windows/text_windows.go | 74 ++++++++- .../platform/windows/textengine_windows.go | 48 +++++- 21 files changed, 685 insertions(+), 42 deletions(-) create mode 100644 app/font_weights.go create mode 100644 internal/platform/windows/font_weights_windows.go create mode 100644 internal/platform/windows/font_weights_windows_test.go create mode 100644 internal/platform/windows/fonts_direct_windows.go create mode 100644 internal/platform/windows/fonts_direct_windows_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d435ec192..53b85bed2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -293,7 +293,7 @@ jobs: # native structure ABI tests are here for the same reason: they build only # on Windows. - name: Material contracts and controls (WARP) - run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI)' -count=1 -v + run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|MonoWeights|InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI)' -count=1 -v - name: Terminal keyboard routing run: go test ./internal/platform/windows -run '^TestATerminalGetsEditingKeysAndChordsAsRawKeys$' -count=1 -v - name: Native Windows global shortcut diff --git a/app/font_weights.go b/app/font_weights.go new file mode 100644 index 000000000..a4f7346b6 --- /dev/null +++ b/app/font_weights.go @@ -0,0 +1,64 @@ +package app + +import "github.com/vivaui/viva/gfx" + +// The weights of the text Viva draws, which the application may choose where the +// platform's engine has the choice: which installed weight of a family the main +// text and the bold text are drawn at, for the interface's proportional text and +// for the fixed-pitch text apart. + +// SetInterfaceFont is SetInterfaceFontFamily with the two weights the interface's +// text is drawn at: main for regular and medium text, bold for semibold and bold. +// The weights are DWRITE_FONT_WEIGHT values — 300 Light, 400 Regular, 500 Medium, +// 600 Semibold, 700 Bold and so on, as FontWeights lists a family's — and 0 keeps +// the platform's own (400 and 700). A weight the family is not installed with is +// drawn through the platform's nearest match, so naming one never fails. +// +// Weights are followed where the platform's engine has the choice (Windows today); +// an engine without it draws the family at its own weights, and FontWeights lists +// nothing there. Set either band to the weight already in use and nothing changes. +func SetInterfaceFont(family string, main, bold int) bool { + engine := PlatformTextEngine() + aware, ok := engine.(gfx.FontFamilyAware) + if !ok { + return false + } + aware.SetFontFamily(interfaceFamilyName(family)) + if weights, ok := engine.(gfx.FontWeightAware); ok { + weights.SetFontWeights(main, bold) + } + return true +} + +// FontWeights lists the weights family is installed with, ascending, as +// DWRITE_FONT_WEIGHT values (300 Light, 400 Regular, 500 Medium, 600 Semibold, +// 700 Bold, 800 ExtraBold, 900 Black …): the choices SetInterfaceFont takes for +// the main and the bold text of that family. The list is the family's own, so a +// family installed in one weight lists one number, and a family the system does +// not have lists none. +// +// It is empty where the platform cannot report a family's weights (macOS and +// Linux today, and every target that cannot enumerate fonts), where an +// application offers the family's default weights instead. The list is read from +// the system on every call, so it is for a settings page, not for painting. +func FontWeights(family string) []int { return nativeFontWeights(family) } + +// SetMonospaceFontWeights names the weights the fixed-pitch text that Viva draws +// is drawn at: the terminal's and the code blocks', whose face the application +// chooses through gfx.MonoFace. main is the regular text's weight, bold the bold +// runs' (SGR bold, WeightBold), as DWRITE_FONT_WEIGHT values, and 0 keeps the +// platform's own (400 and 700). The cell the fixed-pitch text is laid out on +// follows the weights, as the face's own advance does. +// +// It reports false where the platform's engine has no such choice (macOS and +// Linux today); the call has no effect there, as SetInterfaceFont's weights have +// none. The change applies to everything shaped afterwards, and the application +// asks for the next paint. +func SetMonospaceFontWeights(main, bold int) bool { + weights, ok := PlatformTextEngine().(gfx.MonoWeightAware) + if !ok { + return false + } + weights.SetMonoWeights(main, bold) + return true +} diff --git a/app/fonts.go b/app/fonts.go index 6fa302b65..9ef674724 100644 --- a/app/fonts.go +++ b/app/fonts.go @@ -31,12 +31,14 @@ func MonospaceFamilies() []string { return nativeMonospaceFamilies() } // The list is what the system reports, symbol and icon families included // (Wingdings, Apple Symbols): no platform marks them in a way all three agree // on, so a picker that wants only families fit for reading prose chooses which -// to leave out. On Windows a family whose name fills the 31 characters GDI -// reports (the system cuts a longer one) is left out, since the cut name would -// name no family. The list is read from the system on every call and can take -// tens of milliseconds, so it is for a settings page, not for painting. It is -// empty where the platform cannot enumerate fonts (a browser, an unsupported -// target). +// to leave out. Every name is one the platform's own text engine resolves: on +// Windows the families come from DirectWrite, not from GDI's typeface names, +// which name a family's styles ("Maple Mono Light") and draw in the fallback +// font when a text format is made from them. A style of a family is chosen by +// the family's name and the weight the text is drawn at, not by a name of its +// own. The list is read from the system on every call and can take tens of +// milliseconds, so it is for a settings page, not for painting. It is empty +// where the platform cannot enumerate fonts (a browser, an unsupported target). func FontFamilies() []string { return nativeFontFamilies() } // RegisterFont makes the TrueType or OpenType font in data (a .ttf, .otf or .ttc, as an @@ -69,12 +71,15 @@ const maxInterfaceFamilyName = 96 // SetInterfaceFontFamily names the family the proportional text that Viva draws // itself is shaped in — labels, text fields, the menus, popups and dialogs of the // application's own windows, everything but the terminal's monospace face — or -// "" for the platform's own interface font. Text the operating system draws -// (native menus, status-item menus, file dialogs, alerts) keeps the system font. -// A name that is too long (96 bytes) or holds a control character is taken as "". -// It reports false where the platform's engine cannot follow a family (an -// unsupported target); the call has no effect there, and FontFamilies is empty -// too. The Web target follows the family through its document text engine. +// "" for the platform's own interface font, and draws it at the platform's own +// weights. SetInterfaceFont also chooses those weights. +// +// Text the operating system draws (native menus, status-item menus, file dialogs, +// alerts) keeps the system font. A name that is too long (96 bytes) or holds a +// control character is taken as "". It reports false where the platform's engine +// cannot follow a family (an unsupported target); the call has no effect there, +// and FontFamilies is empty too. The Web target follows the family through its +// document text engine. // // The change applies to everything shaped afterwards; what was shaped before is // forgotten, and the next paint of a window lays out and draws its text in the @@ -83,11 +88,7 @@ const maxInterfaceFamilyName = 96 // process's: every window follows it. A name the system has no family for is // drawn in the system font. func SetInterfaceFontFamily(family string) bool { - if aware, ok := PlatformTextEngine().(gfx.FontFamilyAware); ok { - aware.SetFontFamily(interfaceFamilyName(family)) - return true - } - return false + return SetInterfaceFont(family, 0, 0) } // SetFontThickening draws the text Viva itself rasterizes — labels, text fields, the terminal diff --git a/app/system_darwin.go b/app/system_darwin.go index f5732795f..af9f33c3a 100644 --- a/app/system_darwin.go +++ b/app/system_darwin.go @@ -143,6 +143,10 @@ func nativeShowFatalError(title, message string) { darwinplatform.ShowFatalError func nativeMonospaceFamilies() []string { return darwinplatform.MonospaceFamilies() } func nativeFontFamilies() []string { return darwinplatform.FontFamilies() } +// nativeFontWeights is empty: the darwin engine follows a family but not the weights +// it is drawn at. +func nativeFontWeights(string) []int { return nil } + func nativeAppearance() Appearance { if darwinplatform.DarkAppearance() { return AppearanceDark diff --git a/app/system_js.go b/app/system_js.go index 563dd8967..212a75e86 100644 --- a/app/system_js.go +++ b/app/system_js.go @@ -113,6 +113,7 @@ func nativeShowFatalError(string, string) {} func nativeMonospaceFamilies() []string { return nil } func nativeFontFamilies() []string { return nil } +func nativeFontWeights(string) []int { return nil } func nativeAppearance() Appearance { return appearanceOf(webplatform.DarkAppearance()) } diff --git a/app/system_linux.go b/app/system_linux.go index baa0dd927..76012fcd6 100644 --- a/app/system_linux.go +++ b/app/system_linux.go @@ -166,6 +166,10 @@ func nativeShowFatalError(title, message string) { linuxplatform.ShowFatalError( func nativeMonospaceFamilies() []string { return linuxplatform.MonospaceFamilies() } func nativeFontFamilies() []string { return linuxplatform.FontFamilies() } +// nativeFontWeights is empty: the linux engine follows a family but not the weights it +// is drawn at. +func nativeFontWeights(string) []int { return nil } + func nativeAppearance() Appearance { return appearanceOf(linuxplatform.DarkAppearance()) } func nativeWatchAppearance() {} // the event loop listens while an observer is set (platform.DesktopWatched) diff --git a/app/system_unsupported.go b/app/system_unsupported.go index c3312f707..28bfb0bc3 100644 --- a/app/system_unsupported.go +++ b/app/system_unsupported.go @@ -40,6 +40,7 @@ func nativeShowFatalError(string, string) {} func nativeMonospaceFamilies() []string { return nil } func nativeFontFamilies() []string { return nil } +func nativeFontWeights(string) []int { return nil } func nativeAppearance() Appearance { return AppearanceUnknown } diff --git a/app/system_windows.go b/app/system_windows.go index 54c6cb67f..ccfb273ea 100644 --- a/app/system_windows.go +++ b/app/system_windows.go @@ -122,8 +122,9 @@ func nativeEnableCrashDumps(relativeDir string) (string, error) { func nativeShowFatalError(title, message string) { windowsplatform.ShowFatalError(title, message) } -func nativeMonospaceFamilies() []string { return windowsplatform.MonospaceFamilies() } -func nativeFontFamilies() []string { return windowsplatform.FontFamilies() } +func nativeMonospaceFamilies() []string { return windowsplatform.MonospaceFamilies() } +func nativeFontFamilies() []string { return windowsplatform.FontFamilies() } +func nativeFontWeights(family string) []int { return windowsplatform.FontWeights(family) } func nativeAppearance() Appearance { return appearanceOf(windowsplatform.DarkAppearance()) } diff --git a/gfx/text_engine.go b/gfx/text_engine.go index 194eac830..e84556419 100644 --- a/gfx/text_engine.go +++ b/gfx/text_engine.go @@ -135,14 +135,41 @@ type FontFamilyAware interface { // FontGeneration counts the changes after which the same line shapes // differently: it moves on every SetFontFamily that changed the family, // when the system's own fonts changed under the engine, and, on an engine - // that has the weight's choice (FontThickener), on every SetFontThickening - // that changed it. What the canvas or a renderer remembers of shaped text - // (a cut line, a rasterized label) is stale once it differs from the - // generation it was made at. Wrapping around is harmless: only equality is - // ever asked. + // that has the weight's choice (FontThickener, FontWeightAware, + // MonoWeightAware), on every SetFontThickening, SetFontWeights or + // SetMonoWeights that changed it. What the canvas or a renderer remembers + // of shaped text (a cut line, a rasterized label) is stale once it differs + // from the generation it was made at. Wrapping around is harmless: only + // equality is ever asked. FontGeneration() uint32 } +// FontWeightAware is an optional FontFamilyAware capability: an engine that can also +// name which installed weights the interface's text is drawn at. A family ships as +// several weights (Thin … Black), and which of them the main text and the bold text +// use is the application's choice; a family without the engine's own weights (400 for +// regular, 700 for bold) is drawn at them through the platform's nearest match. +type FontWeightAware interface { + // SetFontWeights names the weight the main text and the bold text are drawn at, as + // DWRITE_FONT_WEIGHT values (300 Light, 400 Regular, 500 Medium, 600 Semibold, + // 700 Bold …), or 0 for the platform's own. Main covers regular and medium text, + // bold covers semibold and bold. What was shaped at another weight is forgotten, + // and FontGeneration moves, as it does for a family change. + SetFontWeights(main, bold int) +} + +// MonoWeightAware is an optional TextEngine capability: the weights the fixed-pitch +// text — a terminal's face, drawn through a MonoFace — is drawn at, named apart from +// the interface's because a terminal's family and weights are its own choice. The +// weights also pick the face whose cell the fixed-pitch text is laid out on. +type MonoWeightAware interface { + // SetMonoWeights names the weight the regular fixed-pitch text and the bold + // fixed-pitch text are drawn at, as FontWeightAware does, or 0 for the platform's + // own. What was shaped at another weight is forgotten, FontGeneration moves, and + // the cells the canvas measured are measured again. + SetMonoWeights(main, bold int) +} + // FontThickener is an optional TextEngine capability that draws the glyphs it // rasterizes with a thicker stroke, as the system's own text looks, or with the // font's own outlines. An engine without it has no such choice: the renderer diff --git a/internal/platform/windows/direct_gdi_windows.go b/internal/platform/windows/direct_gdi_windows.go index bde6d280a..d6627ef9b 100644 --- a/internal/platform/windows/direct_gdi_windows.go +++ b/internal/platform/windows/direct_gdi_windows.go @@ -233,7 +233,7 @@ func (rasterizer *directRasterizer) useGDI(pieces []gridPiece, family string, si } for index := range pieces { piece := &pieces[index] - weight := nativeFontWeight(piece.weight) + weight := rasterizer.services.monoWeight(piece.weight) // GDI shapes nothing, has no font to fall back to for what the font lacks, and // makes up the weights a family has no face for. if piece.run.Ligatures || !printableASCII(piece.text) || !gdiDrawsWeight(weight) { diff --git a/internal/platform/windows/direct_gdi_windows_test.go b/internal/platform/windows/direct_gdi_windows_test.go index 5ed88d16a..2de27da0a 100644 --- a/internal/platform/windows/direct_gdi_windows_test.go +++ b/internal/platform/windows/direct_gdi_windows_test.go @@ -320,6 +320,32 @@ func TestFixedPitchWeightsGDIWouldMakeUpStayWithDirect2D(t *testing.T) { } } +// TestChosenMonoWeightsDecideTheRenderer guards the grid path of SetMonoWeights: an +// ASCII run is GDI's only where the weight chosen for the fixed-pitch text is one GDI +// draws. Naming another weight must move the run to Direct2D, which draws the face the +// family has for it; otherwise the terminal keeps the platform's weights for the bulk +// of its text and only the cell and the non-ASCII runs follow the choice. +func TestChosenMonoWeightsDecideTheRenderer(t *testing.T) { + engine, err := theTextEngine() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + t.Cleanup(func() { engine.SetMonoWeights(0, 0) }) + label := gridLabel(8, asciiRun("INFO ")) + draw := func(main int) (hinted, natural gridRender) { + engine.SetMonoWeights(main, 0) + return rasterizeGrid(t, label, 1, false), rasterizeGrid(t, label, 1, true) + } + hinted, natural := draw(0) + if bytes.Equal(hinted.pixels, natural.pixels) { + t.Fatal("a regular ASCII run was not drawn by GDI") + } + hinted, natural = draw(500) // medium: GDI makes up a face wider than the cells + if !bytes.Equal(hinted.pixels, natural.pixels) { + t.Error("a run at the chosen medium weight was drawn by GDI") + } +} + // TestFixedPitchRasterizerDeselectsItsFonts guards the rule for GDI objects: a font is not // left selected in the context of the bitmap it was drawn on, because the context is deleted // with the rasterizer and deleting an object that a context still holds is not defined. diff --git a/internal/platform/windows/direct_ink_windows.go b/internal/platform/windows/direct_ink_windows.go index 375f72cdc..c7fb18117 100644 --- a/internal/platform/windows/direct_ink_windows.go +++ b/internal/platform/windows/direct_ink_windows.go @@ -26,7 +26,7 @@ type inkKey struct { fonts uint32 // customFonts.revision fallback uintptr size float32 - weight float32 + mono uint32 // the DirectWrite weight the run is drawn at (textServices.monoWeight) span float32 // the width of the cells it is drawn in, in device pixels italic bool text string @@ -58,7 +58,7 @@ func (rasterizer *directRasterizer) ownedColumns(label platform.TextLabel, piece if piece.index < 0 || piece.run.Cells <= 0 || piece.run.Ligatures || printableASCII(piece.text) { continue } - reach, ok := rasterizer.inkReach(inkKey{family: family, fonts: fonts, fallback: fallback, size: size, weight: piece.weight, span: piece.span, italic: piece.run.Italic, text: piece.text}) + reach, ok := rasterizer.inkReach(inkKey{family: family, fonts: fonts, fallback: fallback, size: size, mono: rasterizer.services.monoWeight(piece.weight), span: piece.span, italic: piece.run.Italic, text: piece.text}) if !ok || (reach.Left <= 0 && reach.Right <= 0) { continue } @@ -102,7 +102,7 @@ func (rasterizer *directRasterizer) inkReach(key inkKey) (platform.GridInk, bool // instead of asking the font for its outline keeps the filter's spill, the hinting and the // fallback font in the answer. func (rasterizer *directRasterizer) measureInk(key inkKey) (platform.GridInk, error) { - format, err := rasterizer.services.formatStyle(key.family, key.size, key.weight, key.italic) + format, err := rasterizer.services.formatWeight(key.family, key.size, key.mono, key.italic) if err != nil { return platform.GridInk{}, err } diff --git a/internal/platform/windows/direct_windows.go b/internal/platform/windows/direct_windows.go index 1e13fca9b..2e159b37d 100644 --- a/internal/platform/windows/direct_windows.go +++ b/internal/platform/windows/direct_windows.go @@ -520,7 +520,7 @@ func (rasterizer *directRasterizer) grid(pixels []byte, label platform.TextLabel // exactly the pitch of the grid, a single wider character is centered on its cells, and // the run's decorations are DirectWrite's own. func (rasterizer *directRasterizer) drawRun(target *directTarget, family string, fallback uintptr, size, weight float32, run gfx.TextRun, piece string, left, span, pitch, baseline float32, clip pieceClip) error { - format, err := rasterizer.services.formatStyle(family, size, weight, run.Italic) + format, err := rasterizer.services.formatMono(family, size, weight, run.Italic) if err != nil { return err } diff --git a/internal/platform/windows/font_weights_windows.go b/internal/platform/windows/font_weights_windows.go new file mode 100644 index 000000000..191f6667f --- /dev/null +++ b/internal/platform/windows/font_weights_windows.go @@ -0,0 +1,60 @@ +package windows + +import ( + "slices" + "syscall" + "unsafe" +) + +// Method slots of IDWriteFontList and IDWriteFont (checked against dwrite.h). +const ( + writeFontListGetFontCount = 4 + writeFontListGetFont = 5 + writeFontGetWeight = 4 +) + +// FontWeights lists the weights family is installed with, ascending: the weights a +// text format of the family may ask for, as DWRITE_FONT_WEIGHT values. A family the +// collection does not have lists none. +func FontWeights(family string) []int { + services := &textServices{} + if err := services.initializeWrite(); err != nil { + return nil + } + defer services.close() + collection, unlock, ok := openCollection(services) + if !ok { + return nil + } + defer unlock() + name, err := syscall.UTF16PtrFromString(family) + if err != nil { + return nil + } + var index, exists uint32 + if err := hresult(comCall(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil || exists == 0 { + return nil + } + var list uintptr + if err := hresult(comCall(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&list)))); err != nil || list == 0 { + return nil + } + defer release(&list) + // GetFontCount returns the count itself, as GetFontFamilyCount does. + count := uint32(comCall(list, writeFontListGetFontCount)) + weights := make([]int, 0, count) + for face := uint32(0); face < count; face++ { + var font uintptr + if err := hresult(comCall(list, writeFontListGetFont, uintptr(face), uintptr(unsafe.Pointer(&font)))); err != nil || font == 0 { + continue + } + // GetWeight returns the DWRITE_FONT_WEIGHT itself. + weight := int(uint32(comCall(font, writeFontGetWeight))) + release(&font) + if !slices.Contains(weights, weight) { + weights = append(weights, weight) + } + } + slices.Sort(weights) + return weights +} diff --git a/internal/platform/windows/font_weights_windows_test.go b/internal/platform/windows/font_weights_windows_test.go new file mode 100644 index 000000000..3c3380adc --- /dev/null +++ b/internal/platform/windows/font_weights_windows_test.go @@ -0,0 +1,112 @@ +package windows + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +// A family's weights are what the settings page offers: the weights it is installed +// with, ascending and without repeats, and none for a family the system does not have. +func TestFontWeightsListsTheFamiliesOwnWeights(t *testing.T) { + weights := FontWeights("Segoe UI") + if len(weights) < 2 { + t.Fatalf("Segoe UI lists %v, fewer weights than it ships", weights) + } + for index, weight := range weights { + if weight <= 0 || weight > 999 { + t.Errorf("weight %d is outside DirectWrite's range", weight) + } + if index > 0 && weights[index-1] >= weight { + t.Errorf("weights are not strictly ascending: %v", weights) + } + } + if got := FontWeights("No such family, certainly not installed"); len(got) != 0 { + t.Errorf("a missing family lists %v", got) + } +} + +// The weights reach the shaped text: the bold band moves to the weight named, the +// main band to its own, and a weight named twice shapes the same line again. +func TestTheInterfaceWeightsShapeTheText(t *testing.T) { + engine, err := theTextEngine() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + engine.SetFontFamily("Segoe UI") + t.Cleanup(func() { + engine.SetFontFamily("") + engine.SetFontWeights(0, 0) + }) + width := func(weight float32) float32 { + line, err := engine.shapeStyle("WWWWWWWWWW", 14, weight, false) + if err != nil { + t.Fatalf("shape: %v", err) + } + return line.width + } + engine.SetFontWeights(0, 0) + regular, bold := width(gfx.WeightRegular), width(gfx.WeightBold) + // The heaviest face the family ships, which is not the bold the platform picks for + // weight 700: a family need not ship Black. + weights := FontWeights("Segoe UI") + if len(weights) < 2 { + t.Skipf("Segoe UI lists %v weights", weights) + } + heavy := weights[len(weights)-1] + if heavy == 700 { + t.Skipf("Segoe UI's heaviest face is bold (%d)", heavy) + } + engine.SetFontWeights(400, heavy) // the family's heaviest against its Bold + heavyWidth := width(gfx.WeightBold) + if heavyWidth == bold { + t.Fatalf("bold text is %.3f wide whether its weight is 700 or %d", bold, heavy) + } + if got := width(gfx.WeightRegular); got != regular { + t.Fatalf("naming the regular weight again changed the main text: %.3f to %.3f", regular, got) + } + if got := width(gfx.WeightMedium); got != regular { + t.Fatalf("medium text is drawn at %.3f, not the main weight's %.3f", got, regular) + } +} + +// The fixed-pitch weights are the terminal's own: the cell it is laid out on is +// measured in the weight it draws with, so a family whose faces differ in advance +// changes the cell when the weight changes, and back when it is taken away. +func TestTheMonoWeightsChooseTheCell(t *testing.T) { + engine, err := theTextEngine() + if err != nil { + t.Skipf("no DirectWrite: %v", err) + } + t.Cleanup(func() { engine.SetMonoWeights(0, 0) }) + // A proportional family used as a grid face: its regular and bold faces differ + // in advance, where a fixed-pitch family's would not. + face := gfx.MonoFamily("Segoe UI") + engine.SetMonoWeights(0, 0) + regular := engine.MonoCell(14, face) + // The weight is the family's own: a stripped image may not install the one the + // test would name, and the invariant is that some installed weight moves the cell. + chosen := 0 + for _, weight := range FontWeights("Segoe UI") { + if weight == 400 { + continue + } + engine.SetMonoWeights(weight, 0) + if engine.MonoCell(14, face).Advance != regular.Advance { + chosen = weight + break + } + } + engine.SetMonoWeights(0, 0) + if chosen == 0 { + t.Skip("no installed weight of Segoe UI changes the cell from regular") + } + engine.SetMonoWeights(chosen, 0) + if bold := engine.MonoCell(14, face); bold.Advance == regular.Advance { + t.Fatalf("the cell is %.3f wide at both regular and weight %d", regular.Advance, chosen) + } + engine.SetMonoWeights(0, 0) + if again := engine.MonoCell(14, face); again.Advance != regular.Advance { + t.Fatalf("taking the weight away left the cell at %.3f, not %.3f", again.Advance, regular.Advance) + } +} diff --git a/internal/platform/windows/fonts_direct_windows.go b/internal/platform/windows/fonts_direct_windows.go new file mode 100644 index 000000000..c81dd65ea --- /dev/null +++ b/internal/platform/windows/fonts_direct_windows.go @@ -0,0 +1,153 @@ +package windows + +import ( + "math" + "sort" + "syscall" + "unsafe" +) + +// Method slots of IDWriteFontCollection, IDWriteFontFamily and +// IDWriteLocalizedStrings (checked against dwrite.h). +const ( + writeCollectionGetFontFamilyCount = 3 + writeFontFamilyGetFamilyNames = 6 + writeStringsGetStringLength = 7 + writeStringsGetString = 8 +) + +// The installed families, read from DirectWrite's system font collection. This +// is the list every name in this package is resolved through: CreateTextFormat +// looks a family up in that collection, so a name that is not one of its families +// draws in the fallback font without saying so. GDI, whose enumeration the list +// used to come from, reports the typeface names of a family's styles instead +// ("Maple Mono Light", "Cascadia Mono SemiBold"): a style is what a user may +// install, but it is not a family, and picking one changed nothing. + +// directFamilies lists the family names of the collection every text format is +// made from, sorted, only the fixed-pitch ones when monospace is set. It reports +// false when DirectWrite cannot answer at all, which leaves the caller its GDI +// fallback. +func directFamilies(mono bool) ([]string, bool) { + services := &textServices{} + if err := services.initializeWrite(); err != nil { + return nil, false + } + defer services.close() + names, ok := collectionFamilyNames(services) + if !ok { + return nil, false + } + if mono { + // The measurement takes the same collection lock the names were read + // under, so it runs after that lock is back: a writer waiting for it + // would otherwise meet the read lock this goroutine already holds. + kept := names[:0] + for _, name := range names { + if familyMeasuresMono(services, name) { + kept = append(kept, name) + } + } + names = kept + } + if len(names) == 0 { + return nil, false + } + sort.Slice(names, func(i, j int) bool { return lowerASCII(names[i]) < lowerASCII(names[j]) }) + return names, true +} + +// collectionFamilyNames reads every family name of the collection text formats +// are made from: the application's fonts and the system's when it registered +// one, the system's alone otherwise. +func collectionFamilyNames(services *textServices) ([]string, bool) { + collection, unlock, ok := openCollection(services) + if !ok { + return nil, false + } + defer unlock() + // GetFontFamilyCount returns the count itself; it takes no out parameter. + count := uint32(comCall(collection, writeCollectionGetFontFamilyCount)) + names := make([]string, 0, count) + for index := uint32(0); index < count; index++ { + name, ok := collectionFamilyName(collection, index) + if !ok || name == "" { + continue + } + // An @-prefixed name is the vertical-writing variant of the family before + // it, which nothing here draws. + if name[0] == '@' { + continue + } + names = append(names, name) + } + return names, len(names) > 0 +} + +// openCollection is the font collection every text format is made from: the +// application's fonts and the system's when it registered one, the system's alone +// otherwise. unlock is called once the collection is no longer read; it stays +// locked only while a name is looked up in it, never across a layout that takes +// the same lock. +func openCollection(services *textServices) (collection uintptr, unlock func(), ok bool) { + customFonts.RLock() + if customFonts.collection != 0 { + return customFonts.collection, customFonts.RUnlock, true + } + customFonts.RUnlock() + system := uintptr(0) + status := comCall(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&system)), 0) + if err := hresult(status); err != nil || system == 0 { + return 0, func() {}, false + } + return system, func() { release(&system) }, true +} + +// collectionFamilyName is the family's name in the collection, in the locale the +// font lists first — the name CreateTextFormat resolves. +func collectionFamilyName(collection uintptr, index uint32) (string, bool) { + var family uintptr + if err := hresult(comCall(collection, writeCollectionGetFontFamily, uintptr(index), uintptr(unsafe.Pointer(&family)))); err != nil || family == 0 { + return "", false + } + defer release(&family) + var strings uintptr + if err := hresult(comCall(family, writeFontFamilyGetFamilyNames, uintptr(unsafe.Pointer(&strings)))); err != nil || strings == 0 { + return "", false + } + defer release(&strings) + var length uint32 + if err := hresult(comCall(strings, writeStringsGetStringLength, 0, uintptr(unsafe.Pointer(&length)))); err != nil || length == 0 { + return "", false + } + buffer := make([]uint16, length+1) + if err := hresult(comCall(strings, writeStringsGetString, 0, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)))); err != nil { + return "", false + } + return syscall.UTF16ToString(buffer), true +} + +// familyMeasuresMono reports whether family draws the printable ASCII on one advance, as +// a terminal's grid needs. Twenty i's and twenty W's come out the same width only +// when it does, which measures the family through the same layout the text is +// drawn with: the system's fixed-pitch flag is wrong for some families a terminal +// wants (Nerd Fonts among them) and right-but-slow to trust for others. +func familyMeasuresMono(services *textServices, family string) bool { + narrow, err := services.measureIn(family, "iiiiiiiiiiiiiiiiiiii", monoMeasureSize, 0) + if err != nil || narrow.Width <= 0 { + return false + } + wide, err := services.measureIn(family, "WWWWWWWWWWWWWWWWWWWW", monoMeasureSize, 0) + if err != nil { + return false + } + return math.Abs(float64(narrow.Width-wide.Width)) < monoMeasureTolerance +} + +// monoMeasureSize is the size the fixed-pitch families are measured at, and +// monoMeasureTolerance the width they must agree within, in logical pixels. Two +// advances differ by far more than this in a proportional family at any size. +const ( + monoMeasureSize = 14 + monoMeasureTolerance = 0.01 +) diff --git a/internal/platform/windows/fonts_direct_windows_test.go b/internal/platform/windows/fonts_direct_windows_test.go new file mode 100644 index 000000000..6c01d7490 --- /dev/null +++ b/internal/platform/windows/fonts_direct_windows_test.go @@ -0,0 +1,65 @@ +package windows + +import ( + "syscall" + "testing" + "unsafe" +) + +// familyExists asks DirectWrite whether name is a family of the system collection, +// the way every text format here resolves one. +func familyExists(services *textServices, name string) (bool, error) { + var collection uintptr + if err := hresult(comCall(services.write, writeFactoryGetSystemFontCollection, uintptr(unsafe.Pointer(&collection)), 0)); err != nil || collection == 0 { + return false, err + } + defer release(&collection) + wide, err := syscall.UTF16PtrFromString(name) + if err != nil { + return false, err + } + var index, exists uint32 + if err := hresult(comCall(collection, writeCollectionFindFamilyName, uintptr(unsafe.Pointer(wide)), uintptr(unsafe.Pointer(&index)), uintptr(unsafe.Pointer(&exists)))); err != nil { + return false, err + } + return exists != 0, nil +} + +// Every listed name must be a family DirectWrite resolves: a settings page applies +// a name from the list through CreateTextFormat, and the typeface names GDI reports +// ("Maple Mono Light", "Cascadia Mono SemiBold") are not families, so choosing one +// silently kept the fallback font and previewed it instead. +func TestEveryListedFamilyResolves(t *testing.T) { + services := &textServices{} + if err := services.initializeWrite(); err != nil { + t.Skipf("no DirectWrite: %v", err) + } + defer services.close() + lists := []struct { + name string + families []string + }{ + {"FontFamilies", FontFamilies()}, + {"MonospaceFamilies", MonospaceFamilies()}, + } + for _, list := range lists { + if len(list.families) == 0 { + t.Fatalf("%s listed no family", list.name) + } + resolved := map[string]bool{} + for _, family := range list.families { + if resolved[family] { + t.Errorf("%s lists %q twice", list.name, family) + continue + } + exists, err := familyExists(services, family) + if err != nil { + t.Fatalf("%s: %q: %v", list.name, family, err) + } + if !exists { + t.Errorf("%s lists %q, which DirectWrite does not resolve", list.name, family) + } + resolved[family] = true + } + } +} diff --git a/internal/platform/windows/fonts_windows.go b/internal/platform/windows/fonts_windows.go index 0b46aa7fb..632f2cff5 100644 --- a/internal/platform/windows/fonts_windows.go +++ b/internal/platform/windows/fonts_windows.go @@ -122,14 +122,28 @@ func fontMeasuresUniform(logFont *enumLogFont) bool { // MonospaceFamilies lists the installed fixed-pitch font families, sorted. func MonospaceFamilies() []string { return fontFamilies(true) } -// FontFamilies lists every installed font family, sorted. A family whose name fills -// the 31 characters of a LOGFONT is left out (see fontEnumCallback). +// FontFamilies lists every installed font family, sorted. func FontFamilies() []string { return fontFamilies(false) } -// fontFamilies enumerates the installed families, only the fixed-pitch ones when -// monospace is set. Raster fonts and the vertical-writing variants are left out -// either way. +// fontFamilies lists the installed families, only the fixed-pitch ones when +// monospace is set. The names come from DirectWrite, whose families are the ones +// every format and layout in this package resolves a name through: a list from +// GDI would hold the typeface names of a family's styles ("Maple Mono Light", +// "Cascadia Mono SemiBold"), which CreateTextFormat does not know, and a name +// picked from it would silently draw in the fallback font. The GDI enumeration +// is kept for a machine without DirectWrite, where the lists are at least what +// the old code returned. func fontFamilies(mono bool) []string { + if names, ok := directFamilies(mono); ok { + return names + } + return gdiFamilies(mono) +} + +// gdiFamilies enumerates the installed families through GDI, only the fixed-pitch +// ones when monospace is set. Raster fonts and the vertical-writing variants are +// left out either way. +func gdiFamilies(mono bool) []string { fontEnumMu.Lock() defer fontEnumMu.Unlock() if fontEnumCallbackPtr == 0 { diff --git a/internal/platform/windows/ink_overflow_windows_test.go b/internal/platform/windows/ink_overflow_windows_test.go index cd634a3b4..921175081 100644 --- a/internal/platform/windows/ink_overflow_windows_test.go +++ b/internal/platform/windows/ink_overflow_windows_test.go @@ -57,7 +57,7 @@ func TestMeasuredInkIsTheFontsOutline(t *testing.T) { rasterizer := newTestRasterizer(t) const size = 40 span := float32(testIconCell * size) - reach, err := rasterizer.measureInk(inkKey{family: gfx.MonoFamilyName(face), size: size, span: span, text: testIcon}) + reach, err := rasterizer.measureInk(inkKey{family: gfx.MonoFamilyName(face), size: size, mono: 400, span: span, text: testIcon}) if err != nil { t.Fatal(err) } diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index cf931fe63..bb4e2f804 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -26,6 +26,15 @@ type textServices struct { write uintptr createFormat func(uintptr, *uint16, uintptr, uint32, uint32, uint32, float32, *uint16, *uintptr) uintptr createLayout func(uintptr, *uint16, uint32, uintptr, float32, float32, *uintptr) uintptr + // mainWeight and boldWeight are the weights the interface's proportional text is + // drawn at: main for regular and medium text, bold for semibold and bold. A zero + // keeps DirectWrite's own weight for that band (400 and 700). The engine sets them + // (SetFontWeights); the rasterizer shares this struct, so both draw the same. + mainWeight, boldWeight uint32 + // monoMainWeight and monoBoldWeight are the same for the fixed-pitch text — a + // terminal's face — whose weights the application names apart from the interface's + // (SetMonoWeights). They also choose the cell the terminal is laid out on. + monoMainWeight, monoBoldWeight uint32 } type labelTexture struct { label platform.TextLabel @@ -107,6 +116,23 @@ func (services *textServices) formatFamily(name string, size, weight float32) (u // formatStyle is a DirectWrite text format of a family at a Viva weight, in italics or not. func (services *textServices) formatStyle(name string, size, weight float32, italic bool) (uintptr, error) { + return services.formatWeight(name, size, nativeFontWeight(weight), italic) +} + +// formatInterface is formatStyle for the interface's proportional text: the weight is +// the application's main or bold weight where it named one for that text's band. +func (services *textServices) formatInterface(name string, size, weight float32, italic bool) (uintptr, error) { + return services.formatWeight(name, size, services.interfaceWeight(weight), italic) +} + +// formatMono is formatStyle for fixed-pitch text — a terminal's face — drawn at the +// weights the application chose for it. +func (services *textServices) formatMono(name string, size, weight float32, italic bool) (uintptr, error) { + return services.formatWeight(name, size, services.monoWeight(weight), italic) +} + +// formatWeight is a DirectWrite text format of a family at a DirectWrite weight. +func (services *textServices) formatWeight(name string, size float32, weight uint32, italic bool) (uintptr, error) { family, _ := syscall.UTF16PtrFromString(name) locale, _ := syscall.UTF16PtrFromString("") var format uintptr @@ -117,10 +143,37 @@ func (services *textServices) formatStyle(name string, size, weight float32, ita // The collection the application's fonts joined, or the system's when it registered none. customFonts.RLock() defer customFonts.RUnlock() - status := services.createFormat(services.write, family, customFonts.collection, nativeFontWeight(weight), style, 5, size, locale, &format) + status := services.createFormat(services.write, family, customFonts.collection, weight, style, 5, size, locale, &format) return format, hresult(status) } +// interfaceWeight is the DirectWrite weight text at a Viva weight is drawn at: the +// application's main weight for regular and medium text, its bold weight for semibold +// and bold, and nativeFontWeight's own answer for either band the application did not name. +func (services *textServices) interfaceWeight(weight float32) uint32 { + return services.chosenWeight(weight, services.mainWeight, services.boldWeight) +} + +// monoWeight is interfaceWeight for the fixed-pitch text, whose weights the +// application names apart from the interface's. +func (services *textServices) monoWeight(weight float32) uint32 { + return services.chosenWeight(weight, services.monoMainWeight, services.monoBoldWeight) +} + +// chosenWeight is the weight a Viva weight is drawn at under a main and a bold +// choice: main for regular and medium text, bold for semibold and bold, and +// nativeFontWeight's own answer for a band the application did not name. +func (services *textServices) chosenWeight(weight float32, main, bold uint32) uint32 { + native := nativeFontWeight(weight) + switch { + case native <= 500 && main != 0: + return main + case native >= 600 && bold != 0: + return bold + } + return native +} + // nativeFontWeight is the DirectWrite weight of a Viva weight: regular, medium, semibold and // bold are the faces Segoe UI has. A font without one of them, such as Consolas, which has // regular and bold only, is drawn with the face DirectWrite finds nearest. @@ -407,7 +460,7 @@ func MeasureMono(size float32, face gfx.MonoFace) (width, height float32, err er } engine.mu.Lock() defer engine.mu.Unlock() - metrics, err := engine.services.measureIn(monoFamily(face), "M", size, 0) + metrics, err := engine.services.measureMonoIn(monoFamily(face), "M", size, 0) if err != nil { return 0, 0, err } @@ -439,10 +492,23 @@ func (services *textServices) measure(value string, size, weight float32) (text. } func (services *textServices) measureIn(typeface, value string, size, weight float32) (text.Metrics, error) { + return services.measureWeightIn(typeface, value, size, nativeFontWeight(weight)) +} + +// measureMonoIn is measureIn at the weight the application named for fixed-pitch +// text: the cell a terminal is laid out on and the box drawing strokes that come +// with it follow the face the terminal actually draws. +func (services *textServices) measureMonoIn(typeface, value string, size, weight float32) (text.Metrics, error) { + return services.measureWeightIn(typeface, value, size, services.monoWeight(weight)) +} + +// measureWeightIn lays value out in typeface at a DirectWrite weight and reports its +// metrics. +func (services *textServices) measureWeightIn(typeface, value string, size float32, weight uint32) (text.Metrics, error) { if size <= 0 || math.IsNaN(float64(size)) || math.IsInf(float64(size), 0) { return text.Metrics{}, fmt.Errorf("windows: invalid font size") } - format, err := services.formatFamily(typeface, size, weight) + format, err := services.formatWeight(typeface, size, weight, false) if err != nil { return text.Metrics{}, err } @@ -552,7 +618,7 @@ func (services *textServices) boxStrokes(typeface string, size, weight float32) stretchNormal = 5 styleNormal = 0 ) - if err := hresult(comCall(family, writeFontFamilyGetFirstMatchingFont, uintptr(nativeFontWeight(weight)), stretchNormal, styleNormal, uintptr(unsafe.Pointer(&font)))); err != nil { + if err := hresult(comCall(family, writeFontFamilyGetFirstMatchingFont, uintptr(services.monoWeight(weight)), stretchNormal, styleNormal, uintptr(unsafe.Pointer(&font)))); err != nil { return 0, 0 } defer release(&font) diff --git a/internal/platform/windows/textengine_windows.go b/internal/platform/windows/textengine_windows.go index d8079cd1b..329f2865d 100644 --- a/internal/platform/windows/textengine_windows.go +++ b/internal/platform/windows/textengine_windows.go @@ -124,6 +124,8 @@ func theTextEngine() (*textEngine, error) { } var _ gfx.FontFamilyAware = (*textEngine)(nil) +var _ gfx.FontWeightAware = (*textEngine)(nil) +var _ gfx.MonoWeightAware = (*textEngine)(nil) var _ gfx.TextRasterizer = (*textEngine)(nil) var _ gfx.MonoCellEngine = (*textEngine)(nil) @@ -176,13 +178,55 @@ func (engine *textEngine) SetFontFamily(family string) { engine.generation.Add(1) } +// SetFontWeights implements gfx.FontWeightAware: the weights the interface's text is +// drawn at, main for regular and medium text and bold for semibold and bold, or 0 for +// the engine's own. Everything shaped at another weight is forgotten. +func (engine *textEngine) SetFontWeights(main, bold int) { + mainWeight, boldWeight := interfaceWeight(main), interfaceWeight(bold) + engine.mu.Lock() + defer engine.mu.Unlock() + if mainWeight == engine.services.mainWeight && boldWeight == engine.services.boldWeight { + return + } + engine.services.mainWeight, engine.services.boldWeight = mainWeight, boldWeight + engine.cache.Clear() + if engine.italicCache != nil { + engine.italicCache.Clear() + } + engine.generation.Add(1) +} + +// interfaceWeight is a weight the application chose, clamped to DirectWrite's range, or +// 0 for the engine's own weight of that band. +func interfaceWeight(weight int) uint32 { + if weight <= 0 { + return 0 + } + return uint32(min(weight, 999)) +} + +// SetMonoWeights implements gfx.MonoWeightAware: the weights the fixed-pitch text is +// drawn at, main for its regular text and bold for its bold runs, or 0 for the engine's +// own. The cell the text is laid out on follows them, so the generation moves and the +// canvas measures its cells again. +func (engine *textEngine) SetMonoWeights(main, bold int) { + mainWeight, boldWeight := interfaceWeight(main), interfaceWeight(bold) + engine.mu.Lock() + defer engine.mu.Unlock() + if mainWeight == engine.services.monoMainWeight && boldWeight == engine.services.monoBoldWeight { + return + } + engine.services.monoMainWeight, engine.services.monoBoldWeight = mainWeight, boldWeight + engine.generation.Add(1) +} + // MonoCell implements gfx.MonoCellEngine: the cell of the face's own font, which is the // cell a terminal is laid out on and stands on. func (engine *textEngine) MonoCell(size float32, face gfx.MonoFace) gfx.MonoCellMetrics { engine.mu.Lock() defer engine.mu.Unlock() family := monoFamily(face) - metrics, err := engine.services.measureIn(family, "M", size, 0) + metrics, err := engine.services.measureMonoIn(family, "M", size, 0) if err != nil { return gfx.MonoCellMetrics{} } @@ -292,7 +336,7 @@ func (engine *textEngine) shapeStyle(value string, size, weight float32, italic if family == "" { family = "Segoe UI" } - format, err := engine.services.formatStyle(family, size, weight, italic) + format, err := engine.services.formatInterface(family, size, weight, italic) if err != nil { return nil, err } From b17e60542d576c1206b9bbcc819f54d73eb4efd8 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Mon, 16 Nov 2026 15:56:32 +0800 Subject: [PATCH 13/13] fix(update): resume an interrupted download --- docs/updating.md | 18 +- update/client.go | 15 +- update/doc.go | 6 +- update/download.go | 418 +++++++++++++++++++++++++++---- update/download_resume_test.go | 439 +++++++++++++++++++++++++++++++++ 5 files changed, 839 insertions(+), 57 deletions(-) create mode 100644 update/download_resume_test.go diff --git a/docs/updating.md b/docs/updating.md index 54ba6414d..201f88740 100644 --- a/docs/updating.md +++ b/docs/updating.md @@ -260,6 +260,19 @@ err = update.Install(update.InstallOptions{ }, application.Quit) ``` +A download that stops part way returns an error wrapping +`update.ErrInterrupted`: the connection failed, nothing arrived for a minute, +the host answered with a temporary status (408, 429 or 5xx), or `ctx` ended (the +error then wraps `context.Canceled` or `context.DeadlineExceeded` as well). The +bytes that arrived stay in `downloadDir`, and calling `Download` again with the +same directory sends a `Range` request for the rest; a host that ignores it +sends the whole file, which is fine. When the directory already holds the +verified file, `Download` returns it without a request. Keep `downloadDir` per +release and remove it once the release is installed or skipped. Two processes +must not download the same asset into the same directory at once. +`DownloadPatch` behaves the same way, so a cut-off patch is worth resuming +before falling back to the full archive. + `Install` returns only after it has started the helper that replaces the application; the helper waits for this process to exit. If `Install` returns an error nothing has been changed and `quit` was not called. @@ -294,7 +307,10 @@ installer are per-user by default and need no elevation. another operating system or architecture. - **Exact bytes.** A download is written while it is hashed and is kept only when both its length and SHA-256 match the feed (`ErrSize`, `ErrChecksum`). - A refused download leaves no file behind. `Install` hashes the file again + A refused download leaves no file behind. An interrupted one keeps its bytes + in a hidden file named by the feed's digest, so they are only ever continued + with the rest of the same file, and the whole file is hashed again before it + is kept. `Install` hashes the file again immediately before handing it to the platform, because the file sits on disk between the two calls. - **Bounded.** `latest.json` is limited to 1 MiB, its signature to 4 KiB, an diff --git a/update/client.go b/update/client.go index 8f53172f9..fac858d89 100644 --- a/update/client.go +++ b/update/client.go @@ -49,6 +49,13 @@ var ( // ErrChecksum reports a download whose SHA-256 is not the one the feed // declared. ErrChecksum = errors.New("update: download does not match its checksum") + // ErrInterrupted reports a download that stopped before the file was + // complete: the connection failed, nothing arrived for a minute, the host + // answered with a temporary error, or the caller's context ended (the error + // then wraps the context's error too). The bytes that arrived stay in the + // directory, and calling Download or DownloadPatch again with the same + // directory asks the host only for the rest. + ErrInterrupted = errors.New("update: download interrupted") ) // Config configures a Client. FeedURL, PublicKeys and Current are required. @@ -69,7 +76,8 @@ type Config struct { // HTTP overrides the client used for the feed and its signature. Nil uses a // client with a 30 second timeout. The archive download always uses a client // with no total timeout, because a large installer may take longer than any - // sensible request timeout; the context passed to Download cancels it. + // sensible request timeout; the context passed to Download cancels it, and + // a connection that delivers nothing for a minute ends with ErrInterrupted. HTTP *http.Client // MaxAssetBytes bounds Download. Zero means DefaultMaxAssetBytes. MaxAssetBytes int64 @@ -91,7 +99,9 @@ type Client struct { assetHTTP *http.Client maxAsset int64 maxManifest int64 - now func() time.Time + // stall ends a download that has received nothing for this long. + stall time.Duration + now func() time.Time } // New validates config and returns a Client. @@ -147,6 +157,7 @@ func New(config Config) (*Client, error) { assetHTTP: assetHTTP, maxAsset: maxAsset, maxManifest: DefaultMaxManifestBytes, + stall: stallTimeout, now: now, }, nil } diff --git a/update/doc.go b/update/doc.go index 8860f1a63..28c43886a 100644 --- a/update/doc.go +++ b/update/doc.go @@ -24,8 +24,10 @@ // it is newer than the running version: a check that finds nothing newer // returns (nil, nil). Download streams the archive for the running platform, // hashing as it writes, and refuses a file whose size or digest is not the one -// the feed declared. Neither function sends an identifier, telemetry or -// anything else the caller did not configure. +// the feed declared. A transfer that is cut off, goes silent for a minute or is +// cancelled reports ErrInterrupted and keeps what arrived, so calling Download +// again with the same directory asks only for the rest. Neither function sends +// an identifier, telemetry or anything else the caller did not configure. // // # What this package does not do // diff --git a/update/download.go b/update/download.go index 0d0fe95ec..2f78a9098 100644 --- a/update/download.go +++ b/update/download.go @@ -3,8 +3,11 @@ package update import ( "context" "crypto/sha256" + "crypto/tls" "encoding/hex" + "errors" "fmt" + "hash" "io" "math" "net/http" @@ -12,21 +15,48 @@ import ( "os" "path" "path/filepath" + "strconv" "strings" + "sync" + "time" ) +// stallTimeout ends a download that has received nothing for this long. A +// slow connection still delivers something every few seconds; one that is +// silent for a minute has gone away without saying so. +const stallTimeout = time.Minute + +// errStalled is the cause a download's context is cancelled with when nothing +// arrived for the stall timeout. +var errStalled = errors.New("update: download stalled") + // Download streams asset into dir and returns the file's path. The bytes are -// hashed as they arrive and the call fails without keeping a file unless the -// length and SHA-256 are exactly the ones the feed declared; a partially -// written download is removed. +// hashed as they arrive and the file is kept under its own name only when its +// length and SHA-256 are exactly the ones the feed declared. +// +// A transfer that stops part way, because the connection failed, went silent +// for a minute, the host answered with a temporary error or ctx ended, returns +// an error wrapping ErrInterrupted and keeps the bytes that arrived in a hidden +// file in dir. Calling Download again with the same asset and dir asks the host +// only for the rest; the whole file is still checked against the feed's digest +// before it is kept, and a file that fails that check is fetched again from the +// start once. When dir already holds the verified file, Download returns it +// without a request. +// +// dir must belong to the application: another user who can write to it could +// put a link where the partial file goes. Two processes must not download the +// same asset into the same dir at once; calls within one process wait for each +// other. // // progress, when not nil, is called while the file arrives with the bytes -// written so far and the total the feed declared. It runs on the goroutine -// calling Download, so it may update state directly but must not block. +// written so far and the total the feed declared; a resumed download starts at +// the bytes it kept. It runs on the goroutine calling Download, so it may update +// state directly but must not block. // // An archive is not unpacked or installed here: this method only guarantees // the file is the one the signed feed named. A refusal wraps ErrChecksum, -// ErrSize, ErrTooLarge, ErrInsecureURL or ErrManifest. +// ErrSize, ErrTooLarge, ErrInsecureURL or ErrManifest, and leaves no partial +// file behind. func (client *Client) Download(ctx context.Context, asset Asset, dir string, progress func(done, total int64)) (string, error) { if err := asset.validate(); err != nil { return "", fmt.Errorf("%w: %w", ErrManifest, err) @@ -38,10 +68,10 @@ func (client *Client) Download(ctx context.Context, asset Asset, dir string, pro } // DownloadPatch streams a delta update into dir and returns the patch file's -// path. It checks the bytes exactly as Download does, against the size and -// SHA-256 the signed feed declared for the patch. The patch is not applied -// here: ReadPatch and PatchReader.Apply do that, after the caller has checked the -// patch names the running application and version. +// path. It checks, keeps and resumes the bytes exactly as Download does, against +// the size and SHA-256 the signed feed declared for the patch. The patch is not +// applied here: ReadPatch and PatchReader.Apply do that, after the caller has +// checked the patch names the running application and version. func (client *Client) DownloadPatch(ctx context.Context, asset Asset, patch Patch, dir string, progress func(done, total int64)) (string, error) { if err := asset.validate(); err != nil { return "", fmt.Errorf("%w: %w", ErrManifest, err) @@ -56,8 +86,8 @@ func (client *Client) DownloadPatch(ctx context.Context, asset Asset, patch Patc return client.download(ctx, patch.URL, patch.Size, patch.SHA256, name, dir, progress) } -// download fetches one file and keeps it only when its length and digest are -// the declared ones. +// download fetches one file, resuming what an earlier call kept, and keeps it +// under name only when its length and digest are the declared ones. func (client *Client) download(ctx context.Context, rawURL string, size int64, digest string, name, dir string, progress func(done, total int64)) (string, error) { if size >= math.MaxInt64 { return "", fmt.Errorf("%w: file is %d bytes", ErrTooLarge, size) @@ -65,68 +95,295 @@ func (client *Client) download(ctx context.Context, rawURL string, size int64, d if err := os.MkdirAll(dir, 0o755); err != nil { return "", fmt.Errorf("update: %w", err) } - request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + partial := filepath.Join(dir, partialName(digest)) + unlock, err := transfers.lock(ctx, partial) if err != nil { - return "", fmt.Errorf("update: %w", err) + return "", err + } + defer unlock() + + destination := filepath.Join(dir, name) + if holds(destination, size, digest) { + report(progress, size, size) + return destination, nil + } + resumed, err := client.fetchFile(ctx, rawURL, size, digest, partial, progress) + if err != nil && resumed && (errors.Is(err, ErrChecksum) || errors.Is(err, ErrSize)) { + // The kept bytes were not the start of this file: a crash wrote less than + // it reported, or the host was serving something else then. The partial is + // gone, so this asks for the whole file. + _, err = client.fetchFile(ctx, rawURL, size, digest, partial, progress) } - request.Header.Set("User-Agent", "viva-update/1") - response, err := client.assetHTTP.Do(request) if err != nil { - return "", fmt.Errorf("update: %w", err) + return "", err } - defer response.Body.Close() - if response.Request != nil && response.Request.URL != nil && response.Request.URL.Scheme != "https" { - return "", fmt.Errorf("%w: %s redirected to %s", ErrInsecureURL, rawURL, response.Request.URL) + if err := os.Chmod(partial, 0o644); err != nil { + return "", fmt.Errorf("update: %w", err) } - if response.StatusCode != http.StatusOK { - return "", fmt.Errorf("update: %s: %s", rawURL, response.Status) + if err := os.Rename(partial, destination); err != nil { + return "", fmt.Errorf("update: %w", err) } + report(progress, size, size) + return destination, nil +} - file, err := os.CreateTemp(dir, ".viva-update-*") +// fetchFile brings partial up to size bytes, asking the host only for what it does +// not hold yet, and checks the whole file against digest. resumed reports that +// the bytes it checked include some kept from before this call. A refusal +// removes partial; an interruption keeps it for the next call. +func (client *Client) fetchFile(ctx context.Context, rawURL string, size int64, digest, partial string, progress func(done, total int64)) (resumed bool, err error) { + file, offset, hasher, err := openPartial(partial, size) if err != nil { - return "", fmt.Errorf("update: %w", err) + return false, err } - temporary := file.Name() - keep := false + refused := false defer func() { _ = file.Close() - if !keep { - _ = os.Remove(temporary) + if refused { + _ = os.Remove(partial) + } else if info, statErr := os.Lstat(partial); statErr == nil && info.Size() == 0 { + _ = os.Remove(partial) } }() + resumed = offset > 0 + report(progress, offset, size) - hasher := sha256.New() - writer := io.MultiWriter(file, hasher) - if progress != nil { - progress(0, size) - } - counter := &progressWriter{writer: writer, total: size, progress: progress} - written, err := io.Copy(counter, io.LimitReader(response.Body, size+1)) - if err != nil { - return "", fmt.Errorf("update: reading %s: %w", rawURL, err) + if offset < size { + written, err := client.transfer(ctx, rawURL, size, offset, file, hasher, progress) + offset, resumed = written.size, written.resumed + if err != nil { + return resumed, err + } } - if written != size { - return "", fmt.Errorf("%w: got %d bytes, feed declares %d", ErrSize, written, size) + if offset != size { + refused = true + return resumed, fmt.Errorf("%w: got %d bytes, feed declares %d", ErrSize, offset, size) } if err := file.Close(); err != nil { - return "", fmt.Errorf("update: %w", err) + return resumed, fmt.Errorf("update: %w", err) } sum := hex.EncodeToString(hasher.Sum(nil)) if !strings.EqualFold(sum, digest) { - return "", fmt.Errorf("%w: %s", ErrChecksum, sum) + refused = true + return resumed, fmt.Errorf("%w: %s", ErrChecksum, sum) } - if err := os.Chmod(temporary, 0o644); err != nil { - return "", fmt.Errorf("update: %w", err) + return resumed, nil +} + +// transferred is what a transfer left in the partial file: its length, and +// whether that still starts with bytes kept from an earlier call. +type transferred struct { + size int64 + resumed bool +} + +// transfer asks the host for the bytes from offset on and appends them to file +// and hasher. A host that ignores the range, or answers for another part of the +// file, makes it start over from the first byte. Nothing arriving for the +// client's stall timeout ends it with ErrInterrupted, as does a failed +// connection, a temporary status or the end of ctx. +func (client *Client) transfer(ctx context.Context, rawURL string, size, offset int64, file *os.File, hasher hash.Hash, progress func(done, total int64)) (transferred, error) { + state := transferred{size: offset, resumed: offset > 0} + watched, stop := context.WithCancelCause(ctx) + defer stop(nil) + stall := client.stall + if stall <= 0 { + stall = stallTimeout } - destination := filepath.Join(dir, name) - if err := os.Rename(temporary, destination); err != nil { - return "", fmt.Errorf("update: %w", err) + watchdog := time.AfterFunc(stall, func() { stop(errStalled) }) + defer watchdog.Stop() + alive := func() { watchdog.Reset(stall) } + interrupted := func(err error) error { + if ctx.Err() != nil { + return fmt.Errorf("%w: %w", ErrInterrupted, ctx.Err()) + } + if errors.Is(context.Cause(watched), errStalled) { + return fmt.Errorf("%w: %s: nothing arrived for %s", ErrInterrupted, rawURL, stall) + } + return fmt.Errorf("%w: %s: %w", ErrInterrupted, rawURL, err) + } + startOver := func() error { + state = transferred{} + hasher.Reset() + if err := file.Truncate(0); err != nil { + return fmt.Errorf("update: %w", err) + } + if _, err := file.Seek(0, io.SeekStart); err != nil { + return fmt.Errorf("update: %w", err) + } + report(progress, 0, size) + return nil + } + + var response *http.Response + for { + var err error + response, err = client.requestFrom(watched, rawURL, state.size) + if err != nil { + if errors.Is(err, ErrInsecureURL) || !transient(err) { + return state, err + } + return state, interrupted(err) + } + alive() + status := response.StatusCode + if status == http.StatusPartialContent && state.size > 0 && rangeFrom(response.Header.Get("Content-Range"), state.size, size) { + break + } + if status == http.StatusOK { + if state.size > 0 { + // The host ignored the range and sent the whole file. + if err := startOver(); err != nil { + _ = response.Body.Close() + return state, err + } + } + break + } + _ = response.Body.Close() + if state.size > 0 && (status == http.StatusPartialContent || status == http.StatusRequestedRangeNotSatisfiable) { + // An answer for another part of the file, or none: the kept bytes + // cannot be continued, so ask once more for all of it. + if err := startOver(); err != nil { + return state, err + } + continue + } + failure := fmt.Errorf("update: %s: %s", rawURL, response.Status) + if temporaryStatus(status) { + return state, interrupted(failure) + } + return state, failure } - keep = true + defer response.Body.Close() + + body := &watchedReader{reader: response.Body, alive: alive} + counter := &progressWriter{writer: io.MultiWriter(file, hasher), total: size, done: state.size, progress: progress} + written, err := io.Copy(counter, io.LimitReader(body, size-state.size+1)) + state.size += written + if err != nil { + if body.failed { + return state, interrupted(err) + } + return state, fmt.Errorf("update: writing %s: %w", file.Name(), err) + } + return state, nil +} + +// requestFrom asks for rawURL, from byte offset on when offset is not zero. +func (client *Client) requestFrom(ctx context.Context, rawURL string, offset int64) (*http.Response, error) { + request, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return nil, fmt.Errorf("update: %w", err) + } + request.Header.Set("User-Agent", "viva-update/1") + if offset > 0 { + request.Header.Set("Range", "bytes="+strconv.FormatInt(offset, 10)+"-") + } + response, err := client.assetHTTP.Do(request) + if err != nil { + return nil, fmt.Errorf("update: %w", err) + } + if response.Request != nil && response.Request.URL != nil && response.Request.URL.Scheme != "https" { + _ = response.Body.Close() + return nil, fmt.Errorf("%w: %s redirected to %s", ErrInsecureURL, rawURL, response.Request.URL) + } + return response, nil +} + +// openPartial opens the file a download is kept in while it arrives and hashes +// what it already holds. Anything there that is not a regular file is removed, +// and a file longer than size is emptied: neither can be the start of this one. +func openPartial(partial string, size int64) (*os.File, int64, hash.Hash, error) { + if info, err := os.Lstat(partial); err == nil && !info.Mode().IsRegular() { + if err := os.Remove(partial); err != nil { + return nil, 0, nil, fmt.Errorf("update: %w", err) + } + } + file, err := os.OpenFile(partial, os.O_RDWR|os.O_CREATE, 0o600) + if err != nil { + return nil, 0, nil, fmt.Errorf("update: %w", err) + } + hasher := sha256.New() + offset, err := io.Copy(hasher, io.LimitReader(file, size+1)) + if err == nil && offset > size { + offset = 0 + hasher.Reset() + err = file.Truncate(0) + } + if err == nil { + _, err = file.Seek(offset, io.SeekStart) + } + if err != nil { + _ = file.Close() + return nil, 0, nil, fmt.Errorf("update: %w", err) + } + return file, offset, hasher, nil +} + +// partialName is the hidden file a download is kept in until it is complete. +// It is named by the digest, so bytes are only ever continued with the rest of +// the same file. +func partialName(digest string) string { + return ".viva-update-" + strings.ToLower(digest) + ".part" +} + +// holds reports whether path is a regular file of exactly size bytes whose +// SHA-256 is digest. +func holds(path string, size int64, digest string) bool { + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || info.Size() != size { + return false + } + file, err := os.Open(path) + if err != nil { + return false + } + defer file.Close() + hasher := sha256.New() + if written, err := io.Copy(hasher, io.LimitReader(file, size+1)); err != nil || written != size { + return false + } + return strings.EqualFold(hex.EncodeToString(hasher.Sum(nil)), digest) +} + +// rangeFrom reports whether a Content-Range header answers a request for the +// bytes from offset to the end of a file of size bytes, and nothing else. +func rangeFrom(header string, offset, size int64) bool { + spec, ok := strings.CutPrefix(header, "bytes ") + if !ok { + return false + } + span, complete, ok := strings.Cut(spec, "/") + if !ok || (complete != "*" && complete != strconv.FormatInt(size, 10)) { + return false + } + first, last, ok := strings.Cut(span, "-") + return ok && first == strconv.FormatInt(offset, 10) && last == strconv.FormatInt(size-1, 10) +} + +// temporaryStatus reports a status a host answers with while it is busy or +// restarting, after which the same request may succeed. +func temporaryStatus(status int) bool { + switch status { + case http.StatusRequestTimeout, http.StatusTooManyRequests, http.StatusInternalServerError, + http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout: + return true + } + return false +} + +// transient reports whether a failed request may succeed when tried again. A +// certificate the system does not trust will not start being trusted. +func transient(err error) bool { + var certificate *tls.CertificateVerificationError + return !errors.As(err, &certificate) +} + +func report(progress func(done, total int64), done, total int64) { if progress != nil { - progress(size, size) + progress(done, total) } - return destination, nil } type progressWriter struct { @@ -139,12 +396,69 @@ type progressWriter struct { func (writer *progressWriter) Write(data []byte) (int, error) { written, err := writer.writer.Write(data) writer.done += int64(written) - if writer.progress != nil { - writer.progress(writer.done, writer.total) - } + report(writer.progress, writer.done, writer.total) return written, err } +// watchedReader tells alive whenever bytes arrive and remembers that the +// connection, rather than the file being written, failed. +type watchedReader struct { + reader io.Reader + alive func() + failed bool +} + +func (reader *watchedReader) Read(data []byte) (int, error) { + n, err := reader.reader.Read(data) + if n > 0 { + reader.alive() + } + if err != nil && err != io.EOF { + reader.failed = true + } + return n, err +} + +// transfers lets one download at a time use a partial file, so two calls in +// this process for the same file in the same directory take turns; the second +// then finds the first one's verified file. +var transfers keyedLock + +type keyedLock struct { + mu sync.Mutex + held map[string]chan struct{} +} + +func (locks *keyedLock) lock(ctx context.Context, key string) (func(), error) { + if absolute, err := filepath.Abs(key); err == nil { + key = absolute + } + for { + locks.mu.Lock() + wait, busy := locks.held[key] + if !busy { + if locks.held == nil { + locks.held = make(map[string]chan struct{}) + } + done := make(chan struct{}) + locks.held[key] = done + locks.mu.Unlock() + return func() { + locks.mu.Lock() + delete(locks.held, key) + locks.mu.Unlock() + close(done) + }, nil + } + locks.mu.Unlock() + select { + case <-wait: + case <-ctx.Done(): + return nil, fmt.Errorf("%w: %w", ErrInterrupted, ctx.Err()) + } + } +} + // assetFileName is the name an archive is saved under: the last element of // its URL path, or a fixed name when that is not a plain file name. A backslash // is a path separator on Windows even when the URL wrote "%5C", so the name is diff --git a/update/download_resume_test.go b/update/download_resume_test.go new file mode 100644 index 000000000..cb06783e4 --- /dev/null +++ b/update/download_resume_test.go @@ -0,0 +1,439 @@ +package update + +import ( + "bytes" + "context" + "crypto/ed25519" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +// resumeServer answers each request with the handler for its number, counting +// from zero, and records the Range header every request carried. +type resumeServer struct { + *httptest.Server + mu sync.Mutex + ranges []string +} + +func (server *resumeServer) requests() []string { + server.mu.Lock() + defer server.mu.Unlock() + return append([]string(nil), server.ranges...) +} + +func newResumeServer(t *testing.T, handlers ...func(http.ResponseWriter, *http.Request)) (*resumeServer, *Client) { + t.Helper() + server := &resumeServer{} + server.Server = httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + server.mu.Lock() + index := len(server.ranges) + server.ranges = append(server.ranges, request.Header.Get("Range")) + server.mu.Unlock() + if index >= len(handlers) { + t.Errorf("unexpected request %d", index+1) + http.Error(writer, "unexpected", http.StatusInternalServerError) + return + } + handlers[index](writer, request) + })) + t.Cleanup(server.Close) + client, err := New(Config{ + FeedURL: server.URL + "/latest.json", + PublicKeys: []ed25519.PublicKey{make(ed25519.PublicKey, ed25519.PublicKeySize)}, + Current: "1.0.0", + HTTP: server.Client(), + }) + if err != nil { + t.Fatal(err) + } + return server, client +} + +// cutAfter declares the whole file, sends its first n bytes and drops the +// connection, the way a network that fails mid-transfer does. +func cutAfter(content []byte, n int) func(http.ResponseWriter, *http.Request) { + return func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write(content[:n]) + writer.(http.Flusher).Flush() + panic(http.ErrAbortHandler) + } +} + +// serveRanges answers with the file, honouring a Range header as a release +// host does. +func serveRanges(content []byte) func(http.ResponseWriter, *http.Request) { + return func(writer http.ResponseWriter, request *http.Request) { + http.ServeContent(writer, request, "app.zip", time.Time{}, bytes.NewReader(content)) + } +} + +// serveWhole answers with the whole file and ignores any Range header. +func serveWhole(content []byte) func(http.ResponseWriter, *http.Request) { + return func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + _, _ = writer.Write(content) + } +} + +func resumeContent() []byte { + return bytes.Repeat([]byte("0123456789abcdef"), 4096) // 64 KiB +} + +func assertFileHolds(t *testing.T, path string, want []byte) { + t.Helper() + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Fatalf("%s holds %d bytes that are not the file's %d", filepath.Base(path), len(got), len(want)) + } +} + +func assertOnlyEntry(t *testing.T, dir, name string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != name { + var names []string + for _, entry := range entries { + names = append(names, entry.Name()) + } + t.Fatalf("directory holds %v, want only %s", names, name) + } +} + +func TestDownloadResumesAnInterruptedTransfer(t *testing.T) { + content := resumeContent() + half := len(content) / 2 + server, client := newResumeServer(t, cutAfter(content, half), serveRanges(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + _, err := client.Download(context.Background(), asset, dir, nil) + if !errors.Is(err, ErrInterrupted) { + t.Fatalf("first Download: %v, want ErrInterrupted", err) + } + if errors.Is(err, context.Canceled) { + t.Fatalf("a dropped connection reads as a cancel: %v", err) + } + partial := filepath.Join(dir, partialName(asset.SHA256)) + info, err := os.Stat(partial) + if err != nil { + t.Fatalf("the bytes that arrived were not kept: %v", err) + } + if info.Size() != int64(half) { + t.Fatalf("kept %d bytes, want %d", info.Size(), half) + } + + var first [2]int64 + calls := 0 + path, err := client.Download(context.Background(), asset, dir, func(done, total int64) { + if calls == 0 { + first = [2]int64{done, total} + } + calls++ + }) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[0] != "" || got[1] != fmt.Sprintf("bytes=%d-", half) { + t.Fatalf("Range headers = %q, want none then bytes=%d-", got, half) + } + if first != [2]int64{int64(half), int64(len(content))} { + t.Errorf("a resumed download first reports %v, want what was kept", first) + } + assertFileHolds(t, path, content) + assertOnlyEntry(t, dir, "app.zip") +} + +func TestDownloadStartsOverWhenTheServerIgnoresTheRange(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, cutAfter(content, 1000), serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + if _, err := client.Download(context.Background(), asset, dir, nil); !errors.Is(err, ErrInterrupted) { + t.Fatalf("first Download: %v, want ErrInterrupted", err) + } + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[1] != "bytes=1000-" { + t.Fatalf("Range headers = %q", got) + } + assertFileHolds(t, path, content) + assertOnlyEntry(t, dir, "app.zip") +} + +func TestDownloadStartsOverWhenTheRangeAnswerIsAnotherPart(t *testing.T) { + content := resumeContent() + wrongRange := func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(content)-1, len(content))) + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + writer.WriteHeader(http.StatusPartialContent) + _, _ = writer.Write(content) + } + server, client := newResumeServer(t, cutAfter(content, 1000), wrongRange, serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + if _, err := client.Download(context.Background(), asset, dir, nil); !errors.Is(err, ErrInterrupted) { + t.Fatalf("first Download: %v, want ErrInterrupted", err) + } + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if got := server.requests(); len(got) != 3 || got[1] != "bytes=1000-" || got[2] != "" { + t.Fatalf("Range headers = %q, want a range and then the whole file", got) + } + assertFileHolds(t, path, content) +} + +func TestDownloadStartsOverWhenTheRangeIsRefused(t *testing.T) { + content := resumeContent() + refuse := func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", len(content))) + writer.WriteHeader(http.StatusRequestedRangeNotSatisfiable) + } + server, client := newResumeServer(t, cutAfter(content, 1000), refuse, serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + if _, err := client.Download(context.Background(), asset, dir, nil); !errors.Is(err, ErrInterrupted) { + t.Fatalf("first Download: %v, want ErrInterrupted", err) + } + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if got := server.requests(); len(got) != 3 || got[1] != "bytes=1000-" || got[2] != "" { + t.Fatalf("Range headers = %q, want a range and then the whole file", got) + } + assertFileHolds(t, path, content) + assertOnlyEntry(t, dir, "app.zip") +} + +func TestDownloadStartsOverWhenKeptBytesAreNotTheFile(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, serveRanges(content), serveRanges(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + // What a crash can leave: a file of the right length so far, but zeros. + stale := make([]byte, 5000) + if err := os.WriteFile(filepath.Join(dir, partialName(asset.SHA256)), stale, 0o600); err != nil { + t.Fatal(err) + } + + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[0] != "bytes=5000-" || got[1] != "" { + t.Fatalf("Range headers = %q, want a resume and then the whole file", got) + } + assertFileHolds(t, path, content) + assertOnlyEntry(t, dir, "app.zip") +} + +func TestDownloadRefusesTheWholeFileOnceAfterAResumeFails(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, serveRanges(content), serveRanges(content)) + asset := testAsset(server.Server, content) + asset.SHA256 = testDigest("another file") + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, partialName(asset.SHA256)), content[:5000], 0o600); err != nil { + t.Fatal(err) + } + + if _, err := client.Download(context.Background(), asset, dir, nil); !errors.Is(err, ErrChecksum) { + t.Fatalf("Download: %v, want ErrChecksum", err) + } + if got := server.requests(); len(got) != 2 { + t.Fatalf("made %d requests, want the resume and one fresh attempt", len(got)) + } + assertEmptyDirectory(t, dir) +} + +func TestDownloadReusesAVerifiedFile(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("first Download: %v", err) + } + var last [2]int64 + again, err := client.Download(context.Background(), asset, dir, func(done, total int64) { last = [2]int64{done, total} }) + if err != nil { + t.Fatalf("second Download: %v", err) + } + if again != path { + t.Errorf("second Download returned %q, want %q", again, path) + } + if got := server.requests(); len(got) != 1 { + t.Errorf("made %d requests, want the file on disk reused", len(got)) + } + if last != [2]int64{int64(len(content)), int64(len(content))} { + t.Errorf("progress = %v, want complete", last) + } +} + +func TestDownloadReplacesAFileThatIsNotTheRelease(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, serveWhole(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "app.zip"), []byte("an older release"), 0o644); err != nil { + t.Fatal(err) + } + + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("Download: %v", err) + } + if got := server.requests(); len(got) != 1 { + t.Fatalf("made %d requests, want one", len(got)) + } + assertFileHolds(t, path, content) +} + +func TestDownloadEndsAStalledTransfer(t *testing.T) { + content := resumeContent() + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + stall := func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write(content[:2000]) + writer.(http.Flusher).Flush() + select { + case <-request.Context().Done(): + case <-release: + } + } + server, client := newResumeServer(t, stall, serveRanges(content)) + client.stall = 50 * time.Millisecond + asset := testAsset(server.Server, content) + dir := t.TempDir() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _, err := client.Download(ctx, asset, dir, nil) + if !errors.Is(err, ErrInterrupted) { + t.Fatalf("stalled Download: %v, want ErrInterrupted", err) + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("a stall reads as the caller's cancel or deadline: %v", err) + } + if ctx.Err() != nil { + t.Fatal("the stall was not detected before the test's own deadline") + } + path, err := client.Download(ctx, asset, dir, nil) + if err != nil { + t.Fatalf("resumed Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[1] != "bytes=2000-" { + t.Fatalf("Range headers = %q", got) + } + assertFileHolds(t, path, content) +} + +func TestDownloadKeepsTheBytesWhenCancelled(t *testing.T) { + content := resumeContent() + release := make(chan struct{}) + t.Cleanup(func() { close(release) }) + hold := func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Length", strconv.Itoa(len(content))) + writer.WriteHeader(http.StatusOK) + _, _ = writer.Write(content[:3000]) + writer.(http.Flusher).Flush() + select { + case <-request.Context().Done(): + case <-release: + } + } + server, client := newResumeServer(t, hold, serveRanges(content)) + asset := testAsset(server.Server, content) + dir := t.TempDir() + + ctx, cancel := context.WithCancel(context.Background()) + _, err := client.Download(ctx, asset, dir, func(done, total int64) { + if done >= 3000 { + cancel() + } + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancelled Download: %v, want context.Canceled", err) + } + path, err := client.Download(context.Background(), asset, dir, nil) + if err != nil { + t.Fatalf("resumed Download: %v", err) + } + if got := server.requests(); len(got) != 2 || got[1] != "bytes=3000-" { + t.Fatalf("Range headers = %q", got) + } + assertFileHolds(t, path, content) +} + +func TestDownloadPatchResumesAnInterruptedTransfer(t *testing.T) { + content := resumeContent() + server, client := newResumeServer(t, cutAfter(content, 4096), serveRanges(content)) + asset := testAsset(server.Server, []byte("the full archive")) + patch := Patch{ + FromVersion: "0.9.0", URL: server.URL + "/downloads/app.patch", + Size: int64(len(content)), SHA256: testDigest(string(content)), + } + asset.Patches = []Patch{patch} + dir := t.TempDir() + + if _, err := client.DownloadPatch(context.Background(), asset, patch, dir, nil); !errors.Is(err, ErrInterrupted) { + t.Fatalf("first DownloadPatch: %v, want ErrInterrupted", err) + } + path, err := client.DownloadPatch(context.Background(), asset, patch, dir, nil) + if err != nil { + t.Fatalf("second DownloadPatch: %v", err) + } + if got := server.requests(); len(got) != 2 || got[1] != "bytes=4096-" { + t.Fatalf("Range headers = %q", got) + } + assertFileHolds(t, path, content) +} + +func TestDownloadCallsAServerErrorAnInterruption(t *testing.T) { + content := resumeContent() + unavailable := func(writer http.ResponseWriter, request *http.Request) { + http.Error(writer, "busy", http.StatusServiceUnavailable) + } + missing := func(writer http.ResponseWriter, request *http.Request) { + http.NotFound(writer, request) + } + server, client := newResumeServer(t, unavailable, missing) + asset := testAsset(server.Server, content) + + if _, err := client.Download(context.Background(), asset, t.TempDir(), nil); !errors.Is(err, ErrInterrupted) { + t.Errorf("503: %v, want ErrInterrupted", err) + } + _, err := client.Download(context.Background(), asset, t.TempDir(), nil) + if err == nil || errors.Is(err, ErrInterrupted) || !strings.Contains(err.Error(), "404") { + t.Errorf("404: %v, want a status error that is not an interruption", err) + } +}