diff --git a/README.zh-CN.md b/README.zh-CN.md index c643f4e78..431ed7d25 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -133,6 +133,8 @@ go run ./cmd/viva help package # 每个命令和参数 `viva.toml` 严格解码:未知的表或键、重复项、类型错误的值都是错误,并会指出行号。macOS 程序按 `min_system` 编译,而不是按构建机器的 macOS 版本;`package` 会拒绝声称支持的系统比其程序所需更旧的包。签名与公证通过 `--sign-identity` 或 `APPLE_SIGNING_IDENTITY` 加 notarytool 凭据显式开启;`--no-sign` 把它们全部关闭。`--arch amd64` 从任一宿主构建另一种 Darwin 架构:构建保留 cgo 和 Objective-C/Metal 桥,让 clang 产出另一份 Mach-O 切片。每个目标、安装器格式和参数见[构建与打包指南](https://vivaui.dev/zh/docs/build-and-package/)。 +Linux 和 Windows 构建默认关闭 cgo。需要链接自己的 C 或 Rust 库的应用可以使用 `viva build --cgo` 或 `viva package --cgo`,并提供目标 C 编译器与 `CGO_CFLAGS`/`CGO_LDFLAGS`。这些程序必须针对它支持的系统库和最低操作系统版本验证;这个显式开关不提供交叉编译器,也不让原生依赖变得可移植。浏览器构建拒绝 `--cgo`;macOS 仍像以前一样为其系统桥保持 cgo 开启。 + 发布链接是测出来的,不是假设的。`go-toml/v2` 只被 `viva` 命令使用,`purego` 只被 Linux 后端使用,所以两者都不在 macOS 或 Windows 程序里。开发期热重载协议、单实例套接字、PNG 图标解码和 Go 测试运行时都留在发布程序之外(热重载、单实例和 PNG 是可选包;测试运行时则完全不存在),泄漏计数器保留,因为它们每个窗口或驱动只花两个原子量。 静态画布可以通过公开 API 呈现: diff --git a/app/composition_handoff_test.go b/app/composition_handoff_test.go index 00734caa9..ce4916815 100644 --- a/app/composition_handoff_test.go +++ b/app/composition_handoff_test.go @@ -123,6 +123,40 @@ func TestPainterTentativeHandoffRetainsInstalledOwner(t *testing.T) { } } +// A cached provider can hand back a different Editor than the one the +// platform was told about, before the next sync. A native text event arrives +// on the window thread in that window: it belongs to the installed owner, not +// to whatever the last published TextInput now names. +func TestPainterAppliesTextEventsToTheInstalledOwner(t *testing.T) { + installed := text.NewEditor("abc") + other := text.NewEditor("other") + cached := &TextInput{Editor: installed, Bounds: gfx.Rect{Width: 120, Height: 24}, FontSize: 13} + var canvas gfx.Canvas + config := Config{Title: "installed owner", 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}) + } + config.TextInput = func(TextInputContext) *TextInput { return cached } + owner := newTestPainter(t, &canvas, config) + owner.syncTextInput() + if owner.activeEditor != installed || owner.activeText == nil || owner.activeText.Editor != installed { + t.Fatal("the painter did not install the cached editor") + } + // The provider swaps its cached Editor between paints; the platform still + // talks to the installed one. + cached.Editor = other + owner.activeText.Editor = other + if _, err := owner.applyTextEvent(platform.TextEvent{Kind: platform.TextInsert, Text: "x"}); err != nil { + t.Fatal(err) + } + if got := installed.String(); got != "abcx" { + t.Fatalf("installed owner = %q, want the event applied to it", got) + } + if got := other.String(); got != "other" { + t.Fatalf("the swapped-in editor = %q, want it untouched", got) + } +} + func TestPainterCachedCustomHandoffPreservesProviderOwnership(t *testing.T) { first, second := text.NewEditor("first"), text.NewEditor("second") for _, editor := range []*text.Editor{first, second} { diff --git a/app/painter.go b/app/painter.go index adeb6c36b..291c907c8 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1400,15 +1400,23 @@ func (painter *painter) disableTextInput() platform.TextInputUpdate { func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextState, error) { painter.tap.Cancel() active := painter.activeText - if active == nil || active.Editor == nil && active.OnEvent == nil { + // The installed owner is the editor the platform has been told about, not + // whatever the last published TextInput names: a cached provider can hand + // back a different Editor before the next sync. Keep activeText for the + // provider's own state and CopyText. + editor := painter.activeEditor + if editor == nil && active != nil { + editor = active.Editor + } + if active == nil || editor == nil && active.OnEvent == nil { return platform.TextState{}, fmt.Errorf("app: native text event without an active handler") } epoch := painter.textEpoch appEvent := appTextEvent(event) explicit := event.CompositionPhase != text.CompositionNone if explicit { - if active.Editor != nil { - explicit = active.Editor.TentativeCompositionEnabled() + if editor != nil { + explicit = editor.TentativeCompositionEnabled() } else { explicit = active.State.TentativeComposition } @@ -1429,12 +1437,12 @@ func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextS return painter.nativeText.State, nil } var next TextState - if active.Editor != nil { - accepted := appEvent.apply(active.Editor) - if painter.nativeText.Secure && accepted && !active.Editor.TentativeCompositionActive() { - active.Editor.ClearHistory() + if editor != nil { + accepted := appEvent.apply(editor) + if painter.nativeText.Secure && accepted && !editor.TentativeCompositionActive() { + editor.ClearHistory() } - next = TextStateOf(active.Editor) + next = TextStateOf(editor) } else { var err error if next, err = active.OnEvent(appEvent); err != nil { diff --git a/cmd/viva/package_tarball.go b/cmd/viva/package_tarball.go index 54c7b36ad..fafef155c 100644 --- a/cmd/viva/package_tarball.go +++ b/cmd/viva/package_tarball.go @@ -18,24 +18,30 @@ import ( ) // linuxRuntimeDepends are the libraries a Viva program opens at run time with -// dlopen (Vulkan, XCB and Cairo). Nothing in the executable's headers names -// them, so a .deb has to say so itself. -var linuxRuntimeDepends = []string{"libvulkan1", "libxcb1", "libcairo2"} +// dlopen and cannot start without: Vulkan, XCB, Cairo, and the Pango/fontconfig +// stack text rendering needs. Nothing in the executable's headers names them, so +// a .deb has to say so itself. Libraries the backend loads with a fallback (the +// optional XCB extensions and PangoFT2) stay out: requiring them would refuse an +// install on a distribution that keeps a provider out of its enabled repos. +var linuxRuntimeDepends = []string{ + "libvulkan1", "libxcb1", "libcairo2", + "libfontconfig1", "libpango-1.0-0", "libpangocairo-1.0-0", "libglib2.0-0", +} // linuxArchRuntimeDepends are the same libraries under Arch's names. -var linuxArchRuntimeDepends = []string{"vulkan-icd-loader", "libxcb", "cairo"} +var linuxArchRuntimeDepends = []string{ + "vulkan-icd-loader", "libxcb", "cairo", "fontconfig", "pango", "glib2", +} // 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. +// packages provide for the same set. Distribution package names differ; both +// supported targets are 64-bit. These dlopen libraries are invisible to normal ELF +// dependency scanning. GTK, IME, WebKit and the fallback-loaded XCB extensions +// 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)", + "libpangocairo-1.0.so.0()(64bit)", "libgobject-2.0.so.0()(64bit)", } // linuxApplication describes the application for the Debian and RPM packages: diff --git a/cmd/viva/package_tarball_test.go b/cmd/viva/package_tarball_test.go index 58d28979a..8c12a1723 100644 --- a/cmd/viva/package_tarball_test.go +++ b/cmd/viva/package_tarball_test.go @@ -5,12 +5,14 @@ import ( "bytes" "compress/gzip" "crypto/sha256" + "encoding/binary" "encoding/hex" "fmt" "io" "os" "os/exec" "path/filepath" + "slices" "strings" "testing" ) @@ -163,7 +165,7 @@ func TestPackageLinuxMakesADeb(t *testing.T) { text := string(control["./control"]) for _, want := range []string{ "Package: fixture-notes\n", "Version: 2.0.1\n", "Architecture: amd64\n", "Maintainer: Ann Lee \n", - "Depends: libvulkan1, libxcb1, libcairo2, libfoo1 (>= 1.2)\n", "Homepage: https://example.com/notes\n", "Description: Takes notes\n", + "Depends: libvulkan1, libxcb1, libcairo2, libfontconfig1, libpango-1.0-0, libpangocairo-1.0-0, libglib2.0-0, libfoo1 (>= 1.2)\n", "Homepage: https://example.com/notes\n", "Description: Takes notes\n", } { if !strings.Contains(text, want) { t.Errorf("control lacks %q:\n%s", want, text) @@ -288,24 +290,92 @@ func TestPackageLinuxRPMDeclaresRuntimeLibraries(t *testing.T) { if err != nil { t.Fatal(err) } + requires := rpmRequiredCapabilities(t, data) 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", + "libpango-1.0.so.0", "libpangocairo-1.0.so.0", "libgobject-2.0.so.0", + } { + capability := library + "()(64bit)" + if !slices.Contains(requires, capability) { + t.Errorf("RPM lacks runtime requirement %s, has %v", capability, requires) + } + } + for _, library := range []string{ + "libpangoft2-1.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 slices.Contains(requires, capability) { + t.Errorf("RPM hard-requires %s, which the backend loads with a fallback", capability) } } - if bytes.Contains(data, []byte("libfoo1 (>= 1.2)")) { + if slices.Contains(requires, "libfoo1 (>= 1.2)") { t.Fatal("RPM contains a Debian-only manifest dependency") } }) } } +// rpmRequiredCapabilities reads RPMTAG_REQUIRENAME from an RPM's main header. +// Grepping the whole file for the capability strings would also match the +// payload or a description, so the test could pass after the requires moved or +// were encoded differently. +func rpmRequiredCapabilities(t *testing.T, data []byte) []string { + t.Helper() + const ( + leadSize = 96 + headerMagic = 0x8eade801 + stringArrayTp = 8 + requireName = 1049 + ) + if len(data) < leadSize { + t.Fatal("the rpm is shorter than its lead") + } + offset := leadSize + // The signature header, padded to the eight-byte boundary the main header + // starts on. + if len(data) < offset+16 { + t.Fatal("the rpm has no signature header") + } + index := int(binary.BigEndian.Uint32(data[offset+8:])) + store := int(binary.BigEndian.Uint32(data[offset+12:])) + offset = (offset + 16 + index*16 + store + 7) &^ 7 + if len(data) < offset+16 || binary.BigEndian.Uint32(data[offset:]) != headerMagic { + t.Fatal("the rpm has no main header") + } + entries := int(binary.BigEndian.Uint32(data[offset+8:])) + storeSize := int(binary.BigEndian.Uint32(data[offset+12:])) + indexStart := offset + 16 + storeStart := indexStart + entries*16 + if storeStart+storeSize > len(data) { + t.Fatal("the rpm header runs past the file") + } + for entry := 0; entry < entries; entry++ { + at := indexStart + entry*16 + tag := binary.BigEndian.Uint32(data[at:]) + if tag != requireName { + continue + } + if kind := binary.BigEndian.Uint32(data[at+4:]); kind != stringArrayTp { + t.Fatalf("REQUIRENAME has type %d, want a string array", kind) + } + count := int(binary.BigEndian.Uint32(data[at+12:])) + position := storeStart + int(binary.BigEndian.Uint32(data[at+8:])) + names := make([]string, 0, count) + for range count { + end := bytes.IndexByte(data[position:storeStart+storeSize], 0) + if end < 0 { + t.Fatal("REQUIRENAME holds an unterminated string") + } + names = append(names, string(data[position:position+end])) + position += end + 1 + } + return names + } + t.Fatal("the rpm declares no REQUIRENAME tag") + return nil +} + func TestPackageLinuxFailures(t *testing.T) { for _, test := range []struct { name, toml string @@ -375,7 +445,7 @@ func TestPackageLinuxRefusesAFileAsOutput(t *testing.T) { func TestDebDepends(t *testing.T) { got := strings.Join(debDepends([]string{"libcairo2 (>= 1.16)", "foo"}), ", ") - if got != "libvulkan1, libxcb1, libcairo2 (>= 1.16), foo" { + if got != "libvulkan1, libxcb1, libfontconfig1, libpango-1.0-0, libpangocairo-1.0-0, libglib2.0-0, libcairo2 (>= 1.16), foo" { t.Errorf("depends = %q", got) } } @@ -441,7 +511,7 @@ func TestPackageLinuxMakesAPKGBUILD(t *testing.T) { "pkgname='fixture-notes-bin'", "pkgver='2.0.1'", "arch=('x86_64')", - "depends=('vulkan-icd-loader' 'libxcb>=1.16' 'cairo' 'extra-lib')", + "depends=('vulkan-icd-loader' 'fontconfig' 'pango' 'glib2' 'libxcb>=1.16' 'cairo' 'extra-lib')", "source=('fixture-notes-2.0.1-linux-amd64.tar.gz')", "sha256sums=('" + hex.EncodeToString(digest[:]) + "')", "_icon_size=256", diff --git a/internal/platform/linux/ime_linux.go b/internal/platform/linux/ime_linux.go index 53ada4a52..dd0ab89f3 100644 --- a/internal/platform/linux/ime_linux.go +++ b/internal/platform/linux/ime_linux.go @@ -191,6 +191,9 @@ func (ime *linuxIME) sync() { // 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 + // Retire before settling: the settlement is delivered through + // the router, and a reentrant sync must not find the session it + // just retired still current. ime.retire() if keep { ime.apply(platform.TextEvent{Kind: platform.TextUnmark, CompositionPhase: text.CompositionCommit}) diff --git a/internal/platform/linux/ime_linux_test.go b/internal/platform/linux/ime_linux_test.go index f348eda44..e7c91f359 100644 --- a/internal/platform/linux/ime_linux_test.go +++ b/internal/platform/linux/ime_linux_test.go @@ -106,8 +106,12 @@ func newIMEHarness(t testing.TB) *imeHarness { _, _, err := harness.input.prepare(frame) return err } + // ibusTried keeps a present() that defers sync from dialing the host's + // daemon: these tests are about the state machine, and a machine with a + // reachable IBus address would otherwise get a fresh native context in the + // middle of an assertion. harness.ime = &linuxIME{ - app: &linuxApplication{}, text: harness.input, router: router, context: harness.context, + app: &linuxApplication{ibusTried: true}, text: harness.input, router: router, context: harness.context, origin: func() (int32, int32) { return harness.origin[0], harness.origin[1] }, } router.ime = harness.ime diff --git a/internal/platform/linux/ime_retirement_linux_test.go b/internal/platform/linux/ime_retirement_linux_test.go index 50cf66e3c..074923053 100644 --- a/internal/platform/linux/ime_retirement_linux_test.go +++ b/internal/platform/linux/ime_retirement_linux_test.go @@ -1,6 +1,7 @@ package linux import ( + "errors" "os" "testing" @@ -31,7 +32,11 @@ func TestIBusTentativeUnsupportedResetSettlesEditorBeforeRetirement(t *testing.T if !h.ime.composing() { t.Fatal("native session did not start") } + settled := len(h.events) h.ime.setFocused(false) + if len(h.events) != settled+1 { + t.Fatalf("retirement settled %d events, want exactly one", len(h.events)-settled) + } 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") } @@ -59,6 +64,25 @@ func TestIBusTentativeUnsupportedResetSettlesEditorBeforeRetirement(t *testing.T } } +// A Reset that crosses an owner change must not settle the retired session's +// text into whatever now owns the field: sync re-checks the context, epoch and +// owner after a failed reset. +func TestRetirementKeepsSettlementWhenResetCrossesAnOwnerChange(t *testing.T) { + h := newTentativeIMEHarness(t) + h.preedit(t, nativeMode("ni", ibus.PreeditModeClear)) + before := len(h.events) + h.context.err = errors.New("reset failed") + h.context.onCall = func(name string) { + if name == "Reset" { + h.ime.epoch++ + } + } + h.ime.setFocused(false) + if len(h.events) != before || h.ime.context == nil { + t.Fatalf("a settlement crossed an owner change: events %d -> %d, context live=%t", before, len(h.events), h.ime.context != nil) + } +} + func TestNativeIBusUnsupportedModeRetirement(t *testing.T) { if os.Getenv("VIVA_IBUS_NATIVE") != "1" { t.Skip("native retirement requires a private input-method daemon") diff --git a/internal/platform/windows/composition_events_windows_test.go b/internal/platform/windows/composition_events_windows_test.go index 74949a23d..267ab762a 100644 --- a/internal/platform/windows/composition_events_windows_test.go +++ b/internal/platform/windows/composition_events_windows_test.go @@ -74,6 +74,56 @@ func TestCompositionIMEEndPreservesOptInAndLegacyBoundaries(t *testing.T) { } } +// Losing the keyboard settles the live composition the way WM_IME_ENDCOMPOSITION +// does, and a native end that arrives afterwards delivers nothing more. +func TestCompositionKillFocusSettlesTheLiveComposition(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) + state := &windowState{ready: true, textEnabled: true, imeComposing: true, imeHasTarget: 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 + } + const handle = ^uintptr(0) + previous := active.Load() + windowStates.Store(handle, state) + t.Cleanup(func() { windowStates.Delete(handle); active.Store(previous) }) + windowProc(handle, wmKillFocus, 0, 0) + if len(events) != 1 || state.imeComposing || state.imeHasTarget { + t.Fatalf("focus loss delivery: events=%+v composing=%v target=%v", events, state.imeComposing, state.imeHasTarget) + } + wantPhase, wantText := text.CompositionNone, "axc" + if enabled { + wantPhase, wantText = text.CompositionCancel, "ac" + } + if events[0].CompositionPhase != wantPhase || editor.String() != wantText { + t.Fatalf("focus loss 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("a native end after focus loss delivered another edit") + } + }) + } +} + func compositionMessageWindow(t *testing.T, editor *text.Editor) (*windowState, *[]platform.TextEvent) { t.Helper() runtime.LockOSThread() @@ -81,7 +131,7 @@ func compositionMessageWindow(t *testing.T, editor *text.Editor) (*windowState, 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.Skipf("no graphics device for the native message surface: %v", err) } t.Cleanup(func() { state.stopCaretTimer() diff --git a/internal/platform/windows/ime_windows.go b/internal/platform/windows/ime_windows.go index ab806854e..b846b079d 100644 --- a/internal/platform/windows/ime_windows.go +++ b/internal/platform/windows/ime_windows.go @@ -111,6 +111,19 @@ func (state *windowState) initializeText() error { return state.updateTextVisuals() } +// endIMEComposition settles the live native composition the way an IME end +// does: the flags go first, then exactly one Unmark, or a Cancel when the +// composition was tentative. A later native end finds nothing to settle. +func (state *windowState) endIMEComposition() { + state.imeComposing = false + state.imeHasTarget = false + event := platform.TextEvent{Kind: platform.TextUnmark} + if state.textState.TentativeComposition { + event.CompositionPhase = text.CompositionCancel + } + state.handleTextEvent(event) +} + func (state *windowState) closeText() { state.imeEpoch++ state.textRevision++ diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 98fa630f5..03dcc92d6 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -639,13 +639,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { state.imeEpoch++ } if state.textEnabled && state.imeComposing { - state.imeComposing = false - state.imeHasTarget = false - event := platform.TextEvent{Kind: platform.TextUnmark} - if state.textState.TentativeComposition { - event.CompositionPhase = text.CompositionCancel - } - state.handleTextEvent(event) + state.endIMEComposition() return 0 } case wmDeadChar: @@ -872,6 +866,14 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } state.captionPress.end() if kind == wmKillFocus { + // Windows does not promise WM_IME_ENDCOMPOSITION once another + // window takes the keyboard, and the phase emission and WM_CHAR + // gate depend on the composition flags: settle it here as that + // message would, so a later native end is a no-op. + if state.textEnabled && state.imeComposing { + state.imeEpoch++ + state.endIMEComposition() + } state.focused = false state.syncShortcutHook() state.textDragging = false diff --git a/text/editor.go b/text/editor.go index 33d53caf3..b7f52b3a0 100644 --- a/text/editor.go +++ b/text/editor.go @@ -286,6 +286,9 @@ func (editor *Editor) Insert(value string) { } editor.collapse(caret) editor.composing = false + // Release the live composition's bookkeeping before recording the edit: + // record opens the next undo unit, and the composition's history has to + // close in the unit it was typed into. editor.releaseCompositionHistory() kind := editInsert if wasComposing { diff --git a/text/lf_labels_composition.go b/text/lf_labels_composition.go index ca24c8ad4..5555a6bbe 100644 --- a/text/lf_labels_composition.go +++ b/text/lf_labels_composition.go @@ -41,7 +41,10 @@ func ensureLFLabelHistoryOwned(state *lfLabelState) { func compositionLFLabelEdits(state *lfLabelState, previous *rune) []lfLabelEdit { composition := &state.composition - // A save point can split a live composition into another undo unit. + // A save point can split a live composition into another undo unit. A nil + // previous is how appendHistory says it starts a new one: a save point, + // Paste, or BreakUndoGroup followed by an insertion all arrive here that + // way, so the unit's original labels are captured afresh. if !composition.recorded || previous == nil { composition.prefix = composition.history[previous].edits composition.unitOriginal = nil diff --git a/ui/list.go b/ui/list.go index 086c809a4..b46661755 100644 --- a/ui/list.go +++ b/ui/list.go @@ -416,9 +416,15 @@ func (s *ListState) RowHeightAt(i int) float32 { return s.rowHeight(i) } // RowID is the identity of visible row i as the last paint named it, by Key when // one is set: the target to give the focus (Canvas.RequestFocus), to look up in a // pointer event or to find among the hits. It is the zero ID before the list has -// been declared. A TreeState has its own RowID, since its rows are named in the -// tree's scope. -func (s *ListState) RowID(i int) gfx.ID { return s.list.rows.At(s.key(i)) } +// been declared, and for a row the list has not declared, so that Selected() can +// be passed before anything is chosen. A TreeState has its own RowID, since its +// rows are named in the tree's scope. +func (s *ListState) RowID(i int) gfx.ID { + if i < 0 || i >= s.list.n { + return gfx.ID{} + } + return s.list.rows.At(s.key(i)) +} // pinnedHeightFor is the height of the header that stays at the top of the list // above row, which is not itself a header: what a row has to clear to be seen. diff --git a/ui/list_test.go b/ui/list_test.go index 1f246b533..b336777c7 100644 --- a/ui/list_test.go +++ b/ui/list_test.go @@ -1,6 +1,7 @@ package ui_test import ( + "fmt" "math" "strconv" "strings" @@ -388,11 +389,22 @@ func TestListKeysAreItemNumbers(t *testing.T) { } } + if id := state.RowID(-1); !id.IsZero() { + t.Errorf("RowID(-1) = %v, want no row", id) + } + if id := state.RowID(len(names)); !id.IsZero() { + t.Errorf("RowID(len) = %v, want no row", id) + } for _, first := range []int{math.MaxInt32 + 1, -len(names)} { func() { defer func() { - if recover() == nil { + recovered := recover() + if recovered == nil { t.Errorf("rows keyed from %d did not panic", first) + return + } + if message := fmt.Sprint(recovered); !strings.Contains(message, "outside 0 to 2^31-1") { + t.Errorf("rows keyed from %d panicked with %q, want the key range named", first, message) } }() state := ui.ListState{Key: func(i int) int { return first + i }} diff --git a/ui/tree.go b/ui/tree.go index ea1a035aa..dda4e31ce 100644 --- a/ui/tree.go +++ b/ui/tree.go @@ -180,13 +180,24 @@ func Tree(c C, state *TreeState, n int, label func(i int) string, content func(i // RowID is the identity of visible row i as the last paint named it, by Key when // one is set: the target to give the focus (Canvas.RequestFocus), to look up in a // pointer event or to find among the hits. It is the zero ID before the tree has -// been declared. -func (s *TreeState) RowID(i int) gfx.ID { return s.rows.At(s.key(i)) } +// been declared, and for a row the tree has not declared. +func (s *TreeState) RowID(i int) gfx.ID { + if i < 0 || i >= s.list.n { + return gfx.ID{} + } + return s.rows.At(s.key(i)) +} // DisclosureID is the identity of the chevron of branch row i, which opens and -// closes it: the zero ID before the tree has been declared. A row that is not a -// branch has no chevron, and no hit is declared at this ID. -func (s *TreeState) DisclosureID(i int) gfx.ID { return s.chevrons.At(s.key(i)) } +// closes it: the zero ID before the tree has been declared, and for a row the +// tree has not declared. A row that is not a branch has no chevron, and no hit is +// declared at this ID. +func (s *TreeState) DisclosureID(i int) gfx.ID { + if i < 0 || i >= s.list.n { + return gfx.ID{} + } + return s.chevrons.At(s.key(i)) +} func (s *TreeState) rowHeight(theme *Theme) float32 { if s.RowHeight > 0 { diff --git a/ui/tree_test.go b/ui/tree_test.go index 29d2990fc..2c83f86b7 100644 --- a/ui/tree_test.go +++ b/ui/tree_test.go @@ -3,6 +3,7 @@ package ui_test import ( "fmt" "math" + "strings" "testing" "time" @@ -108,9 +109,13 @@ 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 { + recovered := recover() + if recovered == nil { t.Fatal("a Tree whose rows are keyed past 2^31-1 did not panic") } + if message := fmt.Sprint(recovered); !strings.Contains(message, "outside 0 to 2^31-1") { + t.Fatalf("a Tree keyed past 2^31-1 panicked with %q, want the key range named", message) + } }() drawPage(ui.NewPage(ui.PageConfig{Theme: &pageTheme}), benchCanvas(), m.page) } diff --git a/update/install.go b/update/install.go index dd764f61c..49f66a196 100644 --- a/update/install.go +++ b/update/install.go @@ -38,12 +38,12 @@ type InstallOptions struct { // Payload is set. Artifact string // Payload is a new application the caller already made with PatchReader.Apply: - // the staged .app on macOS, or the staged executable on Linux. On macOS the - // directory's own name does not matter, so the one ApplyPatch returns can be - // passed as it is: the copy takes the running bundle's name. Install - // replaces the running application with it exactly as it would with an - // unpacked archive, running the same checks. Windows has no patch support, - // so a payload there reports ErrUnsupported. + // the staged .app on macOS, a directory of the installation's files on + // Windows, or the staged executable on Linux. On macOS the directory's own + // name does not matter, so the one ApplyPatch returns can be passed as it + // is: the copy takes the running bundle's name. Install replaces the running + // application with it exactly as it would with an unpacked archive, running + // the same checks. Payload string // Asset is the archive it came from. Its Format tells Install how to unpack // it, and the format must suit the running platform. diff --git a/update/install_windows.go b/update/install_windows.go index 6fcad9677..a39ca3a80 100644 --- a/update/install_windows.go +++ b/update/install_windows.go @@ -216,36 +216,58 @@ func payloadHelperScript(parentPID int, payload, installDir, executable string, // 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 $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") + script.WriteString("$temps = New-Object System.Collections.ArrayList\n") script.WriteString("function Restore {\n") + // Best effort: one locked file must not keep the old version from being + // started, and the relaunch is what makes a failed update recoverable. script.WriteString(" if (Test-Path -LiteralPath $backup) {\n") script.WriteString(" Get-ChildItem -LiteralPath $backup -Recurse -File | ForEach-Object {\n") script.WriteString(" $rel = $_.FullName.Substring($backup.Length).TrimStart('\\')\n") script.WriteString(" $dest = Join-Path $dir $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") + script.WriteString(" New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dest) -ErrorAction SilentlyContinue | Out-Null\n") + script.WriteString(" Copy-Item -LiteralPath $_.FullName -Destination $dest -Force -ErrorAction SilentlyContinue\n") script.WriteString(" }\n }\n") script.WriteString(" foreach ($rel in $created) { Remove-Item -LiteralPath (Join-Path $dir $rel) -Force -ErrorAction SilentlyContinue }\n") + script.WriteString(" foreach ($tmp in $temps) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }\n") script.WriteString("}\n") + // The relaunch keeps the arguments the program was started with, so a test + // binary starts its own case again rather than a whole suite. + script.WriteString("function Launch {\n") + script.WriteString(" Start-Process -FilePath $exe") + if len(args) > 0 { + fmt.Fprintf(&script, " -ArgumentList %s", powerShellArgumentList(args)) + } + script.WriteString("\n}\n") script.WriteString("$alive = $true\n") script.WriteString("for ($i = 0; $i -lt 60; $i++) {\n") script.WriteString(" if (-not (Get-Process -Id $parent -ErrorAction SilentlyContinue)) { $alive = $false; break }\n") script.WriteString(" Start-Sleep -Seconds 1\n") script.WriteString("}\n") - script.WriteString("if ($alive) { Remove-Item -Recurse -Force $backup -ErrorAction SilentlyContinue; exit 1 }\n") + script.WriteString("if ($alive) { exit 1 }\n") script.WriteString("try {\n") + // A backup a previous update could not remove (its old executable was still + // held) would otherwise stay in the install directory for good: the name is + // a fresh GUID each time. + script.WriteString(" Get-ChildItem -LiteralPath $dir -Directory -Filter '.viva-update-*' -ErrorAction SilentlyContinue | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }\n") + script.WriteString(" New-Item -ItemType Directory -Force -Path $backup | Out-Null\n") + script.WriteString(" $backup = (Get-Item -LiteralPath $backup).FullName\n") script.WriteString(" Get-ChildItem -LiteralPath $payload -Recurse -File | ForEach-Object {\n") script.WriteString(" $rel = $_.FullName.Substring($payload.Length).TrimStart('\\')\n") script.WriteString(" $dest = Join-Path $dir $rel\n") + script.WriteString(" $incoming = Join-Path (Split-Path -Parent $dest) ('.viva-update-incoming-' + [guid]::NewGuid().ToString('N') + '.tmp')\n") + script.WriteString(" [void]$temps.Add($incoming)\n") + script.WriteString(" New-Item -ItemType Directory -Force -Path (Split-Path -Parent $dest) | Out-Null\n") + // Copy beside the destination, then rename: the old file is moved aside and + // the new one put in its place with renames, so no copy happens while the + // installed executable is missing. + script.WriteString(" Copy-Item -LiteralPath $_.FullName -Destination $incoming -Force\n") 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(" 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") + script.WriteString(" Move-Item -LiteralPath $incoming -Destination $dest -Force\n") script.WriteString(" }\n") script.WriteString(" $p = Start-Process -FilePath $exe -PassThru") if len(args) > 0 { @@ -253,8 +275,8 @@ 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; Start-Process -FilePath $exe | Out-Null; exit 1 }\n") + script.WriteString(" if ($p.HasExited -and $p.ExitCode -ne 0) { Restore; Launch; exit 1 }\n") + script.WriteString("} catch { Restore; Launch; 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 1fc3d3aeb..0bf2681ff 100644 --- a/update/install_windows_test.go +++ b/update/install_windows_test.go @@ -244,7 +244,10 @@ func TestPayloadHelperScriptKeepsABackupAndRestores(t *testing.T) { "Copy-Item -LiteralPath $_.FullName -Destination $dest -Force", "Start-Process -FilePath $exe -PassThru", "$p.HasExited -and $p.ExitCode -ne 0", - "Restore; Start-Process -FilePath $exe", + "function Launch {", + "Start-Process -FilePath $exe -ArgumentList", + "{ Restore; Launch; exit 1 }", + "} catch { Restore; Launch; exit 1 }", "Remove-Item -Recurse -Force $payload", "exit 0", } { @@ -333,8 +336,24 @@ func TestPayloadHelperReplacesTheApplication(t *testing.T) { if err := os.WriteFile(filepath.Join(payload, "new.dll"), []byte("new"), 0o644); err != nil { t.Fatal(err) } + // A backup the previous update could not delete, because the old program or + // one of its loaded DLLs was still held, must not stay in the install + // directory for good. + stale := filepath.Join(install, ".viva-update-previous") + if err := os.MkdirAll(stale, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(stale, "app.exe"), []byte("stale"), 0o644); err != nil { + t.Fatal(err) + } script := payloadHelperScript(999999, payload, install, filepath.Join(install, "app.exe"), nil) runPayloadHelper(t, script, 0) + if _, err := os.Stat(stale); !os.IsNotExist(err) { + t.Errorf("a previous update's backup survived the next update: %v", err) + } + if left, err := filepath.Glob(filepath.Join(install, ".viva-update-*")); err != nil || len(left) != 0 { + t.Errorf("backups left in the install directory: %v, %v", left, err) + } got, err := os.ReadFile(filepath.Join(install, "app.exe")) if err != nil { t.Fatal(err)