From dc448f272e9a9e90c1fef861b2b1add9eab1dde3 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sun, 15 Nov 2026 17:23:23 +0800 Subject: [PATCH 01/10] feat(gfx): fit a line by cutting out its middle FitLine shortens a line at its end, so a row whose end is what tells it from the next one cannot use it: a long path loses the name that differs while the shared parent stays. FitLineMiddle keeps both ends, shares the room between them on whole characters, and remembers the cut exactly as FitLine does. Motty's completion list draws a long candidate with it (t8y2/motty#875). --- gfx/wrap.go | 107 ++++++++++++++++++++++++++++++++++++++++++----- gfx/wrap_test.go | 106 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+), 11 deletions(-) diff --git a/gfx/wrap.go b/gfx/wrap.go index 28b110cda..8f838cf73 100644 --- a/gfx/wrap.go +++ b/gfx/wrap.go @@ -150,15 +150,36 @@ func (canvas *Canvas) FitLine(line string, size, weight, width float32) string { if canvas.TextWidthWeight(line, size, weight) <= width { return line } - return canvas.cutLine(line, lineFont{size: size, weight: weight}, width) + return canvas.cutLine(line, lineFont{size: size, weight: weight}, width, false) } -// cutLine is ellipsize remembered by the canvas: the same line in the same font -// at the same width is cut once, so a control that shows it again frame after -// frame builds no string. Lines longer than fitMemoMaxLine are cut afresh every -// time, since remembering them would hold a document open on the canvas. -func (canvas *Canvas) cutLine(line string, font lineFont, width float32) string { +// FitLineMiddle is line when it fits width at font size size and weight (TextStyle.Weight), +// else line with an ellipsis where its middle was: both ends stay visible, sharing +// the room as evenly as whole characters allow, and nothing when width leaves no +// room. It is FitLine for a row whose end is as telling as its start, such as the +// path of a file or a candidate that differs from its neighbours only at the end. +// +// A cut line is remembered by the canvas exactly as FitLine remembers one. +func (canvas *Canvas) FitLineMiddle(line string, size, weight, width float32) string { + if width <= 0 { + return "" + } + if canvas.TextWidthWeight(line, size, weight) <= width { + return line + } + return canvas.cutLine(line, lineFont{size: size, weight: weight}, width, true) +} + +// cutLine is ellipsize (or ellipsizeMiddle) remembered by the canvas: the same +// line in the same font at the same width is cut once, so a control that shows +// it again frame after frame builds no string. Lines longer than fitMemoMaxLine +// are cut afresh every time, since remembering them would hold a document open +// on the canvas. +func (canvas *Canvas) cutLine(line string, font lineFont, width float32, middle bool) string { if len(line) > fitMemoMaxLine { + if middle { + return canvas.ellipsizeMiddle(line, font, width) + } return canvas.ellipsize(line, font, width) } hash := uint32(2166136261) @@ -169,14 +190,18 @@ func (canvas *Canvas) cutLine(line string, font lineFont, width float32) string // Hashing the whole word at once sends the same label at distinct widths // to the same slot, making an input and its popup evict each other. // The face and the Mono and Italic flags go in too, so a Mono and a proportional - // line of the same text do not evict each other either. - style := uint32(font.face) << 2 + // line of the same text do not evict each other either, and the middle cut has a + // flag of its own so an end cut and a middle cut of one line keep apart. + style := uint32(font.face) << 3 if font.mono { style |= 1 } if font.italic { style |= 2 } + if middle { + style |= 4 + } for _, bits := range [4]uint32{math.Float32bits(width), math.Float32bits(font.size), math.Float32bits(font.weight), style} { for shift := uint(0); shift < 32; shift += 8 { hash = (hash ^ uint32(byte(bits>>shift))) * 16777619 @@ -187,8 +212,12 @@ func (canvas *Canvas) cutLine(line string, font lineFont, width float32) string } entry := &canvas.fits[hash&(fitMemoSize-1)] generation := canvas.FontGeneration() - if entry.result == "" || entry.font != font || entry.width != width || entry.line != line || entry.generation != generation { - *entry = fitEntry{line: line, result: canvas.ellipsize(line, font, width), font: font, width: width, generation: generation} + if entry.result == "" || entry.font != font || entry.width != width || entry.line != line || entry.middle != middle || entry.generation != generation { + result := canvas.ellipsize(line, font, width) + if middle { + result = canvas.ellipsizeMiddle(line, font, width) + } + *entry = fitEntry{line: line, result: result, font: font, width: width, middle: middle, generation: generation} } return entry.result } @@ -198,6 +227,7 @@ type fitEntry struct { line, result string font lineFont width float32 + middle bool // result is a middle cut, not an end cut generation uint32 // the canvas's FontGeneration when result was cut } @@ -212,7 +242,7 @@ func (canvas *Canvas) ellipsizeCached(line string, font lineFont, width float32, // control that wraps the same text every frame builds no string. This is // the same memo FitLine uses, and it is what keeps a text field whose // placeholder is wider than the field from allocating on every paint. - return canvas.cutLine(line, font, width) + return canvas.cutLine(line, font, width, false) } generation := canvas.FontGeneration() if !cache.filled || cache.font != font || cache.width != width || cache.line != line || cache.generation != generation { @@ -372,6 +402,51 @@ func (canvas *Canvas) ellipsize(line string, font lineFont, width float32) strin return "…" } +// ellipsizeMiddle keeps both ends of line and stands an ellipsis where the +// middle was, shortening it as far as it takes to fit width. The ends share the +// room as evenly as whole characters allow, the end taking the odd character, +// and neither is cut inside a character (a base with its marks, an emoji +// sequence). +func (canvas *Canvas) ellipsizeMiddle(line string, font lineFont, width float32) string { + room := width - canvas.widthIn("…", font) + if room <= 0 { + return "…" + } + // The ends keep the largest total that fits, half the room each with the + // odd byte going to the end, and bisection measures only the few strings + // those cuts need. The whole line does not fit, so it is not offered. + end, start := 0, len(line) + for lo, hi := 0, len(line)-1; lo <= hi; { + kept := (lo + hi) / 2 + prefixEnd := clusterFloor(line, kept/2) + suffixStart := clusterCeil(line, len(line)-(kept-kept/2)) + if prefixEnd > suffixStart { + prefixEnd, suffixStart = suffixStart, prefixEnd + } + if canvas.widthIn(line[:prefixEnd]+"…"+line[suffixStart:], font) <= width { + end, start = prefixEnd, suffixStart + lo = kept + 1 + } else { + hi = kept - 1 + } + } + // Shaping can make the pieces wider together than apart: check the real + // string, and give up a character at a time until it fits. + for { + if candidate := trimSpaceRight(line[:end]) + "…" + trimSpaceLeft(line[start:]); canvas.widthIn(candidate, font) <= width { + return candidate + } + if end == 0 && start == len(line) { + return "…" + } + if end > 0 { + end = prevCluster(line, end) + } else { + start = nextCluster(line, start) + } + } +} + // runeFloor is the largest rune boundary of value at or before i. func runeFloor(value string, i int) int { if i >= len(value) { @@ -395,6 +470,16 @@ func clusterFloor(value string, i int) int { return i } +// clusterCeil is the smallest character boundary of value at or after i. +func clusterCeil(value string, i int) int { + i = runeFloor(value, max(i, 0)) + for i < len(value) && !clusterBoundary(value, i) { + _, w := utf8.DecodeRuneInString(value[i:]) + i += w + } + return i +} + // GraphemeStart returns the nearest whole-character byte boundary at or before // offset, clamped to value. It handles combining marks and emoji sequences. func GraphemeStart(value string, offset int) int { diff --git a/gfx/wrap_test.go b/gfx/wrap_test.go index 9fbc91291..63337d636 100644 --- a/gfx/wrap_test.go +++ b/gfx/wrap_test.go @@ -341,6 +341,112 @@ func TestFitLineRemembersCutLinesAndNeverMixesThemUp(t *testing.T) { } } +func TestFitLineMiddleKeepsBothEndsAndCutsOnlyTheMiddle(t *testing.T) { + canvas := wrapper() + if got := canvas.FitLineMiddle("abcde", 10, 0, 50); got != "abcde" { + t.Errorf("line that fits = %q", got) + } + // Width 185 holds 18 characters: the two ends share them evenly, and the + // end, which tells rows apart, takes the odd character when there is one. + if got := canvas.FitLineMiddle("abcdefghijklmnopqrst", 10, 0, 185); got != "abcdefgh…lmnopqrst" { + t.Errorf("middle cut = %q, want abcdefgh…lmnopqrst", got) + } + if got := canvas.FitLineMiddle("abc", 10, 0, 0); got != "" { + t.Errorf("line with no room = %q", got) + } + if got := canvas.FitLineMiddle("abcdefghijklmnopqrst", 10, 0, 5); got != "…" { + t.Errorf("line with room for the ellipsis alone = %q", got) + } +} + +// A middle cut is a prefix and a suffix of the line it shortens, cut between +// characters rather than inside one, and it fits the width it was given. It is +// checked over every width because the cut is a search, not a formula. +func TestFitLineMiddleCutsWholeCharactersAndFitsEveryWidth(t *testing.T) { + canvas := wrapper() + lines := []string{ + "src/internal/workbench/release-candidate-alpha-tarball.tar.gz", + "工程/内部/工作台/发布候选/版本说明文档.md", + "notes/👩‍💻-team/👨‍👩‍👧‍👦-photos/flag-🇯🇵-trip.txt", + "a/b/c", + } + for _, line := range lines { + for width := float32(0); width <= 700; width += 3.5 { + got := canvas.FitLineMiddle(line, 10, 0, width) + if width <= 0 { + if got != "" { + t.Fatalf("FitLineMiddle(%q, %v) = %q, want nothing", line, width, got) + } + continue + } + if got == line { + if canvas.TextWidthWeight(line, 10, 0) > width { + t.Fatalf("FitLineMiddle(%q, %v) left a line that does not fit", line, width) + } + continue + } + if got != "…" && canvas.TextWidthWeight(got, 10, 0) > width { + t.Fatalf("FitLineMiddle(%q, %v) = %q, which is wider than the room", line, width, got) + } + if strings.Count(got, "…") != 1 { + t.Fatalf("FitLineMiddle(%q, %v) = %q, want one ellipsis", line, width, got) + } + before, after, _ := strings.Cut(got, "…") + if !strings.HasPrefix(line, before) || !strings.HasSuffix(line, after) { + t.Fatalf("FitLineMiddle(%q, %v) = %q, which is not made of the line's two ends", line, width, got) + } + if len(before) > 0 && !clusterBoundary(line, len(before)) { + t.Fatalf("FitLineMiddle(%q, %v) = %q, whose start cuts a character", line, width, got) + } + if len(after) > 0 && !clusterBoundary(line, len(line)-len(after)) { + t.Fatalf("FitLineMiddle(%q, %v) = %q, whose end cuts a character", line, width, got) + } + if width >= 100 && got != "…" && (before == "" || after == "") { + t.Fatalf("FitLineMiddle(%q, %v) = %q, which keeps only one end although %v px are free", line, width, got, width) + } + } + } +} + +func TestFitLineMiddleRemembersItsCutAndKeepsItApartFromAnEndCut(t *testing.T) { + canvas := wrapper() + line := strings.Repeat("a long group name ", 10) + canvas.FitLineMiddle(line, 14, WeightRegular, 248) + if allocations := testing.AllocsPerRun(100, func() { _ = canvas.FitLineMiddle(line, 14, WeightRegular, 248) }); allocations != 0 { + t.Errorf("a remembered middle cut allocated %v times", allocations) + } + // The same line cut at its end and cut in its middle are different answers + // at the same width and font; neither may be served for the other. + if got, want := canvas.FitLine(line, 14, WeightRegular, 248), canvas.ellipsize(line, lineFont{size: 14, weight: WeightRegular}, 248); got != want { + t.Fatalf("an end cut after a middle cut = %q, want %q", got, want) + } + if got, want := canvas.FitLineMiddle(line, 14, WeightRegular, 248), canvas.ellipsizeMiddle(line, lineFont{size: 14, weight: WeightRegular}, 248); got != want { + t.Fatalf("a middle cut after an end cut = %q, want %q", got, want) + } +} + +// BenchmarkFitLineMiddleCut measures the first cut of a path long enough to be +// shortened, which is what a list row pays when the text under it changes. +func BenchmarkFitLineMiddleCut(b *testing.B) { + line := "src/internal/workbench/release-candidate-alpha-tarball.tar.gz" + for range b.N { + canvas := wrapper() + _ = canvas.FitLineMiddle(line, 10, 0, 240) + } +} + +// BenchmarkFitLineMiddleRemembered measures the paint after the first: the +// memo answers, so the row costs a lookup. +func BenchmarkFitLineMiddleRemembered(b *testing.B) { + canvas := wrapper() + line := "src/internal/workbench/release-candidate-alpha-tarball.tar.gz" + canvas.FitLineMiddle(line, 10, 0, 240) + b.ResetTimer() + for range b.N { + _ = canvas.FitLineMiddle(line, 10, 0, 240) + } +} + func TestFitLineReusesOneLabelAtDifferentControlWidths(t *testing.T) { canvas := wrapper() label := strings.Repeat("a long group name ", 10) From b984519dbfdd9aba280ab1b492740de18c081eea Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 21:50:28 +0800 Subject: [PATCH 02/10] feat(ui): panic when a list key is outside item numbers --- ui/list.go | 17 ++++++++++++++--- ui/list_test.go | 38 ++++++++++++++++++++++++++++++++++++++ ui/tree.go | 7 ------- ui/tree_test.go | 14 ++++++++++++++ 4 files changed, 66 insertions(+), 10 deletions(-) diff --git a/ui/list.go b/ui/list.go index 64c1b2187..8562fa62e 100644 --- a/ui/list.go +++ b/ui/list.go @@ -1,6 +1,7 @@ package ui import ( + "math" "runtime" "strings" "time" @@ -16,7 +17,10 @@ import ( // chose. Keep one per list in the model; the zero value is an empty list. type ListState struct { // Key names row i, so a row keeps its focus and state as rows are inserted - // above it: an item's ID, unique among the rows. Nil names a row by its index. + // above it: an item's ID, unique among the rows and from 0 to 2^31-1, the item + // numbers gfx.Index names. Nil names a row by its index. Number the items rather + // than hash them: a 32-bit hash is past 2^31-1 half the time, and a key outside + // that range panics, since every such key would name the same row. Key func(i int) int // Label is the text of row i: typing the first letters of a row's text while // the list has the keyboard focus chooses it. It is also the row's name for @@ -242,10 +246,17 @@ func (s *ListState) AtEnd() bool { return scroll != nil && scroll.AtEnd() } -// key is row i's key: its index without a Key. +// key is row i's key: its index without a Key. A key outside 0 to 2^31-1 panics: +// gfx.Index names every such number as it names item 0, so those rows would share +// one identity and a click on any of them would reach them all. A paint asks it of +// every row it declares, so it stays within the inliner's budget, which a message +// naming the key would exceed. func (s *ListState) key(i int) int { if s.Key != nil { - return s.Key(i) + i = s.Key(i) + } + if uint(i) > math.MaxInt32 { + panic("ui: a List row's key is outside 0 to 2^31-1, the numbers gfx.Index names; give ListState.Key the items' numbers, not hashes") } return i } diff --git a/ui/list_test.go b/ui/list_test.go index e2c484c4f..1f246b533 100644 --- a/ui/list_test.go +++ b/ui/list_test.go @@ -1,6 +1,7 @@ package ui_test import ( + "math" "strconv" "strings" "testing" @@ -363,6 +364,43 @@ func TestListNameAndNoTypeahead(t *testing.T) { } } +// Keys up to 2^31-1 name their rows, so a click chooses the row under it. A key +// outside that range would share item 0's name with every other such key, and a +// click on one of those rows would reach them all: the list panics instead. +func TestListKeysAreItemNumbers(t *testing.T) { + names := []string{"alpha", "beta", "gamma"} + view := func(state *ui.ListState) func(ui.C) { + state.Label = func(i int) string { return names[i] } + return func(c ui.C) { + ui.Column(c).Fill().Children(func() { + ui.List(c, state, len(names), func(row ui.ListRow) { ui.Text(row.C, names[row.Index]) }).Grow(1) + }) + } + } + + var state ui.ListState + state.Key = func(i int) int { return math.MaxInt32 - i } + d := openPage(t, view(&state)) + for _, row := range []int{1, 0, 2} { + d.click(names[row]) + if state.Selected() != row { + t.Fatalf("a click on %q chose row %d", names[row], state.Selected()) + } + } + + for _, first := range []int{math.MaxInt32 + 1, -len(names)} { + func() { + defer func() { + if recover() == nil { + t.Errorf("rows keyed from %d did not panic", first) + } + }() + state := ui.ListState{Key: func(i int) int { return first + i }} + drawPage(ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas(), view(&state)) + }() + } +} + func BenchmarkList100k(b *testing.B) { m := newListModel(100_000) page, canvas := ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas() diff --git a/ui/tree.go b/ui/tree.go index ef22b9ecb..5bfcb412b 100644 --- a/ui/tree.go +++ b/ui/tree.go @@ -205,13 +205,6 @@ func (s *TreeState) indent(theme *Theme) float32 { return 16 * theme.Metrics.ControlHeight / 32 } -func (s *TreeState) key(i int) int { - if s.Key != nil { - return s.Key(i) - } - return i -} - // row declares row i: the row element, painted by components.Tree, holding what // the caller declares after the chevron. func (s *TreeState) row(i int, rowBox Box) { diff --git a/ui/tree_test.go b/ui/tree_test.go index 12f99ac1c..29d2990fc 100644 --- a/ui/tree_test.go +++ b/ui/tree_test.go @@ -2,6 +2,7 @@ package ui_test import ( "fmt" + "math" "testing" "time" @@ -101,6 +102,19 @@ func (m *treeModel) page(c ui.C) { }) } +// A Tree names its rows by ListState.Key as a List does, so a key past 2^31-1 +// panics there too rather than give the rows one identity. +func TestTreeKeyPastTheItemNumbersPanics(t *testing.T) { + m := newTreeModel([]folder{{name: "etc", open: true, files: []string{"hosts", "passwd"}}}) + m.state.Key = func(i int) int { return math.MaxInt32 + 1 + i } + defer func() { + if recover() == nil { + t.Fatal("a Tree whose rows are keyed past 2^31-1 did not panic") + } + }() + drawPage(ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas(), m.page) +} + // The chevron opens and closes a branch; the arrows move, open and close; Enter // chooses. func TestTreeOpensMovesAndChooses(t *testing.T) { From 43407399daa71daeacc3566d2e9d005f48104f4a Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Sun, 15 Nov 2026 05:50:49 -0800 Subject: [PATCH 03/10] build: add an opt-in --cgo flag for native packages --- README.md | 8 ++++++++ cmd/viva/build.go | 21 +++++++++++++++++---- cmd/viva/build_test.go | 35 +++++++++++++++++++++++++++++++++++ cmd/viva/help.go | 4 ++-- 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index d47429375..f45ef0f73 100644 --- a/README.md +++ b/README.md @@ -276,6 +276,14 @@ Objective-C/Metal bridge and lets clang emit the other Mach-O slice. The [Build and package guide](https://vivaui.dev/en/docs/build-and-package/) covers every target, installer format and flag. +Linux and Windows builds disable cgo by default. Applications that link their +own C or Rust libraries can use `viva build --cgo` or `viva package --cgo` and +provide the target C compiler and `CGO_CFLAGS`/`CGO_LDFLAGS`. Those packages must +be checked against the system libraries and minimum operating system they +support; the explicit option does not supply a cross compiler or make native +dependencies portable. Browser builds reject `--cgo`; macOS keeps cgo enabled +for its system bridge as before. + The release link is measured, not assumed. `go-toml/v2` is used only by the `viva` command and `purego` only by the Linux backend, so neither is in a macOS or Windows program. The development reload protocol, single-instance sockets, diff --git a/cmd/viva/build.go b/cmd/viva/build.go index ad7a7093f..782e73887 100644 --- a/cmd/viva/build.go +++ b/cmd/viva/build.go @@ -37,6 +37,8 @@ type buildPlan struct { out string executable string debug bool + // cgo explicitly opts Linux and Windows applications into native dependencies. + cgo bool } // goTarget is the GOOS/GOARCH pair for a target. @@ -99,9 +101,15 @@ func (plan buildPlan) environment(base []string) []string { // default on a machine with a C compiler, and a cgo program links the C // library of the machine that built it: a Linux program built on Ubuntu // then refuses to start on a distribution with an older glibc, for a - // capability the program does not use. Pin it off so the package is the - // same whichever machine built it. - environment = append(environment, "CGO_ENABLED=0") + // capability the program does not use. Default it off so pure-Go + // applications package the same way whichever machine built them. + // Applications may link their own native libraries. Require an explicit + // option so the developer's ambient cgo setting cannot change default packages. + if plan.cgo { + environment = append(environment, "CGO_ENABLED=1") + } else { + environment = append(environment, "CGO_ENABLED=0") + } } return environment } @@ -145,6 +153,7 @@ type buildFlags struct { arch string tags string debug bool + cgo bool } func (shared *buildFlags) register(flags *flag.FlagSet, defaultTarget string) { @@ -154,6 +163,7 @@ func (shared *buildFlags) register(flags *flag.FlagSet, defaultTarget string) { flags.StringVar(&shared.arch, "arch", runtime.GOARCH, "arm64 or amd64 (not used by web)") flags.StringVar(&shared.tags, "tags", "", "comma-separated build tags, added to [build] tags") flags.BoolVar(&shared.debug, "debug", false, "keep symbols and debug information (not the release size)") + flags.BoolVar(&shared.cgo, "cgo", false, "enable application cgo on Linux and Windows (requires a target C compiler)") } // newPlan resolves flags, viva.toml and the package argument into a plan. @@ -164,6 +174,9 @@ func newPlan(shared buildFlags, packageArgument string) (buildPlan, error) { if shared.target != "web" && !contains(buildArches, shared.arch) { return buildPlan{}, fmt.Errorf("unknown architecture %q; use one of: %s", shared.arch, strings.Join(buildArches, ", ")) } + if shared.target == "web" && shared.cgo { + return buildPlan{}, errors.New("the web target does not support cgo") + } if shared.target == "darwin" && runtime.GOOS != "darwin" { return buildPlan{}, errors.New("building for darwin needs a macOS host: the Metal bridge is Objective-C and cannot be cross-compiled") } @@ -171,7 +184,7 @@ func newPlan(shared buildFlags, packageArgument string) (buildPlan, error) { if err != nil { return buildPlan{}, err } - plan := buildPlan{manifest: loaded, target: shared.target, arch: shared.arch, debug: shared.debug} + plan := buildPlan{manifest: loaded, target: shared.target, arch: shared.arch, debug: shared.debug, cgo: shared.cgo} plan.pkg = packageArgument if plan.pkg == "" { diff --git a/cmd/viva/build_test.go b/cmd/viva/build_test.go index d85f06d95..ae8631ff3 100644 --- a/cmd/viva/build_test.go +++ b/cmd/viva/build_test.go @@ -2,6 +2,7 @@ package main import ( "bytes" + "flag" "io" "os" "os/exec" @@ -161,6 +162,40 @@ func TestBuildEnvironment(t *testing.T) { } } +func TestBuildCgoOptIn(t *testing.T) { + for _, target := range []string{"linux", "windows"} { + t.Run(target, func(t *testing.T) { + var shared buildFlags + flags := flag.NewFlagSet("build", flag.ContinueOnError) + shared.register(flags, target) + if err := flags.Parse([]string{"-cgo"}); err != nil { + t.Fatal(err) + } + plan := loadPlan(t, fixture(t, notesTOML), shared, "") + base := []string{"CGO_ENABLED=0", "CC=fixture-cc", "CGO_CFLAGS=-I/fixture/include", "CGO_LDFLAGS=-L/fixture/lib -lfixture"} + environment := plan.environment(base) + if got := lastEnvironment(environment, "CGO_ENABLED"); got != "1" { + t.Errorf("explicit cgo build has CGO_ENABLED=%q, want 1", got) + } + for _, key := range []string{"CC", "CGO_CFLAGS", "CGO_LDFLAGS"} { + if got, want := lastEnvironment(environment, key), lastEnvironment(base, key); got != want { + t.Errorf("%s=%q, want %q", key, got, want) + } + } + if got := lastEnvironment(base, "CGO_ENABLED"); got != "0" { + t.Error("the build modified the caller's environment") + } + }) + } +} + +func TestWebBuildRejectsCgo(t *testing.T) { + _, err := newPlan(buildFlags{dir: fixture(t, notesTOML), target: "web", cgo: true}, "") + if err == nil || !strings.Contains(err.Error(), "does not support cgo") { + t.Fatalf("web cgo build: %v", err) + } +} + func TestNewPlanChoosesThePackageTagsAndName(t *testing.T) { dir := fixture(t, notesTOML) diff --git a/cmd/viva/help.go b/cmd/viva/help.go index c6f6e4045..817a4c411 100644 --- a/cmd/viva/help.go +++ b/cmd/viva/help.go @@ -28,8 +28,8 @@ func commands() []command { "viva.toml when there is one; the package argument overrides [app] package (or [web] package for\n" + "--target web, which also writes the loader and an index.html). macOS builds are compiled for\n" + "[mac] min_system, not for the macOS of the machine building them, and reach Cocoa through cgo;\n" + - "Linux and Windows builds use no cgo, so their programs do not depend on the C library of the\n" + - "machine that built them and a package built on a newer distribution still starts on an older one.\n" + + "Linux and Windows builds disable cgo by default. Use --cgo for application-owned native libraries;\n" + + "provide the target C compiler and link flags, and check the resulting system dependencies.\n" + "Windows release builds use the GUI subsystem; with --debug they keep the console.", run: func(arguments []string, output, errorOutput io.Writer) error { return runBuild(arguments, output, errorOutput) From 86d29ea0301079d48a306c3c44e737dbe87969c0 Mon Sep 17 00:00:00 2001 From: Lichenkang <2188718831@qq.com> Date: Sun, 15 Nov 2026 05:51:25 -0800 Subject: [PATCH 04/10] fix(package): declare the RPM runtime libraries the app loads --- cmd/viva/package_tarball.go | 16 ++++++++++++---- cmd/viva/package_tarball_test.go | 31 +++++++++++++++++++++++++++++++ tools/rpmpkg/rpmpkg.go | 3 ++- 3 files changed, 45 insertions(+), 5 deletions(-) diff --git a/cmd/viva/package_tarball.go b/cmd/viva/package_tarball.go index decd280b6..54c7b36ad 100644 --- a/cmd/viva/package_tarball.go +++ b/cmd/viva/package_tarball.go @@ -25,10 +25,18 @@ var linuxRuntimeDepends = []string{"libvulkan1", "libxcb1", "libcairo2"} // linuxArchRuntimeDepends are the same libraries under Arch's names. var linuxArchRuntimeDepends = []string{"vulkan-icd-loader", "libxcb", "cairo"} -// linuxRPMRuntimeDepends are the same libraries under the names Fedora, RHEL and -// openSUSE use. The manifest's depends are Debian names, so the .rpm does not -// take them over; an application that needs more must say so in its own code. -var linuxRPMRuntimeDepends = []string{"vulkan-loader", "libxcb", "cairo"} +// linuxRPMRuntimeDepends names the shared-library capabilities that RPM's library +// packages provide. Distribution package names differ; both supported targets are +// 64-bit. These dlopen libraries are invisible to normal ELF dependency scanning. +// GTK, IME and WebKit integrations remain optional and are not forced on every app. +var linuxRPMRuntimeDepends = []string{ + "libvulkan.so.1()(64bit)", "libxcb.so.1()(64bit)", "libcairo.so.2()(64bit)", + "libfontconfig.so.1()(64bit)", "libpango-1.0.so.0()(64bit)", + "libpangocairo-1.0.so.0()(64bit)", "libpangoft2-1.0.so.0()(64bit)", + "libgobject-2.0.so.0()(64bit)", "libxcb-cursor.so.0()(64bit)", + "libxcb-randr.so.0()(64bit)", "libxcb-render.so.0()(64bit)", + "libxcb-shape.so.0()(64bit)", "libxcb-sync.so.1()(64bit)", +} // linuxApplication describes the application for the Debian and RPM packages: // both install the same files, so they share one description. diff --git a/cmd/viva/package_tarball_test.go b/cmd/viva/package_tarball_test.go index 409dbf37f..58d28979a 100644 --- a/cmd/viva/package_tarball_test.go +++ b/cmd/viva/package_tarball_test.go @@ -275,6 +275,37 @@ func TestPackageLinuxMakesAnRPM(t *testing.T) { } } +// dlopen dependencies do not appear in the program's ELF headers. RPM must request +// their shared-library capabilities so a clean installation has the text and XCB libraries. +func TestPackageLinuxRPMDeclaresRuntimeLibraries(t *testing.T) { + for _, arch := range []struct{ goarch, rpm string }{{"amd64", "x86_64"}, {"arm64", "aarch64"}} { + t.Run(arch.goarch, func(t *testing.T) { + dir := packageLinuxFixture(t, linuxTOML, 256) + if _, err := runLinuxPackage(t, dir, "--format", "rpm", "--arch", arch.goarch); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(dir, "build", "fixture-notes-2.0.1-1."+arch.rpm+".rpm")) + if err != nil { + t.Fatal(err) + } + for _, library := range []string{ + "libvulkan.so.1", "libxcb.so.1", "libcairo.so.2", "libfontconfig.so.1", + "libpango-1.0.so.0", "libpangocairo-1.0.so.0", "libpangoft2-1.0.so.0", + "libgobject-2.0.so.0", "libxcb-cursor.so.0", "libxcb-randr.so.0", + "libxcb-render.so.0", "libxcb-shape.so.0", "libxcb-sync.so.1", + } { + capability := library + "()(64bit)" + if !bytes.Contains(data, []byte(capability+"\x00")) { + t.Errorf("RPM lacks runtime requirement %s", capability) + } + } + if bytes.Contains(data, []byte("libfoo1 (>= 1.2)")) { + t.Fatal("RPM contains a Debian-only manifest dependency") + } + }) + } +} + func TestPackageLinuxFailures(t *testing.T) { for _, test := range []struct { name, toml string diff --git a/tools/rpmpkg/rpmpkg.go b/tools/rpmpkg/rpmpkg.go index b40652b4d..1d22a58ea 100644 --- a/tools/rpmpkg/rpmpkg.go +++ b/tools/rpmpkg/rpmpkg.go @@ -42,7 +42,8 @@ type Package struct { // License is the License tag; "Unspecified" when empty. License string // Requires are the capabilities the package needs, named as the target - // distribution names them (Fedora: vulkan-loader, libxcb, cairo). + // distribution names them, including shared-library capabilities such as + // libpango-1.0.so.0()(64bit). Requires []string } From 731bdef9d3de72c953b825c08e2571624ab01b97 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:52:01 +0800 Subject: [PATCH 05/10] fix(text): keep LF labels across composition history splits --- text/editor.go | 2 +- text/lf_labels_composition.go | 4 +- text/lf_labels_history_split_test.go | 85 ++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 text/lf_labels_history_split_test.go diff --git a/text/editor.go b/text/editor.go index a946dc67a..33d53caf3 100644 --- a/text/editor.go +++ b/text/editor.go @@ -286,6 +286,7 @@ func (editor *Editor) Insert(value string) { } editor.collapse(caret) editor.composing = false + editor.releaseCompositionHistory() kind := editInsert if wasComposing { kind = editComposition @@ -293,7 +294,6 @@ func (editor *Editor) Insert(value string) { kind = editSeparate } editor.record(change, before, editor.selectionState(), kind) - editor.releaseCompositionHistory() } // Paste inserts text as one undo unit, separate from adjacent typing. diff --git a/text/lf_labels_composition.go b/text/lf_labels_composition.go index c6e153613..ca24c8ad4 100644 --- a/text/lf_labels_composition.go +++ b/text/lf_labels_composition.go @@ -41,8 +41,10 @@ func ensureLFLabelHistoryOwned(state *lfLabelState) { func compositionLFLabelEdits(state *lfLabelState, previous *rune) []lfLabelEdit { composition := &state.composition - if !composition.recorded { + // A save point can split a live composition into another undo unit. + if !composition.recorded || previous == nil { composition.prefix = composition.history[previous].edits + composition.unitOriginal = nil if len(state.pending) != 0 { composition.unitOriginal = state.pending[0].removed } else if composition.currentLF != 0 { diff --git a/text/lf_labels_history_split_test.go b/text/lf_labels_history_split_test.go new file mode 100644 index 000000000..8ddde487a --- /dev/null +++ b/text/lf_labels_history_split_test.go @@ -0,0 +1,85 @@ +package text + +import "testing" + +func TestLFLabelCompositionSplitHistoryUnitsPreserveLabels(t *testing.T) { + for _, scenario := range []struct { + name string + finish func(*Editor) + value string + labels []byte + }{ + {"paste", func(editor *Editor) { editor.Paste("c") }, "a\nbc", []byte{'W'}}, + {"separate insert", func(editor *Editor) { editor.BreakUndoGroup(); editor.Insert("c") }, "a\nbc", []byte{'W'}}, + {"save point", func(editor *Editor) { editor.SetSavePoint(); editor.SetMarkedText("\n\n", Range{}) }, "a\nb\n\n", []byte{'W', 'M', 'M'}}, + {"save point then merge", func(editor *Editor) { + editor.SetSavePoint() + editor.SetMarkedText("\n\n", Range{}) + editor.SetMarkedText("\n\n\n", Range{}) + }, "a\nb\n\n\n", []byte{'W', 'M', 'M', 'M'}}, + } { + t.Run(scenario.name, func(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'M', lfLabelPreserveReplacement) { + t.Fatal("label setup refused") + } + editor.MoveTo(editor.RuneCount(), false) + editor.SetMarkedText("\n", Range{}) + scenario.finish(editor) + editor.Unmark() + if editor.String() != scenario.value { + t.Fatalf("final text=%q, want %q", editor.String(), scenario.value) + } + assertLFLabels(t, editor, scenario.labels) + if !editor.Undo() || editor.String() != "a\nb\n" { + t.Fatalf("split unit Undo=%q", editor.String()) + } + assertLFLabels(t, editor, []byte{'W', 'M'}) + if !editor.SetLFLabels([]byte{'W', 'Z'}, 'D') { + t.Fatal("restored LF identities cannot be relabeled") + } + if !editor.Redo() || editor.String() != scenario.value { + t.Fatalf("split unit Redo=%q", editor.String()) + } + // Replacement LFs have their own identities; replay keeps their labels, + // while the relabeled removed LF must return on the next Undo. + assertLFLabels(t, editor, scenario.labels) + if !editor.Undo() || editor.String() != "a\nb\n" { + t.Fatal("repeated split Undo lost source") + } + assertLFLabels(t, editor, []byte{'W', 'Z'}) + editor.MoveTo(editor.RuneCount(), false) + editor.Insert("\n") + assertLFLabels(t, editor, []byte{'W', 'Z', 'D'}) + if !editor.Undo() || editor.String() != "a\nb\n" { + t.Fatal("new branch insertion lost its Undo") + } + assertLFLabels(t, editor, []byte{'W', 'Z'}) + }) + } +} + +func TestLFLabelCompositionSplitWithoutLFForgetsPreviousUnitLabels(t *testing.T) { + editor := NewEditor("a\nb") + if !editor.TrackLFLabels([]byte{'W'}, 'M', lfLabelPreserveReplacement) { + t.Fatal("label setup refused") + } + editor.SetSelection(Range{Start: 1, End: 2}) + editor.SetMarkedText("x", Range{}) + editor.SetSavePoint() + editor.SetMarkedText("y", Range{}) + editor.Unmark() + assertLFLabels(t, editor, nil) + if !editor.Undo() || editor.String() != "axb" { + t.Fatalf("LF-free split Undo=%q", editor.String()) + } + assertLFLabels(t, editor, nil) + if !editor.Redo() || editor.String() != "ayb" { + t.Fatalf("LF-free split Redo=%q", editor.String()) + } + assertLFLabels(t, editor, nil) + if !editor.Undo() || !editor.Undo() || editor.String() != "a\nb" { + t.Fatal("original LF source lost Undo") + } + assertLFLabels(t, editor, []byte{'W'}) +} From 47898c7d07a69478543b0a1d2b1dee9819d35704 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:52:35 +0800 Subject: [PATCH 06/10] fix(app): keep composition ownership through cached input --- app/composition_handoff_test.go | 180 ++++++++++++++++++ app/painter.go | 95 ++++----- internal/ibus/fcitx_fixture_test.go | 180 ++++++++++++++++++ .../ibus/testdata/fcitx-reference-lifetime.py | 54 ++++++ internal/ibus/testdata/fcitx-reference.py | 16 +- internal/ibus/testdata/native-fcitx-daemon.sh | 22 ++- internal/ibus/testdata/reference-client.py | 15 +- 7 files changed, 510 insertions(+), 52 deletions(-) create mode 100644 app/composition_handoff_test.go create mode 100644 internal/ibus/fcitx_fixture_test.go create mode 100644 internal/ibus/testdata/fcitx-reference-lifetime.py diff --git a/app/composition_handoff_test.go b/app/composition_handoff_test.go new file mode 100644 index 000000000..00734caa9 --- /dev/null +++ b/app/composition_handoff_test.go @@ -0,0 +1,180 @@ +package app + +import ( + "testing" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +func TestPainterTentativeHandoffRetainsInstalledOwner(t *testing.T) { + for _, policy := range []string{"document", "terminal", "secure"} { + for _, mode := range []string{"editor replacement", "cached provider", "cached external switch", "provider disabled", "target replacement", "subpixel disabled", "provider removed", "same owner", "geometry only"} { + t.Run(policy+"/"+mode, func(t *testing.T) { + first, second := text.NewEditor("abc"), text.NewEditor("other") + if !first.EnableTentativeComposition() || !second.EnableTentativeComposition() { + t.Fatal("capability refused") + } + first.Insert("!") + first.SetSelection(text.Range{Start: 1, End: 2}) + second.ApplyComposition(text.CompositionEvent{Phase: text.CompositionUpdate, Text: "incoming"}) + incoming := second.String() + current := first + var extraWidth float32 + var canvas gfx.Canvas + cached := &TextInput{Bounds: gfx.Rect{Width: 120, Height: 24}, FontSize: 13, Editor: first} + role := gfx.RoleTextField + if policy == "terminal" { + role = gfx.RoleTerminal + } + config := Config{Title: "composition handoff", Width: 200, Height: 80} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(11), gfx.Rect{Width: 120, Height: 24}, "First", gfx.HitOptions{Role: role, Autofocus: true, Secure: policy == "secure"}) + canvas.HitWithOptions(gfx.Item(12), gfx.Rect{Y: 30, Width: 120, Height: 24}, "Second", gfx.HitOptions{Role: role}) + } + config.TextInput = func(context TextInputContext) *TextInput { + if mode == "cached external switch" { + return cached + } + if current == nil { + return nil + } + bounds := context.Bounds + bounds.Width += extraWidth + if mode == "cached provider" { + *cached = TextInput{Bounds: bounds, FontSize: 13, Editor: current} + return cached + } + return &TextInput{Bounds: bounds, FontSize: 13, Editor: current} + } + owner := newTestPainter(t, &canvas, config) + owner.syncTextInput() + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextSetMarked, Text: "ni", CompositionPhase: text.CompositionUpdate}); err != nil { + t.Fatal(err) + } + if first.String() != "anic!" || !first.TentativeCompositionActive() { + t.Fatal("preedit did not start") + } + switch mode { + case "editor replacement", "cached provider": + current = second + case "cached external switch": + current, cached.Editor = second, second + case "provider disabled": + current = nil + case "target replacement": + owner.focus.Apply(gfx.EventResult{Focus: gfx.Item(12)}) + case "subpixel disabled": + extraWidth = -119.7 + case "provider removed": + owner.textInput = nil + case "geometry only": + extraWidth = 10 + } + update := owner.syncTextInput() + if mode == "same owner" || mode == "geometry only" { + if !first.TentativeCompositionActive() || first.String() != "anic!" { + t.Fatal("unchanged owner lost its live composition") + } + return + } + want := "anic!" + if policy == "terminal" { + want = "ac!" + } + if first.CompositionActive() || first.TentativeCompositionActive() || first.String() != want || first.CommittedString() != want { + t.Fatalf("outgoing owner not settled: text=%q committed=%q active=%t, want %q", first.String(), first.CommittedString(), first.CompositionActive(), want) + } + if mode == "provider disabled" || mode == "provider removed" || mode == "subpixel disabled" { + if !update.Changed || update.Input != nil || owner.textEnabled || owner.activeText != nil { + t.Fatal("disabled input did not release the native owner") + } + } + if mode == "target replacement" && owner.nativeText.State.Composing { + t.Fatal("same editor's new target published a stale composing snapshot") + } + if second.String() != incoming || !second.TentativeCompositionActive() { + t.Fatal("handoff settled the incoming editor") + } + if policy == "secure" { + if first.CanUndo() || first.CanRedo() { + t.Fatal("secure handoff retained committed history") + } + return + } + undo, redo := []string{"abc!", "abc"}, []string{"abc!", want} + if policy == "document" { + undo, redo = []string{"ac!", "abc!", "abc"}, []string{"abc!", "ac!", want} + } + for _, value := range undo { + if !first.Undo() || first.String() != value { + t.Fatalf("handoff Undo = %q, want %q", first.String(), value) + } + } + for _, value := range redo { + if !first.Redo() || first.String() != value { + t.Fatalf("handoff Redo = %q, want %q", first.String(), value) + } + } + }) + } + } +} + +func TestPainterCachedCustomHandoffPreservesProviderOwnership(t *testing.T) { + first, second := text.NewEditor("first"), text.NewEditor("second") + for _, editor := range []*text.Editor{first, second} { + editor.EnableTentativeComposition() + editor.ApplyComposition(text.CompositionEvent{Phase: text.CompositionUpdate, Text: "ni"}) + } + cached := &TextInput{State: TextStateOf(first), OnEvent: func(event TextEvent) (TextState, error) { + t.Fatal("custom owner received an unsolicited handoff event") + return TextState{}, nil + }} + var canvas gfx.Canvas + config := Config{Title: "custom cached handoff", Width: 200, Height: 80} + config.Paint = func(canvas *gfx.Canvas, size gfx.Size) { + canvas.HitWithOptions(gfx.Item(11), gfx.Rect{Width: 120, Height: 24}, "First", gfx.HitOptions{Role: gfx.RoleTextField, Autofocus: true}) + canvas.HitWithOptions(gfx.Item(12), gfx.Rect{Y: 30, Width: 120, Height: 24}, "Second", gfx.HitOptions{Role: gfx.RoleTextField}) + } + config.TextInput = func(TextInputContext) *TextInput { return cached } + owner := newTestPainter(t, &canvas, config) + owner.syncTextInput() + cached.Editor = second + owner.focus.Apply(gfx.EventResult{Focus: gfx.Item(12)}) + owner.syncTextInput() + if !first.TentativeCompositionActive() || !second.TentativeCompositionActive() { + t.Fatal("cached custom handoff settled a provider-owned or incoming transaction") + } +} + +func BenchmarkPainterTextInputSync(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("steady input") + if enabled { + editor.EnableTentativeComposition() + } + cached := &TextInput{Editor: editor, Bounds: gfx.Rect{Width: 120, Height: 24}, FontSize: 13} + var canvas gfx.Canvas + canvas.HitWithOptions(gfx.Item(11), cached.Bounds, "Field", gfx.HitOptions{Role: gfx.RoleTextField, Autofocus: true}) + owner := &painter{canvas: &canvas, textInput: func(TextInputContext) *TextInput { return cached }} + owner.focus.Sync(&canvas) + owner.syncTextInput() + if !owner.textEnabled { + b.Fatal("input not enabled") + } + b.ReportAllocs() + for b.Loop() { + owner.syncTextInput() + } + b.ReportMetric(float64(unsafe.Sizeof(painter{})), "painter-B") + }) + } +} diff --git a/app/painter.go b/app/painter.go index a913130ae..c215694df 100644 --- a/app/painter.go +++ b/app/painter.go @@ -37,11 +37,14 @@ type painter struct { onResize func(gfx.Size) // scale is the display's device pixels per logical pixel, zero when the platform // does not report it (see platform.Size): the canvas then keeps the scale it was given. - scale float32 - textInput TextInputProvider - activeText *TextInput - onTextEvent platform.TextHandler - textEpoch uint64 + scale float32 + textInput TextInputProvider + activeText *TextInput + // activeEditor remembers the installed owner independently of a provider's + // reusable TextInput, which the application may mutate between frames. + activeEditor *text.Editor + onTextEvent platform.TextHandler + textEpoch uint64 // placing is a press on a text field that lays its rows out itself being held // (see placeCaret), from the rune index placeAnchor. placeUnit is the click // unit a multi-click press took (2 a word, 3 a line) and placeUnitRange the @@ -1237,14 +1240,10 @@ func (painter *painter) focusedTextField() (TextInputContext, gfx.TextPlacement, func (painter *painter) syncTextInput() platform.TextInputUpdate { if painter.textInput == nil { - painter.noteKeyboardTarget(gfx.ID{}, false) - return platform.TextInputUpdate{} + return painter.disableTextInput() } context, placement, hitIndex := painter.focusedTextField() - var previousEditor *text.Editor - if painter.activeText != nil { - previousEditor = painter.activeText.Editor - } + previousEditor := painter.activeEditor var input *TextInput if !context.ID.IsZero() && !context.ReadOnly { input = painter.textInput(context) @@ -1256,42 +1255,17 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { if input != nil { nextEditor = input.Editor } - // A different target ends the composition it started, even when the - // application reuses the same editor: the native input's owner changed - // under the preedit. Settle it here in the shared layer so every platform - // follows the same policy and the adapters stay thin. A document keeps - // what the user sees as committed text; a terminal preedit surface - // discards it, because that preedit was never delivered to the - // application. handoff := previousEditor != nil && painter.textEnabled && (previousEditor != nextEditor || painter.nativeText.Target != context.ID) - if handoff && previousEditor.TentativeCompositionActive() { - phase := text.CompositionCommit - if painter.nativeText.Terminal { - phase = text.CompositionCancel - } - previousEditor.ApplyComposition(text.CompositionEvent{Phase: phase}) - if phase == text.CompositionCommit && painter.nativeText.Secure { - // Committed text left the tentative boundary, so the secure - // invariant applies exactly as it does to an ordinary accepted edit. - previousEditor.ClearHistory() - } + if handoff { + painter.settleTextInput() } if input != nil && input.Editor != nil { input.State = TextStateOf(input.Editor) } - if handoff { - previousEditor.BreakUndoGroup() - } painter.noteKeyboardTarget(context.ID, input != nil && context.Terminal && input.KeyReleases) if input == nil { - painter.activeText = nil - if !painter.textEnabled { - return platform.TextInputUpdate{} - } - painter.textEpoch++ - painter.textEnabled = false - return platform.TextInputUpdate{Changed: true} + return painter.disableTextInput() } // What the application leaves unset comes from the component's declaration. bounds, fontSize, weight, tint := input.Bounds, input.FontSize, input.Weight, input.Color @@ -1324,13 +1298,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { } if bounds.Width <= 0 || bounds.Height <= 0 || roundPixel(bounds.Width) <= 0 || roundPixel(bounds.Height) <= 0 { - painter.activeText = nil - if !painter.textEnabled { - return platform.TextInputUpdate{} - } - painter.textEpoch++ - painter.textEnabled = false - return platform.TextInputUpdate{Changed: true} + return painter.disableTextInput() } var cellWidth, baseline float32 if context.Terminal || context.TypeAhead { @@ -1372,6 +1340,7 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { } } painter.activeText = input + painter.activeEditor = nextEditor if !painter.textEnabled || previousEditor != nextEditor || painter.nativeText.Target != native.Target || painter.nativeText.Multiline != native.Multiline || painter.nativeText.Secure != native.Secure || painter.nativeText.Terminal != native.Terminal || painter.nativeText.Placed != native.Placed || @@ -1386,6 +1355,40 @@ func (painter *painter) syncTextInput() platform.TextInputUpdate { return platform.TextInputUpdate{Changed: true, Input: &painter.nativeText} } +// settleTextInput ends the installed owner's composition before a handoff or +// disable. Documents keep the visible text; terminal preedit was never sent +// to the application and is discarded. State/OnEvent providers own settlement. +func (painter *painter) settleTextInput() { + editor := painter.activeEditor + painter.activeEditor = nil + if editor == nil || !painter.textEnabled { + return + } + if editor.TentativeCompositionActive() { + phase := text.CompositionCommit + if painter.nativeText.Terminal { + phase = text.CompositionCancel + } + editor.ApplyComposition(text.CompositionEvent{Phase: phase}) + if phase == text.CompositionCommit && painter.nativeText.Secure { + editor.ClearHistory() + } + } + editor.BreakUndoGroup() +} + +func (painter *painter) disableTextInput() platform.TextInputUpdate { + painter.settleTextInput() + painter.noteKeyboardTarget(gfx.ID{}, false) + painter.activeText = nil + if !painter.textEnabled { + return platform.TextInputUpdate{} + } + painter.textEpoch++ + painter.textEnabled = false + return platform.TextInputUpdate{Changed: true} +} + func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextState, error) { painter.tap.Cancel() active := painter.activeText diff --git a/internal/ibus/fcitx_fixture_test.go b/internal/ibus/fcitx_fixture_test.go new file mode 100644 index 000000000..ac8ba6701 --- /dev/null +++ b/internal/ibus/fcitx_fixture_test.go @@ -0,0 +1,180 @@ +//go:build darwin || linux + +package ibus + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func TestFcitxFixtureWaitsForTheExportedInputContextInterface(t *testing.T) { + runFcitxFixture(t, false, false) +} + +func TestFcitxFixtureCancellationKillsOwnedProcesses(t *testing.T) { + runFcitxFixture(t, true, false) +} + +func TestFcitxFixtureIsolatesPrivilegedCompositorBindings(t *testing.T) { + runFcitxFixture(t, false, true) +} + +func TestFcitxReferenceRetainsNativeSignalArguments(t *testing.T) { + if _, err := os.Stat("/usr/bin/python3"); err != nil { + t.Skip("reference fixture requires Python") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + command := exec.CommandContext(ctx, "/usr/bin/python3", "testdata/fcitx-reference-lifetime.py", "testdata/fcitx-reference.py", "testdata/reference-client.py") + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("reference signal lifetime: %v\n%s", err, output) + } +} + +func runFcitxFixture(t *testing.T, block, isolate bool) { + t.Helper() + if _, err := os.Stat("/usr/bin/python3"); err != nil { + t.Skip("fixture requires Python") + } + directory := t.TempDir() + write := func(name, content string) string { + t.Helper() + file := filepath.Join(directory, name) + if err := os.WriteFile(file, []byte(content), 0700); err != nil { + t.Fatal(err) + } + return file + } + daemon, err := os.ReadFile("testdata/native-fcitx-daemon.sh") + if err != nil { + t.Fatal(err) + } + script := write("native-fcitx-daemon.sh", string(daemon)) + write("fcitx5", `#!/bin/sh +if [ "$1" = --version ]; then + echo fixture +else + if [ "$VIVA_FIXTURE_REQUIRE_ISOLATION" = true ]; then + case "$*" in + *--disable=*waylandim*) ;; + *) echo 'privileged compositor binding was not isolated' >&2; exit 42 ;; + esac + fi + echo $$ >"$VIVA_FIXTURE_DAEMON_PID" + exec sleep 30 +fi +`) + write("dconf", "#!/bin/sh\nexit 0\n") + write("reference-client.py", "import sys\nprint('{}' if '--keycodes' in sys.argv else 'activation fixture')\n") + write("gdbus", `#!/bin/sh +if [ "$1" = call ]; then + echo '(true,)' +elif [ "$1" = introspect ]; then + if [ ! -f "$VIVA_FIXTURE_EXPORTED" ]; then + if [ "$VIVA_FIXTURE_BLOCK" = true ]; then sleep 2; fi + touch "$VIVA_FIXTURE_EXPORTED" + echo '' + else + touch "$VIVA_FIXTURE_READY" + echo '' + fi +else + exit 2 +fi +`) + client := write("client", "#!/bin/sh\nif [ ! -f \"$VIVA_FIXTURE_READY\" ]; then echo 'client ran before the input context object was exported' >&2; exit 42; fi\necho $$ >\"$VIVA_FIXTURE_CLIENT_PID\"\nif [ \"$VIVA_FIXTURE_BLOCK\" = true ]; then exec sleep 30; fi\n") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + command := exec.CommandContext(ctx, "sh", script) + // Every fixture child stays in this test's process group, including a + // client or daemon that is blocked when cancellation stops the shell. + command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + command.Cancel = func() error { return syscall.Kill(-command.Process.Pid, syscall.SIGTERM) } + command.WaitDelay = 5 * time.Second + readPID := func(name string) int { + data, _ := os.ReadFile(filepath.Join(directory, name)) + pid, _ := strconv.Atoi(strings.TrimSpace(string(data))) + return pid + } + processDone, watcherDone, cancelledWhenReady := make(chan struct{}), make(chan struct{}), make(chan struct{}) + if block { + // Cancel only after cold startup reached the client. The outer + // deadline is a safety bound, not the event this test exercises. + go func() { + defer close(watcherDone) + ticker := time.NewTicker(5 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-processDone: + return + case <-ticker.C: + if readPID("daemon.pid") > 0 && readPID("client.pid") > 0 { + close(cancelledWhenReady) + cancel() + return + } + } + } + }() + } else { + close(watcherDone) + } + defer func() { + cancel() + <-watcherDone + }() + t.Cleanup(func() { + if command.Process != nil { + _ = syscall.Kill(-command.Process.Pid, syscall.SIGKILL) + } + for _, name := range []string{"daemon.pid", "client.pid"} { + if pid := readPID(name); pid > 0 { + _ = syscall.Kill(pid, syscall.SIGKILL) + } + } + }) + command.Env = append(os.Environ(), "PATH="+directory+string(os.PathListSeparator)+os.Getenv("PATH"), "XDG_RUNTIME_DIR="+filepath.Join(directory, "runtime"), "DBUS_SESSION_BUS_ADDRESS=fixture", "VIVA_FCITX_BACKEND=x11", "VIVA_FCITX_REFERENCE=0", "VIVA_FCITX_GTK_REFERENCE=0", "VIVA_FCITX_TEST_BINARY="+client, "VIVA_FIXTURE_EXPORTED="+filepath.Join(directory, "exported"), "VIVA_FIXTURE_READY="+filepath.Join(directory, "ready"), "VIVA_FIXTURE_DAEMON_PID="+filepath.Join(directory, "daemon.pid"), "VIVA_FIXTURE_CLIENT_PID="+filepath.Join(directory, "client.pid"), "VIVA_FIXTURE_BLOCK="+strconv.FormatBool(block)) + command.Env = append(command.Env, "VIVA_FIXTURE_REQUIRE_ISOLATION="+strconv.FormatBool(isolate)) + output, err := command.CombinedOutput() + close(processDone) + <-watcherDone + if !block && err != nil { + t.Fatalf("fixture did not wait for the context interface: %v\n%s", err, output) + } + if block { + select { + case <-cancelledWhenReady: + default: + t.Fatalf("fixture never reached client-ready cancellation: %v\n%s", err, output) + } + if err == nil || ctx.Err() != context.Canceled { + t.Fatalf("fixture did not exercise explicit cancellation: %v\n%s", err, output) + } + } + deadline := time.Now().Add(5 * time.Second) + for syscall.Kill(-command.Process.Pid, 0) != syscall.ESRCH { + if time.Now().After(deadline) { + t.Fatal("fixture left an owned process group running") + } + time.Sleep(5 * time.Millisecond) + } + for _, name := range []string{"daemon.pid", "client.pid"} { + pid := readPID(name) + if pid <= 0 { + t.Fatalf("fixture did not start its owned %s", name) + } + if syscall.Kill(pid, 0) != syscall.ESRCH { + t.Fatalf("fixture left its owned %s running", name) + } + } +} diff --git a/internal/ibus/testdata/fcitx-reference-lifetime.py b/internal/ibus/testdata/fcitx-reference-lifetime.py new file mode 100644 index 000000000..682b60d1a --- /dev/null +++ b/internal/ibus/testdata/fcitx-reference-lifetime.py @@ -0,0 +1,54 @@ +import ast +import gc +import sys +import weakref + + +observed = [] + + +class SignalText: + def __init__(self): + observed.append(weakref.ref(self)) + + def get_text(self): + return "ni" + + +def check(source_path): + with open(source_path, encoding="utf-8") as source: + tree = ast.parse(source.read()) + printed = [] + namespace = {"events": [], "signal_texts": [], "print": lambda *args, **kwargs: printed.append(list(args))} + definitions = ast.Module(body=[node for node in tree.body if isinstance(node, ast.FunctionDef)], type_ignores=[]) + exec(compile(ast.fix_missing_locations(definitions), source_path, "exec"), namespace) + callbacks = {} + for node in ast.walk(tree): + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "connect": + if isinstance(node.args[0], ast.Constant) and isinstance(node.args[1], ast.Lambda): + callbacks[node.args[0].value] = eval(compile(ast.Expression(node.args[1]), source_path, "eval"), namespace) + fcitx = "update-preedit-text-with-mode" in callbacks + cases = [ + ("update-preedit-text", (2, True), ["update" if fcitx else "reference preedit", "ni", 2, True]), + ("commit-text", (), ["commit" if fcitx else "reference commit", "ni"]), + ] + if fcitx: + cases.append(("update-preedit-text-with-mode", (2, True, 1), ["mode", "ni", 2, True, 1])) + for signal, tail, expected in cases: + namespace["events"].clear() + printed.clear() + callbacks[signal](None, SignalText(), *tail) + gc.collect() + if observed[-1]() is None: + raise AssertionError(f"{source_path}/{signal}: native signal text released before emitter returned") + if (namespace["events"] or printed) != [expected]: + raise AssertionError(f"{source_path}/{signal}: reference observation changed") + namespace["signal_texts"].clear() + gc.collect() + if observed[-1]() is not None: + raise AssertionError(f"{source_path}/{signal}: native signal text leaked after dispatch") + print(f"{source_path}/{signal}: retained through emitter, released after dispatch") + + +for source_path in sys.argv[1:]: + check(source_path) diff --git a/internal/ibus/testdata/fcitx-reference.py b/internal/ibus/testdata/fcitx-reference.py index e34ace174..ef45631d1 100644 --- a/internal/ibus/testdata/fcitx-reference.py +++ b/internal/ibus/testdata/fcitx-reference.py @@ -15,10 +15,12 @@ if backend != expected: raise RuntimeError(f"native backend {backend}, expected {expected}") print("reference backend", backend, flush=True) +print("reference GI version", gi.__version__, flush=True) codes = {int(key): value for key, value in json.loads(os.environ["VIVA_IBUS_KEYCODES"]).items()} IBus.init() main = GLib.MainContext.default() requested = os.environ.get("VIVA_FCITX_ENGINE", "pinyin") +signal_texts = [] def drain(duration=0.05): @@ -29,6 +31,13 @@ def drain(duration=0.05): time.sleep(0.001) +def native_text(value): + # libibus checks the floating object after signal emission returns. + # Keep the GI wrapper alive until native dispatch has finished. + signal_texts.append(value) + return value.get_text() + + for client_mode in [False, True]: for ending in ["commit", "escape", "reset", "focus-out"]: bus = IBus.Bus() @@ -39,9 +48,9 @@ def drain(duration=0.05): context.set_capabilities(IBus.Capabilite.PREEDIT_TEXT | IBus.Capabilite.FOCUS) if client_mode: context.set_client_commit_preedit(True) - context.connect("update-preedit-text", lambda _, text, cursor, visible: events.append(["update", text.get_text(), cursor, visible])) - context.connect("update-preedit-text-with-mode", lambda _, text, cursor, visible, mode: events.append(["mode", text.get_text(), cursor, visible, mode])) - context.connect("commit-text", lambda _, text: events.append(["commit", text.get_text()])) + context.connect("update-preedit-text", lambda _, text, cursor, visible: events.append(["update", native_text(text), cursor, visible])) + context.connect("update-preedit-text-with-mode", lambda _, text, cursor, visible, mode: events.append(["mode", native_text(text), cursor, visible, mode])) + context.connect("commit-text", lambda _, text: events.append(["commit", native_text(text)])) connection = context.get_connection() connection.call_sync("org.freedesktop.IBus", context.get_object_path(), "org.freedesktop.IBus.InputContext", "FocusIn", GLib.Variant("()", ()), None, Gio.DBusCallFlags.NONE, 1000, None) subprocess.run(["fcitx5-remote", "--check", "-s", requested], check=True, timeout=2) @@ -66,3 +75,4 @@ def drain(duration=0.05): print("reference settled", client_mode, ending, json.dumps(events, ensure_ascii=False), flush=True) context.destroy() drain(0.01) + signal_texts.clear() diff --git a/internal/ibus/testdata/native-fcitx-daemon.sh b/internal/ibus/testdata/native-fcitx-daemon.sh index ce8d00b42..a951abe53 100644 --- a/internal/ibus/testdata/native-fcitx-daemon.sh +++ b/internal/ibus/testdata/native-fcitx-daemon.sh @@ -36,7 +36,8 @@ else fi export IBUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS export IBUS_ADDRESS_FILE=$task_dir/ibus-address -fcitx5 -D --disable=notificationitem,notifications,classicui,xim > "$task_dir/fcitx.log" 2>&1 & +# This fixture uses GTK/IBus over D-Bus, not Weston's privileged IM binding. +fcitx5 -D --disable=notificationitem,notifications,classicui,xim,waylandim > "$task_dir/fcitx.log" 2>&1 & daemon_pid=$! attempt=0 while ! gdbus call --timeout 1 --session --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.NameHasOwner org.freedesktop.IBus | grep -q true; do @@ -45,6 +46,25 @@ while ! gdbus call --timeout 1 --session --dest org.freedesktop.DBus --object-pa [ "$attempt" -lt 100 ] sleep 0.02 done +# The bus name can be owned before Fcitx exports its IBus object. +attempt=0 +while ! gdbus introspect --session --dest org.freedesktop.IBus --object-path /org/freedesktop/IBus --xml 2>/dev/null | /usr/bin/python3 -c ' +import sys +import xml.etree.ElementTree as ET +try: + root = ET.parse(sys.stdin).getroot() +except ET.ParseError: + sys.exit(1) +ready = any(interface.get("name") == "org.freedesktop.IBus" and + any(method.get("name") == "CreateInputContext" for method in interface.findall("method")) + for interface in root.findall("interface")) +sys.exit(0 if ready else 1) +'; do + kill -0 "$daemon_pid" + attempt=$((attempt + 1)) + [ "$attempt" -lt 100 ] + sleep 0.02 +done fcitx5 --version VIVA_IBUS_KEYCODES=$(/usr/bin/python3 "$fixture_dir/reference-client.py" --keycodes) export VIVA_IBUS_KEYCODES diff --git a/internal/ibus/testdata/reference-client.py b/internal/ibus/testdata/reference-client.py index 6fdfe0e86..9e9247b7e 100644 --- a/internal/ibus/testdata/reference-client.py +++ b/internal/ibus/testdata/reference-client.py @@ -44,6 +44,7 @@ sys.exit(0) IBus.init() +print("reference GI version", gi.__version__, flush=True) bus = IBus.Bus() print("reference connected", bus.is_connected(), flush=True) context = bus.create_input_context("viva-reference-probe") @@ -70,8 +71,17 @@ main.iteration(False) time.sleep(0.005) print("reference engine", engine.get_name(), flush=True) -context.connect("update-preedit-text", lambda ctx, text, cursor, visible: print("reference preedit", text.get_text(), cursor, visible, flush=True)) -context.connect("commit-text", lambda ctx, text: print("reference commit", text.get_text(), flush=True)) +signal_texts = [] + + +def native_text(value): + # libibus still checks the floating object after signal callbacks return. + signal_texts.append(value) + return value.get_text() + + +context.connect("update-preedit-text", lambda ctx, text, cursor, visible: print("reference preedit", native_text(text), cursor, visible, flush=True)) +context.connect("commit-text", lambda ctx, text: print("reference commit", native_text(text), flush=True)) if requested == "hangul": print("reference Hangul mode", context.process_key_event(0xff31, keycodes[0xff31], 0), flush=True) for key in ("rksk " if requested == "hangul" else "nihao "): @@ -85,3 +95,4 @@ main.iteration(False) time.sleep(0.001) context.destroy() +signal_texts.clear() From c221e818645a0fb173a83b4cdde3fd93a7d6a58c Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:53:10 +0800 Subject: [PATCH 07/10] fix(linux): settle tentative text when retiring an IBus mode --- .github/workflows/text-input.yml | 4 +- internal/platform/linux/ime_linux.go | 8 ++ .../linux/ime_retirement_linux_test.go | 111 ++++++++++++++++++ 3 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 internal/platform/linux/ime_retirement_linux_test.go diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index f78cde5a2..fceae1a94 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -80,7 +80,7 @@ jobs: if: runner.os == 'Linux' run: | go test -c -tags vivagtk -o "$RUNNER_TEMP/viva-ibus-frontend.test" ./internal/platform/linux - xvfb-run -a env VIVA_IBUS_TEST_BINARY="$RUNNER_TEMP/viva-ibus-frontend.test" VIVA_IBUS_TEST_RUN='^TestNativeIBus(Frontend|OwnerReactivation|FactoryDeclinedShortcut)$' sh internal/ibus/testdata/native-service.sh libpinyin hangul + xvfb-run -a env VIVA_IBUS_TEST_BINARY="$RUNNER_TEMP/viva-ibus-frontend.test" VIVA_IBUS_TEST_RUN='^TestNativeIBus(Frontend|OwnerReactivation|FactoryDeclinedShortcut|UnsupportedModeRetirement)$' sh internal/ibus/testdata/native-service.sh libpinyin hangul - name: Fcitx native context retirement if: runner.os == 'Linux' run: | @@ -94,7 +94,7 @@ jobs: run: | for backend in x11 wayland; do for engine in pinyin hangul; do - xvfb-run -a env VIVA_FCITX_ENGINE="$engine" VIVA_FCITX_REFERENCE=1 VIVA_FCITX_GTK_REFERENCE=1 VIVA_GTK_IME_NATIVE=1 G_DEBUG=fatal-criticals VIVA_FCITX_TEST_BINARY="$RUNNER_TEMP/viva-ibus-frontend.test" VIVA_IBUS_TEST_RUN='^Test(NativeIBus(Frontend|OwnerReactivation|FactoryDeclinedShortcut)|GTKNativeFcitx(Composition|WindowClose))$' sh internal/ibus/testdata/native-fcitx-service.sh "$backend" + xvfb-run -a env VIVA_FCITX_ENGINE="$engine" VIVA_FCITX_REFERENCE=1 VIVA_FCITX_GTK_REFERENCE=1 VIVA_GTK_IME_NATIVE=1 G_DEBUG=fatal-criticals VIVA_FCITX_TEST_BINARY="$RUNNER_TEMP/viva-ibus-frontend.test" VIVA_IBUS_TEST_RUN='^Test(NativeIBus(Frontend|OwnerReactivation|FactoryDeclinedShortcut|UnsupportedModeRetirement)|GTKNativeFcitx(Composition|WindowClose))$' sh internal/ibus/testdata/native-fcitx-service.sh "$backend" done done - name: Linux text callback ordering diff --git a/internal/platform/linux/ime_linux.go b/internal/platform/linux/ime_linux.go index c249532a7..53ada4a52 100644 --- a/internal/platform/linux/ime_linux.go +++ b/internal/platform/linux/ime_linux.go @@ -182,12 +182,20 @@ func (ime *linuxIME) sync() { ime.active = false if ime.engineComposing || ime.phase != nil && ime.phase.session { if err := ime.reset(); err != nil { + if ime.context != context || ime.epoch != epoch || !ime.sameOwner() { + return + } // A reset the engine cannot describe is not an application // failure: some engines keep sending legacy modes or an // unknown one, and refusing to guess is deliberate. Retire // this native session, keep the text the field already // shows, and let sync open a fresh context next frame. + keep := ime.phase != nil && ime.phase.session ime.retire() + if keep { + ime.apply(platform.TextEvent{Kind: platform.TextUnmark, CompositionPhase: text.CompositionCommit}) + } + ime.app.checkInputMethod() return } } diff --git a/internal/platform/linux/ime_retirement_linux_test.go b/internal/platform/linux/ime_retirement_linux_test.go new file mode 100644 index 000000000..50cf66e3c --- /dev/null +++ b/internal/platform/linux/ime_retirement_linux_test.go @@ -0,0 +1,111 @@ +package linux + +import ( + "os" + "testing" + + "github.com/vivaui/viva/internal/ibus" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/text" +) + +func TestIBusTentativeUnsupportedResetSettlesEditorBeforeRetirement(t *testing.T) { + for _, mode := range []string{"missing", "unknown"} { + for _, visibility := range []string{"visible", "hidden", "empty"} { + t.Run(mode+"/"+visibility, func(t *testing.T) { + h := newTentativeIMEHarness(t) + event := ibus.PreeditEvent{Text: "ni", Cursor: 2, Visible: true} + if mode == "unknown" { + event.HasMode, event.Mode = true, 99 + } + h.preedit(t, event) + want := "anic" + if visibility == "hidden" { + h.preedit(t, ibus.PreeditEvent{Kind: ibus.PreeditHide}) + want = "ac" + } else if visibility == "empty" { + event.Text, event.Cursor = "", 0 + h.preedit(t, event) + want = "ac" + } + if !h.ime.composing() { + t.Fatal("native session did not start") + } + h.ime.setFocused(false) + if h.ime.app.firstErr != nil || h.ime.context != nil || !h.context.closed { + t.Fatal("unsupported mode did not retire the context without disabling input") + } + if h.editor.CompositionActive() || h.editor.TentativeCompositionActive() || h.editor.String() != want || h.editor.CommittedString() != want || h.input.state != platform.EditorState(h.editor) { + t.Fatalf("retired context left unsettled editor: value=%q committed=%q active=%t tentative=%t", h.editor.String(), h.editor.CommittedString(), h.editor.CompositionActive(), h.editor.TentativeCompositionActive()) + } + last := h.events[len(h.events)-1] + if last.Kind != platform.TextUnmark || last.CompositionPhase != text.CompositionCommit { + t.Fatalf("retirement guessed an engine outcome: %+v", last) + } + count := len(h.events) + h.preedit(t, nativeMode("stale", ibus.PreeditModeClear)) + h.ime.commit("stale") + if h.editor.String() != want || len(h.events) != count { + t.Fatal("retired context delivered a stale tail") + } + if visibility == "visible" && (!h.editor.Undo() || h.editor.String() != "ac") { + t.Fatalf("committed preedit Undo = %q, want ac", h.editor.String()) + } + if !h.editor.Undo() || h.editor.String() != "abc" { + t.Fatalf("ordinary selection deletion Undo = %q, want abc", h.editor.String()) + } + }) + } + } +} + +func TestNativeIBusUnsupportedModeRetirement(t *testing.T) { + if os.Getenv("VIVA_IBUS_NATIVE") != "1" { + t.Skip("native retirement requires a private input-method daemon") + } + for _, mode := range []string{"missing", "unknown"} { + t.Run(mode, func(t *testing.T) { + bus, err := ibus.Dial() + if err != nil { + t.Fatal(err) + } + defer bus.Close() + h := newTentativeIMEHarness(t) + app := &linuxApplication{ibus: bus, ibusTried: true} + router := h.ime.router + router.ime = nil + ime := app.newIME(&window{}, h.input, router) + if ime == nil || ime.phase == nil { + t.Fatal("native phase context missing") + } + defer ime.close() + ime.origin = h.ime.origin + h.ime = ime + h.focus(t) + selectNativeIBusEngine(t, bus, ime.context, os.Getenv("VIVA_IBUS_ENGINE")) + original := ime.context + // Inject only the unsupported signal; context creation, retirement + // and reopening use the real daemon and production factory. + event := ibus.PreeditEvent{Text: "ni", Cursor: 2, Visible: true} + if mode == "unknown" { + event.HasMode, event.Mode = true, 99 + } + ime.nativePreedit(event) + ime.setFocused(false) + if h.editor.String() != "anic" || h.editor.CompositionActive() || h.editor.TentativeCompositionActive() || h.input.state != platform.EditorState(h.editor) { + t.Fatalf("unsupported native retirement left unsettled editor: %+v", platform.EditorState(h.editor)) + } + ime.sync() + if ime.dead || ime.context == nil || ime.context == original || ime.phase == nil || ime.phase.session || app.firstErr != nil { + t.Fatal("retirement did not retain a fresh native context") + } + ime.setFocused(true) + selectNativeIBusEngine(t, bus, ime.context, os.Getenv("VIVA_IBUS_ENGINE")) + ime.nativePreedit(nativeMode("x", ibus.PreeditModeClear)) + ime.commit("z") + if h.editor.String() != "anizc" || h.editor.CompositionActive() || !ime.active || app.firstErr != nil { + t.Fatalf("fresh context did not accept subsequent composition: %q", h.editor.String()) + } + }) + } +} From d01d7f55980b77fdea60be2586aac1f169ae15d7 Mon Sep 17 00:00:00 2001 From: ccq <76206374+caichangqing1120@users.noreply.github.com> Date: Sun, 15 Nov 2026 21:53:38 +0800 Subject: [PATCH 08/10] feat(windows): emit opt-in tentative IME phases --- .github/workflows/text-input.yml | 51 +- .../windows/composition_cost_windows_test.go | 42 + .../composition_events_windows_test.go | 887 ++++++++++++++++++ internal/platform/windows/ime_windows.go | 198 +++- internal/platform/windows/window_windows.go | 45 +- 5 files changed, 1181 insertions(+), 42 deletions(-) create mode 100644 internal/platform/windows/composition_cost_windows_test.go create mode 100644 internal/platform/windows/composition_events_windows_test.go diff --git a/.github/workflows/text-input.yml b/.github/workflows/text-input.yml index fceae1a94..21dd8fc4c 100644 --- a/.github/workflows/text-input.yml +++ b/.github/workflows/text-input.yml @@ -48,6 +48,52 @@ jobs: with: go-version-file: go.mod cache: true + - name: Windows IME event dispatch cost + if: runner.os == 'Windows' + env: + IME_COST_BASE: ${{ github.event.pull_request.base.sha || github.event.before || github.sha }} + GOWORK: 'off' + run: | + $reference = $env:IME_COST_BASE + if (-not $reference -or $reference -match '^0+$') { $reference = $env:GITHUB_SHA } + $workspace = $PWD.Path + $directory = Join-Path $env:RUNNER_TEMP ("viva-ime-cost-" + $env:GITHUB_RUN_ID + "-" + $env:GITHUB_RUN_ATTEMPT) + $benchmark = 'internal/platform/windows/composition_cost_windows_test.go' + if (Test-Path $directory) { throw 'cost worktree already exists' } + git fetch --no-tags --depth=1 origin $reference + if ($LASTEXITCODE -ne 0) { throw 'could not fetch cost baseline' } + git worktree add --detach $directory $reference + if ($LASTEXITCODE -ne 0) { throw 'could not create cost worktree' } + try { + Copy-Item $benchmark (Join-Path $directory $benchmark) -Force + $sourceHash = (Get-FileHash -Algorithm SHA256 $benchmark).Hash + $baseHash = (Get-FileHash -Algorithm SHA256 (Join-Path $directory $benchmark)).Hash + if ($sourceHash -ne $baseHash) { throw 'benchmark source changed' } + $benchmarkBlob = git rev-parse ("HEAD:" + $benchmark) + if ($LASTEXITCODE -ne 0) { throw 'benchmark blob is unavailable' } + Write-Output "IME cost benchmark sha256=$sourceHash" + Write-Output "IME cost benchmark blob=$benchmarkBlob" + Write-Output "IME cost OS=$([Environment]::OSVersion.VersionString) arch=$env:PROCESSOR_ARCHITECTURE cpu=$env:PROCESSOR_IDENTIFIER" + go version + for ($pair = 1; $pair -le 5; $pair++) { + Push-Location $directory + try { + Write-Output "IME cost variant=baseline pair=$pair commit=$(git rev-parse HEAD)" + go test ./internal/platform/windows -run '^$' -bench '^BenchmarkWindowsIME(Acknowledgment|StateAllocation)$' -benchmem -benchtime=200ms -count=1 -timeout=90s + if ($LASTEXITCODE -ne 0) { throw 'baseline cost benchmark failed' } + } finally { Pop-Location } + Write-Output "IME cost variant=candidate pair=$pair commit=$(git rev-parse HEAD)" + go test ./internal/platform/windows -run '^$' -bench '^BenchmarkWindowsIME(Acknowledgment|StateAllocation)$' -benchmem -benchtime=200ms -count=1 -timeout=90s + if ($LASTEXITCODE -ne 0) { throw 'candidate cost benchmark failed' } + } + Write-Output "IME cost variant=dispatch commit=$(git rev-parse HEAD)" + go test ./internal/platform/windows -run '^$' -bench '^BenchmarkCompositionMessageDispatch$' -benchmem -benchtime=200ms -count=5 -timeout=90s + if ($LASTEXITCODE -ne 0) { throw 'message dispatch benchmark failed' } + } finally { + git -C $workspace worktree remove --force $directory + if ($LASTEXITCODE -ne 0) { throw 'cost worktree cleanup failed' } + Write-Output 'IME cost worktree removed' + } - name: Application input lifecycle run: go test ./app -count=1 - name: GTK native probe dependencies @@ -105,7 +151,10 @@ jobs: run: go test -tags vivagtk ./internal/platform/linux -run '^TestLinuxTextCallback' -count=1 -timeout=90s - name: Windows IME lifecycle if: runner.os == 'Windows' - run: go test ./internal/platform/windows -run 'TestComposition|TestDynamicTextInput' -count=1 + run: | + go test ./internal/platform/windows -list 'TestComposition|TestDynamicTextInput' + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + go test ./internal/platform/windows -run 'TestComposition|TestDynamicTextInput' -count=1 -v -timeout=90s - name: Windows aligned text input if: runner.os == 'Windows' run: go test ./internal/platform/windows -run '^TestWindowsTextInputAlignmentMatchesGlyphCaretUnderlineAndPointer$' -count=1 diff --git a/internal/platform/windows/composition_cost_windows_test.go b/internal/platform/windows/composition_cost_windows_test.go new file mode 100644 index 000000000..2b8e3e4b7 --- /dev/null +++ b/internal/platform/windows/composition_cost_windows_test.go @@ -0,0 +1,42 @@ +package windows + +import ( + "testing" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +func BenchmarkWindowsIMEAcknowledgment(b *testing.B) { + for _, enabled := range []bool{false, true} { + name := "legacy" + if enabled { + name = "tentative" + } + b.Run(name, func(b *testing.B) { + state := &windowState{textEnabled: true, textState: platform.TextState{TentativeComposition: enabled}} + state.textInput.Terminal = true + state.textInput.OnEvent = func(platform.TextEvent) (platform.TextState, error) { + return state.textState, nil + } + event := platform.TextEvent{Kind: platform.TextSetMarked, Text: "x"} + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + state.handleTextEvent(event) + } + b.ReportMetric(float64(unsafe.Sizeof(windowState{})), "window-B") + }) + } +} + +var compositionWindowStateSink *windowState + +func BenchmarkWindowsIMEStateAllocation(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + compositionWindowStateSink = new(windowState) + } + b.ReportMetric(float64(unsafe.Sizeof(windowState{})), "window-B") + compositionWindowStateSink = nil +} diff --git a/internal/platform/windows/composition_events_windows_test.go b/internal/platform/windows/composition_events_windows_test.go new file mode 100644 index 000000000..74949a23d --- /dev/null +++ b/internal/platform/windows/composition_events_windows_test.go @@ -0,0 +1,887 @@ +package windows + +import ( + "errors" + "runtime" + "slices" + "testing" + "unicode/utf16" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" + "github.com/vivaui/viva/internal/render" + "github.com/vivaui/viva/internal/scene" + "github.com/vivaui/viva/text" +) + +func TestCompositionIMEEndPreservesOptInAndLegacyBoundaries(t *testing.T) { + for _, enabled := range []bool{false, true} { + name := "legacy" + if enabled { + name = "tentative" + } + t.Run(name, func(t *testing.T) { + editor := text.NewEditor("abc") + if enabled && !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + preedit := platform.TextEvent{Kind: platform.TextSetMarked, Text: "x", MarkedSelection: text.Range{Start: 1, End: 1}} + if enabled { + preedit.CompositionPhase = text.CompositionUpdate + } + preedit.Apply(editor) + if editor.String() != "axc" { + t.Fatal("fixture did not begin selected preedit") + } + state := &windowState{ready: true, textEnabled: true, imeComposing: true, textState: platform.EditorState(editor)} + var events []platform.TextEvent + stop := errors.New("stop before renderer submission") + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + events = append(events, event) + event.Apply(editor) + return platform.EditorState(editor), stop + } + // Exercise the actual dispatcher without a graphics device. The handler + // error stops rendering only after the event has reached the real Editor. + const handle = ^uintptr(0) + previous := active.Load() + windowStates.Store(handle, state) + t.Cleanup(func() { windowStates.Delete(handle); active.Store(previous) }) + windowProc(handle, wmIMEEnd, 0, 0) + if len(events) != 1 || state.err != stop || state.imeComposing { + t.Fatalf("end delivery: events=%+v err=%v composing=%v", events, state.err, state.imeComposing) + } + wantPhase, wantText := text.CompositionNone, "axc" + if enabled { + wantPhase, wantText = text.CompositionCancel, "ac" + } + if events[0].CompositionPhase != wantPhase || editor.String() != wantText { + t.Fatalf("end phase=%v text=%q, want phase=%v text=%q", events[0].CompositionPhase, editor.String(), wantPhase, wantText) + } + windowProc(handle, wmIMEEnd, 0, 0) + if len(events) != 1 { + t.Fatal("duplicate end delivered another edit") + } + if enabled { + editor.Undo() + if editor.String() != "abc" { + t.Fatalf("ordinary selection deletion did not remain undoable: %q", editor.String()) + } + } + }) + } +} + +func compositionMessageWindow(t *testing.T, editor *text.Editor) (*windowState, *[]platform.TextEvent) { + t.Helper() + runtime.LockOSThread() + t.Cleanup(runtime.UnlockOSThread) + state := dynamicTextState(0, 0) + state.window, state.scale, state.ready = staticWindow(t), 1, true + if err := state.renderer.initialize(state.window, platform.Color{Alpha: 1}); err != nil { + t.Fatalf("initialize native message surface: %v", err) + } + t.Cleanup(func() { + state.stopCaretTimer() + state.renderer.close() + }) + state.textEnabled = true + state.textInput = testTextInput(editor.String(), 0) + state.textInput.Target = gfx.Item(1) + state.textState = platform.EditorState(editor) + state.textInput.State = state.textState + events := new([]platform.TextEvent) + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + *events = append(*events, event) + event.Apply(editor) + return platform.EditorState(editor), nil + } + previous := active.Load() + windowStates.Store(state.window, state) + t.Cleanup(func() { windowStates.Delete(state.window); active.Store(previous) }) + return state, events +} + +func TestCompositionMessageResultAndFollowingPreedit(t *testing.T) { + for _, enabled := range []bool{false, true} { + name := "legacy" + if enabled { + name = "tentative" + } + t.Run(name, func(t *testing.T) { + editor := text.NewEditor("abc") + if enabled && !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x", selection: text.Range{Start: 1, End: 1}}) + if state.err != nil || !state.textState.Composing || editor.String() != "axc" { + t.Fatalf("preedit acknowledgement: %+v err=%v", state.textState, state.err) + } + // IMM may finish one conversion and begin the next in the same message. + state.applyIMEComposition(imeCompositionMessage{ + hasResult: true, result: "r", hasPreedit: true, preedit: "y", + selection: text.Range{Start: 1, End: 1}, target: text.Range{End: 1}, hasTarget: true, + }) + if state.err != nil || len(*events) != 3 || editor.String() != "aryc" || !state.imeComposing || !state.imeHasTarget { + t.Fatalf("combined result/preedit: text=%q events=%+v state=%+v err=%v", editor.String(), *events, state.textState, state.err) + } + want := []text.CompositionPhase{text.CompositionNone, text.CompositionNone, text.CompositionNone} + if enabled { + want = []text.CompositionPhase{text.CompositionUpdate, text.CompositionResult, text.CompositionUpdate} + } + phases := make([]text.CompositionPhase, len(*events)) + for index, event := range *events { + phases[index] = event.CompositionPhase + } + if !slices.Equal(phases, want) { + t.Fatalf("native phases=%v, want %v", phases, want) + } + windowProc(state.window, wmIMEEnd, 0, 0) + wantText := "aryc" + if enabled { + wantText = "arc" + } + if state.err != nil || editor.String() != wantText || state.textState.Composing { + t.Fatalf("end after combined message: text=%q state=%+v err=%v", editor.String(), state.textState, state.err) + } + }) + } +} + +func TestCompositionMessageEmptyPreeditRemainsAnUpdate(t *testing.T) { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + state, events := compositionMessageWindow(t, editor) + for _, value := range []string{"x", ""} { + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: value}) + } + if state.err != nil || len(*events) != 2 || editor.String() != "ac" { + t.Fatalf("empty preedit: text=%q events=%+v err=%v", editor.String(), *events, state.err) + } + for _, event := range *events { + if event.CompositionPhase != text.CompositionUpdate { + t.Fatalf("empty preedit fabricated a terminal phase: %+v", event) + } + } +} + +func TestCompositionResultDoesNotSuppressAnIdenticalOrdinaryCharacter(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r"}) + windowProc(state.window, wmIMEEnd, 0, 0) + windowProc(state.window, wmChar, 'r', 0) + if state.err != nil || editor.String() != "arr" || len(*events) != 3 || (*events)[2].CompositionPhase != text.CompositionNone { + t.Fatalf("ordinary character after result: text=%q events=%+v err=%v", editor.String(), *events, state.err) + } + windowProc(state.window, wmChar, 0xd801, 0) + windowProc(state.window, wmChar, 0xdc37, 0) + if state.err != nil || editor.String() != "arr\U00010437" || len(*events) != 4 || state.pendingHighSurrogate != 0 { + t.Fatalf("UTF-16 character after result: text=%q events=%+v err=%v", editor.String(), *events, state.err) + } +} + +func TestCompositionMessageDoesNotContinueIntoAReplacementInput(t *testing.T) { + for _, name := range []string{"replacement", "same target", "disabled", "multiline", "placed"} { + t.Run(name, func(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + foreign := 0 + state.config.OnRedraw = func() (platform.Frame, error) { + var input *platform.TextInput + if name != "disabled" { + next := testTextInput("other", 0) + next.Target = gfx.Item(2) + if name == "same target" { + next.Target = state.textInput.Target + next.State.TentativeComposition = true + } + if name == "multiline" || name == "placed" { + next = state.textInput + next.Multiline = name == "multiline" + next.Placed = name == "placed" + } + next.OnEvent = func(platform.TextEvent) (platform.TextState, error) { + foreign++ + return next.State, nil + } + input = &next + } + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: input}}, nil + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || editor.String() != "ar" || len(*events) != 2 || foreign != 0 { + t.Fatalf("message reached a new owner: text=%q events=%+v foreign=%d err=%v", editor.String(), *events, foreign, state.err) + } + }) + } +} + +func TestCompositionMessageContinuesAfterGeometryOnlyRedraw(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + state.config.OnRedraw = func() (platform.Frame, error) { + next := state.textInput + next.CaretX += 10 + next.Width += 10 + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &next}}, nil + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || len(*events) != 3 || editor.String() != "ary" || !state.textState.Composing { + t.Fatalf("geometry redraw lost next preedit: text=%q events=%+v err=%v", editor.String(), *events, state.err) + } +} + +func TestCompositionMessageDoesNotEnterAnIdenticalNewEditor(t *testing.T) { + makeEditor := func() *text.Editor { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + return editor + } + editor, other := makeEditor(), makeEditor() + other.ApplyComposition(text.CompositionEvent{Phase: text.CompositionUpdate, Text: "x"}) + other.ApplyComposition(text.CompositionEvent{Phase: text.CompositionResult, Text: "r"}) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + foreign := 0 + state.config.OnRedraw = func() (platform.Frame, error) { + next := state.textInput + next.State = platform.EditorState(other) + oldValue := state.textState + oldValue.CompositionIdentity = next.State.CompositionIdentity + if oldValue != next.State { + t.Fatal("replacement fixture differs by more than Editor identity") + } + next.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + foreign++ + event.Apply(other) + return platform.EditorState(other), nil + } + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &next}}, nil + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || foreign != 0 || len(*events) != 2 || editor.String() != "ar" || other.String() != "ar" { + t.Fatalf("old message entered identical replacement: old=%q new=%q foreign=%d err=%v", editor.String(), other.String(), foreign, state.err) + } +} + +func TestCompositionMessageDoesNotContinueAfterReentrantEnd(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + state.config.OnRedraw = func() (platform.Frame, error) { + windowProc(state.window, wmIMEEnd, 0, 0) + return platform.Frame{}, nil + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || len(*events) != 2 || editor.String() != "ar" || state.textState.Composing { + t.Fatalf("old message resumed after End: text=%q events=%+v state=%+v err=%v", editor.String(), *events, state.textState, state.err) + } + if state.textState != platform.EditorState(editor) || state.textLabels[state.baseTextLabelCount].Value != state.textState.Value { + t.Fatalf("End discarded the only Result frame: editor=%q state=%+v label=%q", editor.String(), state.textState, state.textLabels[state.baseTextLabelCount].Value) + } +} + +func TestCompositionResultAcknowledgmentSurvivesReentrantEnd(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + apply := state.textInput.OnEvent + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + ack, err := apply(event) + windowProc(state.window, wmIMEEnd, 0, 0) + return ack, err + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || len(*events) != 2 || editor.String() != "ar" || state.textState != platform.EditorState(editor) || + state.textLabels[state.baseTextLabelCount].Value != "ar" { + t.Fatalf("End discarded Result acknowledgment: editor=%q state=%+v events=%+v err=%v", editor.String(), state.textState, *events, state.err) + } +} + +func TestCompositionInputReplacementDoesNotOverwriteNativeCancelReentry(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + state, _ := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + stale := testTextInput("stale replacement", 0) + latest := testTextInput("latest replacement", 0) + latest.Target = gfx.Item(3) + calls := 0 + _, _, err := state.applyTextInputUpdateWithCancel(platform.TextInputUpdate{Changed: true, Input: &stale}, func() { + calls++ + // Model the synchronous window callback at the IMM cancellation boundary. + if _, _, err := state.applyTextInputUpdate(platform.TextInputUpdate{Changed: true, Input: &latest}); err != nil { + t.Fatal(err) + } + }) + if err != nil || calls != 1 || state.textInput.Target != latest.Target || state.textState != latest.State { + t.Fatalf("cancel reentry overwritten: state=%+v target=%+v calls=%d err=%v", state.textState, state.textInput.Target, calls, err) + } +} + +func TestCompositionSupersededFrameDoesNotPublishOldNativeViews(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + state, _ := compositionMessageWindow(t, editor) + base := render.Rectangle{Bounds: scene.Rect{X: 1, Width: 10, Height: 10}} + if err := state.frameWithText(platform.Frame{Rectangles: []render.Rectangle{base}, Update: render.Update{Count: 1, Rebuild: true}}, nil, false); err != nil { + t.Fatal(err) + } + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + state.web = &webHost{state: state} + stale, latest := testTextInput("stale", 0), testTextInput("latest", 0) + staleView := platform.NativeView{ID: 2, Bounds: gfx.Rect{Width: 10, Height: 10}} + latestView := platform.NativeView{ID: 3, Bounds: gfx.Rect{Width: 20, Height: 20}} + presented := 0 + state.config.FramePresented = func() { presented++ } + err := state.frameWithTextAndCancel(platform.Frame{ + TextInput: platform.TextInputUpdate{Changed: true, Input: &stale}, NativeViews: []platform.NativeView{staleView}, + Rectangles: []render.Rectangle{{Bounds: scene.Rect{X: 2, Width: 10, Height: 10}}}, Update: render.Update{Count: 1}, + }, nil, false, func() { + if err := state.frameWithText(platform.Frame{ + TextInput: platform.TextInputUpdate{Changed: true, Input: &latest}, NativeViews: []platform.NativeView{latestView}, + }, nil, false); err != nil { + t.Fatal(err) + } + }) + if err != nil || state.err != nil || state.textState != latest.State || + len(state.web.rects) != 1 || state.web.rects[0].ID != latestView.ID || presented == 0 || state.textRectangles[0] != base { + t.Fatalf("superseded frame published: state=%+v views=%+v rectangle=%+v presented=%d err=%v", state.textState, state.web.rects, state.textRectangles[0], presented, err) + } +} + +func TestCompositionMessageDoesNotOverwriteAReentrantUpdate(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + reentered := false + state.config.OnRedraw = func() (platform.Frame, error) { + if !reentered { + reentered = true + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "z"}) + } + return platform.Frame{}, nil + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || len(*events) != 3 || editor.String() != "arz" || state.textState.Value != "arz" { + t.Fatalf("older tail overwrote reentrant update: text=%q state=%+v events=%+v err=%v", editor.String(), state.textState, *events, state.err) + } +} + +func TestCompositionMessageDoesNotInstallAReentrantEventStaleAck(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + apply := state.textInput.OnEvent + reentered := false + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + ack, err := apply(event) + if !reentered && event.CompositionPhase == text.CompositionResult { + reentered = true + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "z"}) + } + return ack, err + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || len(*events) != 3 || editor.String() != "arz" || state.textState != platform.EditorState(editor) { + t.Fatalf("stale event acknowledgment: text=%q state=%+v events=%+v err=%v", editor.String(), state.textState, *events, state.err) + } +} + +func TestCompositionEmptyResultDoesNotOverwriteSameValueReentrantPreedit(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + apply := state.textInput.OnEvent + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + ack, err := apply(event) + if event.CompositionPhase == text.CompositionResult { + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + } + return ack, err + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "", hasPreedit: true, preedit: "y"}) + if state.err != nil || len(*events) != 3 || editor.String() != "ax" || state.textState != platform.EditorState(editor) || + state.textLabels[state.baseTextLabelCount].Value != "ax" { + t.Fatalf("same-value acknowledgment overwritten: editor=%q state=%+v events=%+v err=%v", editor.String(), state.textState, *events, state.err) + } +} + +func TestCompositionResultFrameSurvivesReentrantNoopAcknowledgment(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, _ := compositionMessageWindow(t, editor) + state.textInput.Terminal, state.textInput.CellWidth, state.textInput.Baseline = true, 8, 12 + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + redraws := 0 + state.config.OnRedraw = func() (platform.Frame, error) { + redraws++ + if redraws > 1 { + t.Fatal("unchanged terminal acknowledgment requested another redraw") + } + state.handleTextEvent(platform.TextEvent{Kind: platform.TextSetSelection, Selection: editor.Selection()}) + return platform.Frame{}, nil + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r"}) + if state.err != nil || redraws != 1 || editor.String() != "ar" || state.textState != platform.EditorState(editor) || + state.textLabels[state.baseTextLabelCount].Value != "ar" { + t.Fatalf("noop acknowledgment lost Result frame: editor=%q state=%+v label=%q err=%v", editor.String(), state.textState, state.textLabels[state.baseTextLabelCount].Value, state.err) + } +} + +func TestCompositionMessageDoesNotInstallAReentrantRedrawStaleFrame(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + reentered := false + state.config.OnRedraw = func() (platform.Frame, error) { + stale := state.textInput + if !reentered { + reentered = true + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "z"}) + } + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &stale}}, nil + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || len(*events) != 3 || editor.String() != "arz" || state.textState != platform.EditorState(editor) { + t.Fatalf("stale redraw acknowledgment: text=%q state=%+v events=%+v err=%v", editor.String(), state.textState, *events, state.err) + } +} + +func TestCompositionMessageDoesNotContinueAfterAckChangesOwner(t *testing.T) { + editor, other := text.NewEditor("a"), text.NewEditor("other") + if !editor.EnableTentativeComposition() || !other.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + foreign := 0 + apply := state.textInput.OnEvent + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + _, err := apply(event) + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + foreign++ + event.Apply(other) + return platform.EditorState(other), nil + } + return platform.EditorState(other), err + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != nil || len(*events) != 2 || foreign != 0 || editor.String() != "ar" || other.String() != "other" || state.textState != platform.EditorState(other) { + t.Fatalf("message entered an acknowledgment owner: old=%q new=%q foreign=%d state=%+v err=%v", editor.String(), other.String(), foreign, state.textState, state.err) + } +} + +func TestCompositionFailedResultReadStillAllowsEndCancellation(t *testing.T) { + for _, failure := range []string{"negative length", "odd length", "negative write", "odd write", "oversized write"} { + t.Run(failure, func(t *testing.T) { + editor := text.NewEditor("abc") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.SetSelection(text.Range{Start: 1, End: 2}) + state, events := compositionMessageWindow(t, editor) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + read := func(args ...uintptr) (uintptr, uintptr, error) { + if args[2] == 0 { + switch failure { + case "negative length": + return ^uintptr(0), 0, nil + case "odd length": + return 3, 0, nil + } + return 4, 0, nil + } + switch failure { + case "negative write": + return ^uintptr(0), 0, nil + case "odd write": + return 3, 0, nil + default: + return 6, 0, nil + } + } + state.handleCompositionData(1, resultString, read) + if len(*events) != 1 || editor.String() != "axc" || state.err != nil { + t.Fatal("a failed IMM read fabricated a result or damaged the pending state") + } + windowProc(state.window, wmIMEEnd, 0, 0) + if len(*events) != 2 || editor.String() != "ac" || state.textState.Composing || (*events)[1].CompositionPhase != text.CompositionCancel { + t.Fatalf("failed read stranded composition: text=%q events=%+v state=%+v", editor.String(), *events, state.textState) + } + editor.Undo() + if editor.String() != "abc" { + t.Fatal("failed sampling lost the ordinary deletion's Undo boundary") + } + }) + } +} + +func TestCompositionSamplesTheWholeMessageBeforeCallbacks(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + sampledCursor := false + apply := state.textInput.OnEvent + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + if !sampledCursor { + t.Error("application callback ran before native sampling finished") + } + return apply(event) + } + read := func(args ...uintptr) (uintptr, uintptr, error) { + switch args[1] { + case compositionCursor: + sampledCursor = true + return 2, 0, nil + case compositionAttr: + return 0, 0, nil + } + value := "r" + if args[1] == compositionString { + value = "\U00010437x" + } + units := utf16.Encode([]rune(value)) + if args[2] != 0 { + copy(unsafe.Slice((*uint16)(pointer(args[2])), len(units)), units) + } + return uintptr(len(units) * 2), 0, nil + } + state.handleCompositionData(1, resultString|compositionString|compositionCursor, read) + if state.err != nil || len(*events) != 2 || editor.String() != "ar\U00010437x" || (*events)[1].MarkedSelection != (text.Range{Start: 1, End: 1}) { + t.Fatalf("sampled message/UTF-16 cursor: text=%q events=%+v err=%v", editor.String(), *events, state.err) + } +} + +func TestCompositionMessageStopsAfterAHandlerError(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, _ := compositionMessageWindow(t, editor) + stop, calls := errors.New("rejected native event"), 0 + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + calls++ + event.Apply(editor) + return platform.EditorState(editor), stop + } + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + if state.err != stop || calls != 1 || editor.String() != "ar" { + t.Fatalf("continued a failed message: calls=%d text=%q err=%v", calls, editor.String(), state.err) + } +} + +func BenchmarkCompositionMessageDispatch(b *testing.B) { + for _, enabled := range []bool{false, true} { + name := "legacy" + if enabled { + name = "tentative" + } + b.Run(name, func(b *testing.B) { + state := &windowState{textEnabled: true, textState: platform.TextState{TentativeComposition: enabled}} + state.textInput.Terminal = true + state.textInput.OnEvent = func(platform.TextEvent) (platform.TextState, error) { + return state.textState, nil + } + message := imeCompositionMessage{hasPreedit: true, preedit: "x"} + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + state.applyIMEComposition(message) + } + b.ReportMetric(float64(unsafe.Sizeof(windowState{})), "window-B") + }) + } +} + +func TestCompositionNativeCancelDoesNotReenableDestroyedWindow(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + state, _ := compositionMessageWindow(t, editor) + state.application = &windowsApplication{windows: 1} + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + window := state.window + closed, staleCalls := 0, 0 + state.config.OnClosed = func() { closed++ } + stale := testTextInput("stale replacement", 0) + stale.Target = gfx.Item(2) + stale.OnEvent = func(platform.TextEvent) (platform.TextState, error) { + staleCalls++ + return stale.State, nil + } + _, _, err := state.applyTextInputUpdateWithCancel(platform.TextInputUpdate{Changed: true, Input: &stale}, func() { + windowProc(window, wmDestroy, 0, 0) + }) + if state.window != 0 || state.application.windows != 0 || closed != 1 || state.err != nil { + t.Fatalf("window destruction fixture: window=%d count=%d closed=%d err=%v", state.window, state.application.windows, closed, state.err) + } + if err != nil || state.textEnabled || state.textInput.Target == stale.Target { + t.Fatalf("native cancellation revived destroyed input: enabled=%v target=%v err=%v", state.textEnabled, state.textInput.Target, err) + } + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "late"}) + if staleCalls != 0 { + t.Fatalf("destroyed window received %d stale callbacks", staleCalls) + } +} + +func TestCompositionDestroyedCallbacksDoNotReviveFrames(t *testing.T) { + for _, callback := range []string{"event", "redraw"} { + t.Run(callback, func(t *testing.T) { + editor := text.NewEditor("a") + if !editor.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + editor.MoveTo(1, false) + state, events := compositionMessageWindow(t, editor) + state.application = &windowsApplication{windows: 1} + state.web = &webHost{state: state} + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + window, closed := state.window, 0 + state.config.OnClosed = func() { closed++ } + if callback == "event" { + apply := state.textInput.OnEvent + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + ack, err := apply(event) + windowProc(window, wmDestroy, 0, 0) + return ack, err + } + } else { + state.config.OnRedraw = func() (platform.Frame, error) { + stale := state.textInput + windowProc(window, wmDestroy, 0, 0) + return platform.Frame{ + TextInput: platform.TextInputUpdate{Changed: true, Input: &stale}, + NativeViews: []platform.NativeView{{ID: 9, Bounds: gfx.Rect{Width: 10, Height: 10}}}, + }, nil + } + } + var trapped any + func() { + defer func() { trapped = recover() }() + state.applyIMEComposition(imeCompositionMessage{hasResult: true, result: "r", hasPreedit: true, preedit: "y"}) + }() + if state.window != 0 || state.application.windows != 0 || closed != 1 { + t.Fatalf("window destruction fixture: window=%d count=%d closed=%d", state.window, state.application.windows, closed) + } + if trapped != nil { + t.Fatalf("closed callback used released native resources: %v", trapped) + } + if state.err != nil || state.textEnabled || editor.String() != "ar" || len(*events) != 2 || len(state.web.rects) != 0 { + t.Fatalf("closed callback resumed input/frame: enabled=%v text=%q events=%d views=%d err=%v", state.textEnabled, editor.String(), len(*events), len(state.web.rects), state.err) + } + }) + } +} + +func TestCompositionCancellationKeepsRetiredIMEOffTheReplacement(t *testing.T) { + for _, enabled := range []bool{false, true} { + mode := "legacy" + if enabled { + mode = "tentative" + } + for _, message := range []string{"retired preedit", "ordinary character"} { + t.Run(mode+"/"+message, func(t *testing.T) { + outgoing, incoming := text.NewEditor("a"), text.NewEditor("abc") + if enabled && (!outgoing.EnableTentativeComposition() || !incoming.EnableTentativeComposition()) { + t.Fatal("could not enable fixture capability") + } + outgoing.MoveTo(1, false) + state, _ := compositionMessageWindow(t, outgoing) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + if enabled { + outgoing.ApplyComposition(text.CompositionEvent{Phase: text.CompositionCommit}) + } else { + outgoing.Unmark() + } + incoming.SetSelection(text.Range{Start: 1, End: 2}) + foreign := 0 + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + foreign++ + event.Apply(incoming) + return platform.EditorState(incoming), nil + } + next := state.textInput + next.Target, next.State = gfx.Item(2), platform.EditorState(incoming) + state.config.OnRedraw = func() (platform.Frame, error) { + live := next + live.State = platform.EditorState(incoming) + return platform.Frame{TextInput: platform.TextInputUpdate{Changed: true, Input: &live}}, nil + } + _, _, err := state.applyTextInputUpdateWithCancel(platform.TextInputUpdate{Changed: true, Input: &next}, func() { + if message == "ordinary character" { + windowProc(state.window, wmChar, 'q', 0) + } else { + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: ""}) + windowProc(state.window, wmIMEEnd, 0, 0) + } + }) + wantText, wantCalls := "abc", 0 + if message == "ordinary character" { + wantText, wantCalls = "aqc", 1 + } + if err != nil || state.err != nil || incoming.String() != wantText || foreign != wantCalls || + !state.textEnabled || state.textInput.Target != next.Target || state.textState != platform.EditorState(incoming) { + t.Fatalf("cancellation crossed input ownership: message=%s text=%q calls=%d enabled=%v target=%v state=%+v err=%v/%v", message, incoming.String(), foreign, state.textEnabled, state.textInput.Target, state.textState, err, state.err) + } + if message == "retired preedit" { + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "y"}) + if state.err != nil || foreign != 1 || incoming.String() != "ayc" || !state.textState.Composing { + t.Fatalf("fresh owner could not compose: text=%q calls=%d state=%+v err=%v", incoming.String(), foreign, state.textState, state.err) + } + } + }) + } + } +} + +func TestCompositionAcknowledgmentCancellationPreservesTheCurrentOwner(t *testing.T) { + for _, enabled := range []bool{false, true} { + mode := "legacy" + if enabled { + mode = "tentative" + } + for _, reentry := range []string{"retired preedit", "ordinary character", "new input", "destroyed window"} { + t.Run(mode+"/"+reentry, func(t *testing.T) { + outgoing, incoming := text.NewEditor("a"), text.NewEditor("abc") + if !outgoing.EnableTentativeComposition() || enabled && !incoming.EnableTentativeComposition() { + t.Fatal("could not enable fixture capability") + } + outgoing.MoveTo(1, false) + incoming.SetSelection(text.Range{Start: 1, End: 2}) + state, events := compositionMessageWindow(t, outgoing) + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "x"}) + state.application = &windowsApplication{windows: 1} + foreign, redraws, closed := 0, 0, 0 + apply := state.textInput.OnEvent + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + _, err := apply(event) + state.textInput.OnEvent = func(event platform.TextEvent) (platform.TextState, error) { + foreign++ + event.Apply(incoming) + return platform.EditorState(incoming), nil + } + return platform.EditorState(incoming), err + } + state.config.OnRedraw = func() (platform.Frame, error) { + redraws++ + return platform.Frame{}, nil + } + state.config.OnClosed = func() { closed++ } + latest := testTextInput("latest", 0) + latest.Target = gfx.Item(3) + cancelCalls := 0 + _, changed, err := state.textEventFrameWithCancel(platform.TextEvent{ + Kind: platform.TextInsert, Text: "r", CompositionPhase: text.CompositionResult, + }, func() { + cancelCalls++ + switch reentry { + case "retired preedit": + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: ""}) + windowProc(state.window, wmIMEStart, 0, 0) + windowProc(state.window, wmIMEEnd, 0, 0) + case "ordinary character": + windowProc(state.window, wmChar, 'q', 0) + case "new input": + _, _, updateErr := state.applyTextInputUpdate(platform.TextInputUpdate{Changed: true, Input: &latest}) + if updateErr != nil { + t.Fatalf("new input during cancellation: %v", updateErr) + } + case "destroyed window": + windowProc(state.window, wmDestroy, 0, 0) + } + }) + if err != nil || state.err != nil || cancelCalls != 1 || outgoing.String() != "ar" || len(*events) != 2 { + t.Fatalf("acknowledgment fixture: cancels=%d text=%q events=%d err=%v/%v", cancelCalls, outgoing.String(), len(*events), err, state.err) + } + wantText, wantCalls, wantRedraws := "abc", 0, 1 + switch reentry { + case "ordinary character": + wantText, wantCalls = "aqc", 1 + case "new input": + wantRedraws = 0 + if !state.textEnabled || state.textInput.Target != latest.Target || state.textState.Value != "latest" { + t.Fatalf("cancellation lost the newest input: enabled=%v target=%v state=%+v", state.textEnabled, state.textInput.Target, state.textState) + } + case "destroyed window": + wantRedraws = 0 + if state.window != 0 || state.textEnabled || state.application.windows != 0 || closed != 1 || changed { + t.Fatalf("cancellation revived a destroyed window: window=%d enabled=%v count=%d closed=%d changed=%v", state.window, state.textEnabled, state.application.windows, closed, changed) + } + } + if incoming.String() != wantText || foreign != wantCalls || redraws != wantRedraws || state.imeCancelling { + t.Fatalf("acknowledgment cancellation crossed owners: text=%q calls=%d redraws=%d cancelling=%v", incoming.String(), foreign, redraws, state.imeCancelling) + } + if reentry == "retired preedit" { + state.applyIMEComposition(imeCompositionMessage{hasPreedit: true, preedit: "y"}) + if state.err != nil || incoming.String() != "ayc" || foreign != 1 || !state.textState.Composing { + t.Fatalf("replacement could not begin a fresh composition: text=%q calls=%d state=%+v err=%v", incoming.String(), foreign, state.textState, state.err) + } + } + }) + } + } +} diff --git a/internal/platform/windows/ime_windows.go b/internal/platform/windows/ime_windows.go index 3b58c23e7..ab806854e 100644 --- a/internal/platform/windows/ime_windows.go +++ b/internal/platform/windows/ime_windows.go @@ -1,6 +1,7 @@ package windows import ( + "errors" "fmt" "strings" "unicode/utf16" @@ -43,6 +44,8 @@ var notifyIME = imm.NewProc("ImmNotifyIME") var setCandidateWindow = imm.NewProc("ImmSetCandidateWindow") var associateContext = imm.NewProc("ImmAssociateContext") +var errSupersededTextFrame = errors.New("windows: text frame superseded during native cancellation") + // candidateForm is CANDIDATEFORM. type candidateForm struct { Index, Style uint32 @@ -109,6 +112,10 @@ func (state *windowState) initializeText() error { } func (state *windowState) closeText() { + state.imeEpoch++ + state.textRevision++ + state.textEnabled = false + state.imeComposing, state.imeHasTarget = false, false state.stopCaretTimer() state.textEngine = nil } @@ -355,23 +362,32 @@ func (state *windowState) textPointerEvent(event platform.PointerEvent) (platfor } func (state *windowState) handleTextEvent(event platform.TextEvent) { + state.imeEpoch++ frame, changed, err := state.textEventFrame(event) if err != nil { state.fail(err) return } - if !changed { + if !changed || state.window == 0 { return } state.frameWithText(frame, nil, true) } func (state *windowState) textEventFrame(event platform.TextEvent) (platform.Frame, bool, error) { + return state.textEventFrameWithCancel(event, state.cancelNativeComposition) +} + +func (state *windowState) textEventFrameWithCancel(event platform.TextEvent, cancelNative func()) (platform.Frame, bool, error) { if !state.textEnabled || state.textInput.OnEvent == nil { return platform.Frame{}, false, nil } previous := state.textState + revision := state.textRevision next, err := state.textInput.OnEvent(event) + if err == nil && state.textRevision != revision { + return platform.Frame{}, state.window != 0, nil + } if err == nil { err = validateTextState(next) } @@ -380,8 +396,24 @@ func (state *windowState) textEventFrame(event platform.TextEvent) (platform.Fra } redraw := platform.TextInputPresentationChanged(state.textInput.Terminal, previous, next) next = next.WithoutRedraw() // a one-shot request, not editor state + ownerChanged := next.CompositionIdentity != previous.CompositionIdentity || next.TentativeComposition != previous.TentativeComposition + cancelPrevious := ownerChanged && (state.imeComposing || previous.Composing) + if ownerChanged { + state.imeEpoch++ + state.imeComposing, state.imeHasTarget = false, false + } + state.textRevision++ state.textState = next state.textInput.State = next + if cancelPrevious { + // IMM may reenter the window procedure. Install the new owner first and + // never overwrite a newer acknowledgment after cancelling the old one. + revision = state.textRevision + state.cancelIMEWith(cancelNative) + if state.textRevision != revision { + return platform.Frame{}, state.window != 0, nil + } + } if !redraw { return platform.Frame{}, false, nil } @@ -389,8 +421,14 @@ func (state *windowState) textEventFrame(event platform.TextEvent) (platform.Fra if err := state.restartCaretTimer(); err != nil { return platform.Frame{}, false, err } + revision = state.textRevision if state.config.OnRedraw != nil { frame, err := state.config.OnRedraw() + if err == nil && state.textRevision != revision { + // A nested no-op may have acknowledged state without submitting a + // frame. Refresh the latest native mirror, without replaying old input. + return platform.Frame{}, state.window != 0, nil + } return frame, true, err } return platform.Frame{}, true, nil @@ -420,6 +458,10 @@ func (state *windowState) resizeTextStorage(rectangleCount, labelCount int) { } func (state *windowState) applyTextInputUpdate(update platform.TextInputUpdate) (bool, bool, error) { + return state.applyTextInputUpdateWithCancel(update, state.cancelNativeComposition) +} + +func (state *windowState) applyTextInputUpdateWithCancel(update platform.TextInputUpdate, cancelNative func()) (bool, bool, error) { if !update.Changed { return false, false, nil } @@ -437,8 +479,15 @@ func (state *windowState) applyTextInputUpdate(update platform.TextInputUpdate) state.textInput.Multiline != update.Input.Multiline || state.textInput.Secure != update.Input.Secure || state.textInput.Terminal != update.Input.Terminal || state.textInput.Placed != update.Input.Placed || state.textState != update.Input.State.WithoutRedraw() + if replaced { + state.textRevision++ + } + revision := state.textRevision if wasEnabled && replaced { - state.cancelComposition() + state.cancelCompositionWith(cancelNative) + if state.textRevision != revision { + return false, false, nil + } } if replaced { state.pendingHighSurrogate = 0 @@ -495,6 +544,10 @@ func (state *windowState) updateIMEAssociation() { } func (state *windowState) prepareFrame(frame platform.Frame, nativeVisualChanged bool) (platform.Frame, bool, error) { + return state.prepareFrameWithCancel(frame, nativeVisualChanged, state.cancelNativeComposition) +} + +func (state *windowState) prepareFrameWithCancel(frame platform.Frame, nativeVisualChanged bool, cancelNative func()) (platform.Frame, bool, error) { if frame.TextInput.Changed { if !state.config.DynamicTextInput { return platform.Frame{}, false, fmt.Errorf("windows: dynamic text input update is disabled") @@ -507,6 +560,7 @@ func (state *windowState) prepareFrame(frame platform.Frame, nativeVisualChanged oldBaseLabels := state.baseTextLabelCount baseRectangles := state.textRectangles[:oldBaseRectangles] baseLabels := state.textLabels[:oldBaseLabels] + partialRectangles := false if !frame.Update.Empty() { if frame.Update.First < 0 || frame.Update.Count < 0 || frame.Update.First > len(frame.Rectangles) || frame.Update.Count > len(frame.Rectangles)-frame.Update.First { @@ -526,17 +580,23 @@ func (state *windowState) prepareFrame(frame platform.Frame, nativeVisualChanged if len(frame.Rectangles) != oldBaseRectangles { return platform.Frame{}, false, fmt.Errorf("windows: canvas rectangle count shrank without rebuild") } - copy(state.textRectangles[frame.Update.First:frame.Update.First+frame.Update.Count], frame.Rectangles[frame.Update.First:frame.Update.First+frame.Update.Count]) + partialRectangles = true } } if frame.TextLabels != nil { baseLabels = frame.TextLabels } - inputChanged, inputStructureChanged, err := state.applyTextInputUpdate(frame.TextInput) + inputChanged, inputStructureChanged, err := state.applyTextInputUpdateWithCancel(frame.TextInput, cancelNative) if err != nil { return platform.Frame{}, false, err } + if frame.TextInput.Changed && !inputChanged { + return platform.Frame{}, false, errSupersededTextFrame + } + if partialRectangles { + copy(state.textRectangles[frame.Update.First:frame.Update.First+frame.Update.Count], frame.Rectangles[frame.Update.First:frame.Update.First+frame.Update.Count]) + } state.baseRectangleCount = len(baseRectangles) state.baseTextLabelCount = len(baseLabels) extraRectangles, extraLabels := 0, 0 @@ -595,6 +655,12 @@ func mergeRenderUpdates(left, right render.Update) render.Update { } func (state *windowState) cancelComposition() { + state.textRevision++ + state.cancelCompositionWith(state.cancelNativeComposition) +} + +func (state *windowState) cancelCompositionWith(cancelNative func()) { + state.imeEpoch++ if !state.imeComposing && !state.textState.Composing { return } @@ -602,15 +668,29 @@ func (state *windowState) cancelComposition() { state.imeHasTarget = false state.textState.Composing = false state.textState.Composition = text.Range{} - if state.window == 0 { + state.cancelIMEWith(cancelNative) +} + +func (state *windowState) cancelIMEWith(cancelNative func()) { + // A cancelling context may synchronously emit preedit/end for its retired + // owner. Ordinary characters and newer input updates still belong to the app. + previous := state.imeCancelling + state.imeCancelling = true + defer func() { state.imeCancelling = previous }() + cancelNative() +} + +func (state *windowState) cancelNativeComposition() { + window := state.window + if window == 0 { return } - context, _, _ := getInputContext.Call(state.window) + context, _, _ := getInputContext.Call(window) if context == 0 { return } notifyIME.Call(context, notifyComposition, compositionCancel, 0) - releaseInputContext.Call(state.window, context) + releaseInputContext.Call(window, context) } // caretBlinks reports whether a native caret belongs on screen. Terminal and @@ -672,6 +752,15 @@ func (state *windowState) setCaretVisible(visible bool) { invalidateRect.Call(state.window, 0, 0) } +type imeCompositionMessage struct { + result, preedit string + hasResult, hasPreedit bool + selection, target text.Range + hasTarget bool +} + +type compositionStringReader func(...uintptr) (uintptr, uintptr, error) + func (state *windowState) handleComposition(flags uintptr) { // An input method that has no context to give, or a composition string it // cannot report, loses that one composition. Closing the window over it would @@ -681,38 +770,76 @@ func (state *windowState) handleComposition(flags uintptr) { return } defer releaseInputContext.Call(state.window, context) + state.handleCompositionData(context, flags, getCompositionString.Call) +} + +func (state *windowState) handleCompositionData(context, flags uintptr, read compositionStringReader) { + state.imeEpoch++ + epoch := state.imeEpoch + message := imeCompositionMessage{} if flags&resultString != 0 { - value, err := compositionText(context, resultString) - state.imeComposing = false - state.imeHasTarget = false + value, err := compositionText(context, resultString, read) if err != nil { + if state.imeEpoch == epoch && !state.textState.TentativeComposition { + state.imeComposing, state.imeHasTarget = false, false + } return } - state.handleTextEvent(platform.TextEvent{Kind: platform.TextInsert, Text: value}) - return + message.result, message.hasResult = value, true + } + // Read the entire native message before an application callback can replace + // the input or reset its IMM context while processing the result. + if flags&compositionString != 0 { + value, err := compositionText(context, compositionString, read) + if err == nil { + message.preedit, message.hasPreedit = value, true + message.target, message.hasTarget = compositionTarget(context, value, read) + cursorUnits := 0 + if flags&compositionCursor != 0 { + position, _, _ := read(context, compositionCursor, 0, 0) + cursorUnits = max(0, int(int32(position))) + } + cursorRunes := text.NewEditor(value).UTF16ToRuneIndex(cursorUnits) + message.selection = text.Range{Start: cursorRunes, End: cursorRunes} + } } - if flags&compositionString == 0 { - return + if state.imeEpoch == epoch { + state.applyIMEComposition(message) } - value, err := compositionText(context, compositionString) - if err != nil { +} + +func (state *windowState) applyIMEComposition(message imeCompositionMessage) { + if !state.textEnabled || state.err != nil || state.imeCancelling { return } - state.imeTarget, state.imeHasTarget = compositionTarget(context, value) - cursorUnits := 0 - if flags&compositionCursor != 0 { - position, _, _ := getCompositionString.Call(context, compositionCursor, 0, 0) - cursorUnits = int(int32(position)) - if cursorUnits < 0 { - cursorUnits = 0 + state.imeEpoch++ + tentative := state.textState.TentativeComposition + owner := state.textState.CompositionIdentity + if message.hasResult { + state.imeComposing, state.imeHasTarget = false, false + event := platform.TextEvent{Kind: platform.TextInsert, Text: message.result} + if tentative { + event.CompositionPhase = text.CompositionResult + } + epoch := state.imeEpoch + 1 // the acknowledged Result advances it once + state.handleTextEvent(event) + if state.imeEpoch != epoch || state.err != nil || !state.textEnabled || state.textInput.DisableIME || + state.textState.CompositionIdentity != owner || state.textState.TentativeComposition != tentative { + return + } + } + if message.hasPreedit { + state.imeComposing = true + state.imeTarget, state.imeHasTarget = message.target, message.hasTarget + event := platform.TextEvent{ + Kind: platform.TextSetMarked, Text: message.preedit, + MarkedSelection: message.selection, + } + if tentative { + event.CompositionPhase = text.CompositionUpdate } + state.handleTextEvent(event) } - cursorRunes := text.NewEditor(value).UTF16ToRuneIndex(cursorUnits) - state.imeComposing = true - state.handleTextEvent(platform.TextEvent{ - Kind: platform.TextSetMarked, Text: value, - MarkedSelection: text.Range{Start: cursorRunes, End: cursorRunes}, - }) } func (state *windowState) positionCompositionWindow() { @@ -762,21 +889,21 @@ func (state *windowState) alignedCaretX(index int) float32 { // compositionTarget is the clause the input method is converting, as runes of the // composition string. -func compositionTarget(context uintptr, value string) (text.Range, bool) { - length, _, _ := getCompositionString.Call(context, compositionAttr, 0, 0) +func compositionTarget(context uintptr, value string, read compositionStringReader) (text.Range, bool) { + length, _, _ := read(context, compositionAttr, 0, 0) if int32(length) <= 0 || length > 1<<16 { return text.Range{}, false } attrs := make([]byte, length) - written, _, _ := getCompositionString.Call(context, compositionAttr, uintptr(unsafe.Pointer(&attrs[0])), length) + written, _, _ := read(context, compositionAttr, uintptr(unsafe.Pointer(&attrs[0])), length) if int32(written) <= 0 || written > length { return text.Range{}, false } return platform.CompositionTarget(attrs[:written], value) } -func compositionText(context uintptr, index uintptr) (string, error) { - lengthValue, _, _ := getCompositionString.Call(context, index, 0, 0) +func compositionText(context uintptr, index uintptr, read compositionStringReader) (string, error) { + lengthValue, _, _ := read(context, index, 0, 0) length := int(int32(lengthValue)) if length < 0 { return "", fmt.Errorf("windows: read IME composition length %d", length) @@ -788,7 +915,7 @@ func compositionText(context uintptr, index uintptr) (string, error) { return "", fmt.Errorf("windows: invalid IME composition length %d", length) } values := make([]uint16, length/2) - writtenValue, _, _ := getCompositionString.Call(context, index, uintptr(unsafe.Pointer(&values[0])), uintptr(length)) + writtenValue, _, _ := read(context, index, uintptr(unsafe.Pointer(&values[0])), uintptr(length)) written := int(int32(writtenValue)) if written < 0 || written > length || written%2 != 0 { return "", fmt.Errorf("windows: invalid IME composition result %d", written) @@ -797,6 +924,7 @@ func compositionText(context uintptr, index uintptr) (string, error) { } func (state *windowState) handleUTF16Character(value uint16) { + state.imeEpoch++ textValue, pending, ready := decodeUTF16Character(state.pendingHighSurrogate, value) state.pendingHighSurrogate = pending if !ready { diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 465ccc477..2965beb63 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -121,13 +121,20 @@ type windowState struct { textRuns []gfx.TextRun captionPress captionPress imeComposing bool + imeCancelling bool // imeDisabled says the window's input-method context is disassociated, and // imeContext holds the context to give back when it returns. A surface that // shows another machine's desktop asks for it (platform.TextInput.DisableIME): // the host's input method would otherwise take the keys that belong to the // machine on the other side. - imeDisabled bool - imeContext uintptr + imeDisabled bool + imeContext uintptr + // imeEpoch invalidates an older message tail when callbacks replace the + // input or reenter native input delivery. + imeEpoch uint64 + // textRevision advances for every installed acknowledgment or input owner; + // an End that merely stops an IMM message tail must not discard its Result. + textRevision uint64 pendingHighSurrogate uint16 accessibility uiaTree pendingKey pendingKey @@ -454,6 +461,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { result = 0 } }() + if state.imeCancelling && (kind == wmIMEStart || kind == wmIMEComposition || kind == wmIMEEnd) { + return 0 + } switch kind { case wmAlwaysOnTop: if state.setAlwaysOnTop(first != 0) { @@ -604,6 +614,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } case wmIMEStart: if state.textEnabled { + state.imeEpoch++ state.imeComposing = true state.positionCompositionWindow() return 0 @@ -619,10 +630,17 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { return result } case wmIMEEnd: + if state.textEnabled { + state.imeEpoch++ + } if state.textEnabled && state.imeComposing { state.imeComposing = false state.imeHasTarget = false - state.handleTextEvent(platform.TextEvent{Kind: platform.TextUnmark}) + event := platform.TextEvent{Kind: platform.TextUnmark} + if state.textState.TentativeComposition { + event.CompositionPhase = text.CompositionCancel + } + state.handleTextEvent(event) return 0 } case wmDeadChar: @@ -955,17 +973,30 @@ func (state *windowState) frame(frame platform.Frame, err error) { // handling it through fail. A caller that presents synchronously (WM_SIZE does) // must not present a frame that was never applied. func (state *windowState) frameWithText(frame platform.Frame, err error, nativeVisualChanged bool) error { + return state.frameWithTextAndCancel(frame, err, nativeVisualChanged, state.cancelNativeComposition) +} + +func (state *windowState) frameWithTextAndCancel(frame platform.Frame, err error, nativeVisualChanged bool, cancelNative func()) error { + if err == nil && state.window == 0 { + return nil + } views := frame.NativeViews if err == nil { state.applyBackdrop() state.applyBorderColor() + var dirty bool + frame, dirty, err = state.prepareFrameWithCancel(frame, nativeVisualChanged, cancelNative) + if err == errSupersededTextFrame { + if state.window != 0 { + state.framePresented() + } + return nil + } defer func() { if state.web != nil && state.ready { state.web.frame(views) } }() - var dirty bool - frame, dirty, err = state.prepareFrame(frame, nativeVisualChanged) if err == nil { err = state.applyFrame(frame) } @@ -997,6 +1028,9 @@ func (state *windowState) frameWithText(frame platform.Frame, err error, nativeV // message loop running with no window to show, and the single-instance claim held // by a process nobody can see. func (state *windowState) destroyed(window uintptr) { + // Native teardown can reenter the dispatcher; retire text callbacks first. + state.ready = false + state.closeText() forgetClipboardListener(window) released := false release := func() { @@ -1022,7 +1056,6 @@ func (state *windowState) destroyed(window uintptr) { } state.accessibility.close() state.renderer.close() - state.closeText() if state.config.Waker != nil && state.config.OnRedraw != nil { state.config.Waker.Unbind() } From 936ceb7eafe3ef7f061a604717b9fa1950e12f07 Mon Sep 17 00:00:00 2001 From: Dean Cen Date: Sun, 15 Nov 2026 21:54:07 +0800 Subject: [PATCH 09/10] fix(update): replace running executables on Windows updates --- update/install_windows.go | 10 +++--- update/install_windows_test.go | 59 +++++++++++++++++++++++++++++++++- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/update/install_windows.go b/update/install_windows.go index dbf6985a1..6fcad9677 100644 --- a/update/install_windows.go +++ b/update/install_windows.go @@ -191,8 +191,8 @@ func installPayload(options InstallOptions, quit func()) error { // startPayloadHelper launches a detached PowerShell script that waits for this // process to exit, copies the staged files over the installation and starts -// the new program. It keeps a copy of every file it replaces until the new -// version has started, and restores them if it fails. +// the new program. It moves every file it replaces to a same-volume backup until +// the new version has started, and restores them if it fails. func startPayloadHelper(parentPID int, payload, installDir, executable string, args []string) error { name, arguments := helperCommand(payloadHelperScript(parentPID, payload, installDir, executable, args)) command := exec.Command(name, arguments...) @@ -215,7 +215,7 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, fmt.Fprintf(&script, "$exe = %s\n", powerShellQuote(executable)) // Enumeration expands DOS aliases, so both substring roots need full names. script.WriteString("$payload = (Get-Item -LiteralPath $payload).FullName\n") - script.WriteString("$backup = Join-Path $env:TEMP ('viva-update-' + [guid]::NewGuid().ToString('N'))\n") + script.WriteString("$backup = Join-Path $dir ('.viva-update-' + [guid]::NewGuid().ToString('N'))\n") script.WriteString("New-Item -ItemType Directory -Force -Path $backup | Out-Null\n") script.WriteString("$backup = (Get-Item -LiteralPath $backup).FullName\n") script.WriteString("$created = New-Object System.Collections.ArrayList\n") @@ -242,7 +242,7 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, script.WriteString(" if (Test-Path -LiteralPath $dest) {\n") script.WriteString(" $bak = Join-Path $backup $rel\n") script.WriteString(" New-Item -ItemType Directory -Force -Path (Split-Path -Parent $bak) | Out-Null\n") - script.WriteString(" Copy-Item -LiteralPath $dest -Destination $bak -Force\n") + script.WriteString(" Move-Item -LiteralPath $dest -Destination $bak -Force\n") script.WriteString(" } else { [void]$created.Add($rel) }\n") script.WriteString(" New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dest) | Out-Null\n") script.WriteString(" Copy-Item -LiteralPath $_.FullName -Destination $dest -Force\n") @@ -254,7 +254,7 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, script.WriteString("\n") script.WriteString(" Start-Sleep -Seconds 2\n") script.WriteString(" if ($p.HasExited -and $p.ExitCode -ne 0) { Restore; Start-Process -FilePath $exe | Out-Null; exit 1 }\n") - script.WriteString("} catch { Restore; exit 1 }\n") + script.WriteString("} catch { Restore; Start-Process -FilePath $exe | Out-Null; exit 1 }\n") script.WriteString("Remove-Item -Recurse -Force $backup -ErrorAction SilentlyContinue\n") script.WriteString("Remove-Item -Recurse -Force $payload -ErrorAction SilentlyContinue\n") script.WriteString("exit 0\n") diff --git a/update/install_windows_test.go b/update/install_windows_test.go index 38fc35fd1..1fc3d3aeb 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -13,6 +13,7 @@ import ( "strings" "syscall" "testing" + "time" "unsafe" ) @@ -235,10 +236,11 @@ func TestPayloadHelperScriptKeepsABackupAndRestores(t *testing.T) { `$payload = 'C:\Temp\O''Brien\payload'`, `$dir = 'C:\Apps\Motty'`, `$exe = 'C:\Apps\Motty\motty.exe'`, - "$backup = Join-Path $env:TEMP", + "$backup = Join-Path $dir", "function Restore", "$created = New-Object System.Collections.ArrayList", "Get-Process -Id $parent", + "Move-Item -LiteralPath $dest -Destination $bak -Force", "Copy-Item -LiteralPath $_.FullName -Destination $dest -Force", "Start-Process -FilePath $exe -PassThru", "$p.HasExited -and $p.ExitCode -ne 0", @@ -352,6 +354,61 @@ func TestPayloadHelperReplacesTheApplication(t *testing.T) { } } +func TestPayloadHelperReplacesARunningExecutable(t *testing.T) { + payload := t.TempDir() + install := t.TempDir() + testExecutable, err := os.Executable() + if err != nil { + t.Fatal(err) + } + copyWindowsFile(t, testExecutable, filepath.Join(install, "app.exe")) + copyWindowsFile(t, systemExecutable(t, "whoami.exe"), filepath.Join(payload, "app.exe")) + + ready := filepath.Join(t.TempDir(), "running") + command := exec.Command(filepath.Join(install, "app.exe"), "-test.run=^TestPayloadHelperRunningProcess$") + command.Env = append(os.Environ(), "VIVA_UPDATE_RUNNING_MARKER="+ready) + if err := command.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = command.Process.Kill() + _, _ = command.Process.Wait() + }) + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(10 * time.Millisecond) { + if _, err := os.Stat(ready); err == nil { + break + } + if time.Now().After(deadline) { + t.Fatal("the old application did not start") + } + } + + script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), nil) + runPayloadHelper(t, script, 0) + got, err := os.ReadFile(filepath.Join(install, "app.exe")) + if err != nil { + t.Fatal(err) + } + want, err := os.ReadFile(systemExecutable(t, "whoami.exe")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Error("the running app.exe was not replaced") + } +} + +func TestPayloadHelperRunningProcess(t *testing.T) { + marker := os.Getenv("VIVA_UPDATE_RUNNING_MARKER") + if marker == "" { + return + } + if err := os.WriteFile(marker, []byte("running"), 0o600); err != nil { + os.Exit(2) + } + time.Sleep(time.Minute) +} + func TestPayloadHelperRollsBackAFailedStart(t *testing.T) { payload := t.TempDir() install := t.TempDir() From 04e87c9b944b72839b9150fdb238d50615b1e755 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sun, 15 Nov 2026 06:11:50 -0800 Subject: [PATCH 10/10] fix(ui): retain configured disclosure spacing after upstream cleanup --- ui/tree.go | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/ui/tree.go b/ui/tree.go index 3d85eb8dc..ea1a035aa 100644 --- a/ui/tree.go +++ b/ui/tree.go @@ -209,15 +209,6 @@ func (s *TreeState) indent(theme *Theme) float32 { return 16 * theme.Metrics.ControlHeight / 32 } -// disclosureSlot is the column a branch spends before its content, in step with the -// component that draws the arrow. -func (s *TreeState) disclosureSlot() float32 { - if s.Disclosure != nil && s.Disclosure.Slot > 0 { - return s.Disclosure.Slot - } - return 24 -} - // row declares row i: the row element, painted by components.Tree, holding what // the caller declares after the chevron. func (s *TreeState) row(i int, rowBox Box) { @@ -243,7 +234,11 @@ func (s *TreeState) row(i int, rowBox Box) { theme := &f.theme left := float32(item.Depth) * s.indent(theme) if node.Branch { - left += s.disclosureSlot() + slot := float32(24) + if s.Disclosure != nil && s.Disclosure.Slot > 0 { + slot = s.Disclosure.Slot + } + left += slot } rowBox.Children(func() { b := Row(c).Height(s.heightOf(node, theme)).Shrink(0).PadRight(8).PadLeft(left).Gap(theme.Metrics.GapItem).Items(Center).Draw(s.paint)